private async Task AddUsers(IMongoDatabase db) { var users = new MongoRepository <User>(db); var emailIndex = Builders <User> .IndexKeys; var createIndexModel = new CreateIndexModel <User>(emailIndex.Ascending(x => x.Email)); users.Collection.Indexes.CreateOneAsync(createIndexModel).Wait(); var admin = new User() { Name = "Admin user", Email = "*****@*****.**", HashedPassword = PasswordHash.CreateHash("admin!") }; admin.Roles.Add(RoleManager.Admin.Name); await users.Add(admin); var guest = new User() { Name = "Guest", Email = "*****@*****.**", HashedPassword = PasswordHash.CreateHash("guest!") }; guest.Roles.Add(RoleManager.Guest.Name); await users.Add(guest); }
public List <PersistencyTenant> LoadPersistedTenants() { var repoTenants = _repo.Where(t => t.ExpireDate >= DateTime.UtcNow).ToList(); if (repoTenants.Count == 0) { _repo.Add(new PersistencyTenant { TenantId = "public-dev", TenantToken = "", ExpireDate = DateTime.UtcNow.AddYears(3) }); _repo.Add(new PersistencyTenant { TenantId = "public-qa", TenantToken = "", ExpireDate = DateTime.UtcNow.AddYears(3) }); _repo.Add(new PersistencyTenant { TenantId = "public-production", TenantToken = "", ExpireDate = DateTime.UtcNow.AddYears(3) }); repoTenants = _repo.Where(t => t.ExpireDate >= DateTime.UtcNow).ToList(); } return(repoTenants); }
private static void EnsureDefaultDevicesAreInit() { var devices = new MongoRepository <IosDevice>(); if (!devices.Any(d => d.Id == "092bb6b72e9b0067c86260d47b6eda05f7d43429")) { devices.Add(new IosDevice { Id = "092bb6b72e9b0067c86260d47b6eda05f7d43429", Name = "MK Support" }); } if (!devices.Any(d => d.Id == "0993f067aa9743a27cf42bce41b00e8ee7c64f97")) { devices.Add(new IosDevice { Id = "0993f067aa9743a27cf42bce41b00e8ee7c64f97", Name = "MK Support 2 - Denis" }); } if (!devices.Any(d => d.Id == "b6dc4dc7c54b9930f634b22cc1bdd8f846651738")) { devices.Add(new IosDevice { Id = "b6dc4dc7c54b9930f634b22cc1bdd8f846651738", Name = "MK Chris P" }); } if (!devices.Any(d => d.Id == "2e00e12d970a3be9423369484fdd18f01235c400")) { devices.Add(new IosDevice { Id = "2e00e12d970a3be9423369484fdd18f01235c400", Name = "apcurium Alex P" }); } }
public void CustomerMasterRepositoryTest002_CreateFindDeleteSync_ExpectNoExceptions() { if (repo.Count() > 0) { repo.DeleteAll(); } Customer entity = new Customer("CustomerMasterRepositoryTest002_cname", "1-800-start"); repo.Add(entity); long newCount = repo.Count(); Assert.Equal(1, newCount); var fetch = repo.GetByEntityId(entity.entityid); Assert.NotNull(fetch); // Assert.Equal(fetch,entity); // Test search API var searchresult = repo.Get(e => e.phone == "1-800-start"); Assert.Equal(1, searchresult.Count); // Test Update API entity.phone = "1-800-updated"; repo.Update(entity); Assert.Equal(1, (repo.Get(e => e.phone == "1-800-updated")).Count); repo.Delete(entity.entityid); Assert.Throws <Exception>(() => fetch = repo.GetByEntityId(entity.entityid)); }
public void Add_Normal_IsTrue() { var log = new Logs { Project = "misapi2018", HostId = "192.168.4.144:8008", LogName = "CatchErrorLog", Level = Level.Debug, UserId = 58988, Url = "http://misapi2018ali.517api.cn:8110/api/House/GetHouse_List_V1", RawUrl = "/api/House/GetHouse_List_V1", UrlReferrer = "", IP = "175.161.71.161, 111.202.96.71", OtherMsg = new Dictionary <string, string>() { { "content-type", "application/json; charset=utf-8" }, { "method", "post" } }, Msg = "Add于:" + DateTime.Now.ToString() }; var totalCount1 = MongoRepository.Count <Logs>(w => w.LogName == log.LogName); for (int i = 0; i < 100 && totalCount1 == 0; i++) { var addresult = MongoRepository.Add(log); log.Id = Guid.NewGuid().ToString("N"); log.UserId += 1; log.CreateTime = DateTime.Now; } var totalCount2 = MongoRepository.Count <Logs>(w => w.LogName == log.LogName); Assert.AreEqual(totalCount2, 100); }
private DAL() { Configurations = new MongoRepository <ConfigKeyValue, string>(); if (!Configurations.Exists(config => config.Key == "CurrentAccountId")) { Configurations.Add(new ConfigKeyValue { Key = "CurrentAccountId", Value = "0000000000000000" }); } if (!Configurations.Exists(config => config.Key == "CurrentSessionId")) { Configurations.Add(new ConfigKeyValue { Key = "CurrentSessionId", Value = "0000000000000000" }); } Users = new MongoRepository <User, string>(); Accounts = new MongoRepository <Account, string>(); Operations = new MongoRepository <Operation, string>(); Sessions = new MongoRepository <Session, string>(); BankIdToIpMapping = new Dictionary <string, string>(); ReadBankIdToIpMappingFromFile(); }
static void Main(string[] args) { var mongodbClient = new MongoRepository("mongodb://*****:*****@mdb.gshichina.com:5004/geshiimdb"); var phone = mongodbClient.ToList <Phone>(a => a.Type == EGoods.Phone); var computer = mongodbClient.ToList <Computer>(a => a.Type == EGoods.Computer); var shirt = mongodbClient.ToList <Shirt>(a => a.Type == EGoods.Shirt); mongodbClient.Add(new Computer { Weight = 1, IsCanOpen360 = true, Name = "战神" }); mongodbClient.Add(new Phone { IsCan5G = false, Long = 112, Wide = 50, Name = "IphoneX" }); mongodbClient.Add(new Shirt { Color = "Yellow", Name = "战神" }); }
private void EnsureDefaultSettingsAreInit() { var defaultsClient = new Dictionary <string, string> { { "CanChangeServiceUrl", "false" }, { "ErrorLog", "" }, { "ErrorLogEnabled", "false" }, { "FacebookAppId", "134284363380764" }, { "FacebookEnabled", "false" }, { "ServiceUrlTest", "http://services.taxihail.com/taxihaildemo/api/" }, { "TwitterAccessTokenUrl", "https://api.twitter.com/oauth/access_token" }, { "TwitterAuthorizeUrl", "https://api.twitter.com/oauth/authorize" }, { "TwitterCallback", "http://www.taxihail.com/oauth" }, { "TwitterConsumerKey", "3nNkJ5EcI7yyi56ifLSAA" }, { "TwitterConsumerSecret", "Th6nCDTgPiI3JPwHxgm8fQheMaLczUeHHG5liHGZRqs" }, { "TwitterEnabled", "false" }, { "TwitterRequestTokenUrl", "https://api.twitter.com/oauth/request_token" }, { "TaxiHail.Version", "2.0" }, { "Client.CreditCardIsMandatory", "false" } }; var settings = new MongoRepository <DefaultCompanySetting>(); foreach (var defaultSetting in defaultsClient) { var existing = settings.SingleOrDefault(s => s.Id == defaultSetting.Key); if (existing == null) { settings.Add(new DefaultCompanySetting { Id = defaultSetting.Key, Value = defaultSetting.Value, IsClient = true }); } if ((existing != null) && !existing.IsClient) { existing.IsClient = true; settings.Update(existing); } if ((existing != null) && (existing.Value != defaultSetting.Value)) { existing.Value = defaultSetting.Value; settings.Update(existing); } } string path = @"~/assets/DefaultSettings/defaults.json"; if (!File.Exists(path)) { var json = File.ReadAllText(HostingEnvironment.MapPath(path)); var serverSettings = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); foreach (KeyValuePair <string, string> defaultSetting in serverSettings) { var existing = settings.SingleOrDefault(s => s.Id == defaultSetting.Key); if (existing == null) { settings.Add(new DefaultCompanySetting { Id = defaultSetting.Key, Value = defaultSetting.Value, IsClient = false }); } } } }
public static async Task <bool> NovoUsuario(UsuarioModel usuario) { try { await Task.Run(() => _repo.Add <UsuarioModel>(usuario)); return(true); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Post([FromBody] RegistrationViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userIdentity = mapper.Map <ApplicationUser>(model); var result = await userManager.CreateAsync(userIdentity, model.Password); if (!result.Succeeded) { return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState))); } var privateKey = this.nethereumService.GenerateNewPrivateKey(); mongoRepository.Add(new UserInfo() { Username = userIdentity.UserName, PrivateKey = privateKey }); return(new OkObjectResult("Account created")); }
public string AddTwitterHashTag(string hashTag, string boardId) { MongoBoardTwitterHashTag twitteracc = new MongoBoardTwitterHashTag { Id = ObjectId.GenerateNewId(), strId = ObjectId.GenerateNewId().ToString(), Boardid = boardId, Statuscount = string.Empty, Entrydate = DateTime.UtcNow.ToString(), Screenname = hashTag.ToLower(), Twitterprofileid = "tag", Friendscount = string.Empty, Followingscount = string.Empty, Followerscount = string.Empty, Favouritescount = string.Empty, Photosvideos = string.Empty, Url = string.Empty, Tweet = string.Empty, Profileimageurl = "tag" }; MongoRepository mongorepo = new MongoRepository("MongoBoardTwitterHashTag"); MongoBoardTwitterHashTag objTwitterPage = new MongoBoardTwitterHashTag(); var ret = mongorepo.Find <MongoBoardTwitterHashTag>(t => t.Screenname.Equals(hashTag.ToLower())); var task = Task.Run(async() => { return(await ret); }); IList <MongoBoardTwitterHashTag> objTwitterPagelist = task.Result.ToList(); if (objTwitterPagelist.Count() > 0) { return(objTwitterPagelist.First().strId.ToString()); } mongorepo.Add <MongoBoardTwitterHashTag>(twitteracc); new Thread(delegate() { AddTwittertrendingHashTagFeeds(hashTag, twitteracc.strId.ToString(), null); }).Start(); return(twitteracc.strId.ToString()); }
private void CreateGame(HsGameMessage message) { var gameDto = message.Data.ToObject <HSGameDto>(); var gameEntity = Mapper.Map <HSGame>(gameDto); _gameRepository.Add(gameEntity); }
public void FirstDBTest() { using (var db = new MongoRepository<DBStub>()) { db.Add(new DBStub() { Name = "test" }); } }
public static string AddFacebookFeedShareDetail(long userId, string socialProfile, string FacebookPageId, string socialmedia, Helper.Cache _redisCache, Helper.AppSettings _appSettings, Model.DatabaseRepository dbr) { MongoRepository _fbFeedShareRepository = new MongoRepository("FacebookPageFeedShare", _appSettings); Domain.Socioboard.Models.Mongo.FacebookPageFeedShare _facebookfeedsShare = new Domain.Socioboard.Models.Mongo.FacebookPageFeedShare(); _facebookfeedsShare.Id = ObjectId.GenerateNewId(); _facebookfeedsShare.strId = ObjectId.GenerateNewId().ToString(); _facebookfeedsShare.userId = userId; _facebookfeedsShare.pageId = FacebookPageId; _facebookfeedsShare.socialProfiles = socialProfile; _facebookfeedsShare.socialmedia = socialmedia; _facebookfeedsShare.scheduleTime = DateTime.UtcNow; var ret = _fbFeedShareRepository.Find <Domain.Socioboard.Models.Mongo.FacebookPageFeedShare>(t => t.pageId == FacebookPageId && t.socialProfiles == socialProfile); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { _fbFeedShareRepository.Add(_facebookfeedsShare); } return("added successfully"); }
public void UpdatePostsToDb(IEnumerable <MongoFacebookFeed> feedCollections) { foreach (var feed in feedCollections) { try { var mongoDbRepository = new MongoRepository("MongoFacebookFeed"); var getAccountPostDetails = mongoDbRepository.Find <MongoFacebookFeed>(t => t.FeedId == feed.FeedId && t.ProfileId == feed.ProfileId); var matchedCount = Task.Run(async() => await getAccountPostDetails).Result.Count; if (matchedCount < 1) { mongoDbRepository.Add(feed); } else { try { var filter = new BsonDocument("FeedId", feed.FeedId); var update = Builders <BsonDocument> .Update.Set("postType", feed.postType).Set("postingFrom", feed.postingFrom).Set("Likecount", feed.Likecount).Set("Commentcount", feed.Commentcount).Set("_facebookComment", feed._facebookComment); mongoDbRepository.Update <MongoFacebookFeed>(update, filter); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public static void SaveLinkedInCompanyPageFeed(oAuthLinkedIn _oauth, string PageId, long UserId, Helper.AppSettings _appSettings) { List <LinkedinPageUpdate.CompanyPagePosts> objcompanypagepost = Helper.LinkedInHelper.GetLinkedinCompanyPageFeeds(_oauth, PageId); LinkedinCompanyPagePosts lipagepost = new LinkedinCompanyPagePosts(); foreach (var item in objcompanypagepost) { lipagepost.Id = ObjectId.GenerateNewId(); lipagepost.strId = ObjectId.GenerateNewId().ToString(); lipagepost.Posts = item.Posts; lipagepost.PostDate = Convert.ToDateTime(item.PostDate).ToString("yyyy/MM/dd HH:mm:ss"); lipagepost.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); lipagepost.UserId = UserId; lipagepost.Type = item.Type; lipagepost.PostId = item.PostId; lipagepost.UpdateKey = item.UpdateKey; lipagepost.PageId = PageId; lipagepost.PostImageUrl = item.PostImageUrl; lipagepost.Likes = item.Likes; lipagepost.Comments = item.Comments; MongoRepository _CompanyPagePostsRepository = new MongoRepository("LinkedinCompanyPagePosts", _appSettings); var ret = _CompanyPagePostsRepository.Find <Domain.Socioboard.Models.Mongo.LinkedinCompanyPagePosts>(t => t.PostId == lipagepost.PostId); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { _CompanyPagePostsRepository.Add(lipagepost); } } }
public void AddDistricQuantity() { MongoRepository <District> districts = new MongoRepository <District>(); MongoRepository <Age> ages = new MongoRepository <Age>(); MongoRepository <Sex> sexs = new MongoRepository <Sex>(); MongoRepository <Job> jobs = new MongoRepository <Job>(); MongoRepository <DistrictQuantity> districtQuantities = new MongoRepository <DistrictQuantity>(); var year = 2016; Random rnd = new Random(); foreach (var district in districts) { foreach (var age in ages) { foreach (var sex in sexs) { foreach (var job in jobs) { DistrictQuantity item = new DistrictQuantity { DistrictId = district.Id, AgeId = age.Id, SexId = sex.Id, JobId = job.Id, Year = year, Quantity = rnd.Next(1, 50) }; districtQuantities.Add(item); } } } } }
private void ImportCpus() { int[] cpuCores = { 2, 3, 4, 6 }; IRepository<Cpu> cpuRepository = new MongoRepository<Cpu>(this.dbContext); IRepository<Vendor> vendorRepository = new MongoRepository<Vendor>(this.dbContext); var vendorsList = vendorRepository.GetAll().ToList(); textWriter.Write("Importing CPUs"); for (int i = 0; i < 42; i++) { if (i % 2 == 0) { textWriter.Write("."); } int currentCpuCoresCount = cpuCores[RandomUtils.GenerateNumberInRange(0, cpuCores.Length - 1)]; cpuRepository.Add(new Cpu() { Id = ObjectId.GenerateNewId(), Cores = currentCpuCoresCount, Model = RandomUtils.GenerateRandomString(RandomUtils.GenerateNumberInRange(2, 5)), Price = currentCpuCoresCount * RandomUtils.GenerateNumberInRange(100, 120), VendorId = vendorsList[RandomUtils.GenerateNumberInRange(0, vendorsList.Count - 1)].Id }); } textWriter.WriteLine(); }
public bool add_Data(string msg) { var log = new Logs { Project = "misapi2018", HostId = "192.168.4.144:8008", LogName = "FormDeubgeLog", Level = Level.Debug, UserId = 58988, Url = "http://misapi2018ali.517api.cn:8110/api/House/GetHouse_List_V1", RawUrl = "/api/House/GetHouse_List_V1", UrlReferrer = "", IP = "175.161.71.161, 111.202.96.71", OtherMsg = new Dictionary <string, string>() { { "content-type", "application/json; charset=utf-8" }, { "method", "post" }, }, Msg = msg }; var result = mongoRepository.Add(log); var quernLog = mongoRepository.Get <Logs>(w => w.UserId == 58988 && w.LogName == "FormDeubgeLog", o => o.Desc(b => b.CreateTime)); if (quernLog != null) { this.textBox1.Text = $"添加成功:{ quernLog.Msg }"; } else { this.textBox1.Text = $"添加失败"; } return(result); }
public SignResponse SignUp(SignUpCommand command) { if (_recruitersRepository.Exists(rec => rec.Email == command.Email)) { return new SignResponse() { CanSignIn = false } } ; RecruiterEntity newEntity = _recruitersRepository.Add(new RecruiterEntity() { Email = command.Email, Password = command.Password, Gender = Gender.Unknown, RegisterStatus = RecruiterRegisterStatus.Register, SourceType = RecruiterSourceType.System, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, //RegisterStatusHistory = new List<BaseStatusHistory>() { new BaseStatusHistory() { Status = RecruiterRegisterStatus.Register, Date = DateTime.Now } }, FriendlyId = _recruitersRepository.GetNextId <RecruiterEntity>() }); return(new SignResponse() { CanSignIn = true, UserId = newEntity.Id, UserType = CvLocate.Common.EndUserDtoInterface.Enums.UserType.Recruiter }); } #endregion }
//public static string addtwitterContentfeedsdata(string keyword, string userId, Helper.AppSettings _appSettings ) //{ // //MongoRepository mongorepo = new MongoRepository("ContentFeeds", _appSettings); // MongoRepository mongorepo = new MongoRepository("RssNewsContentsFeeds", _appSettings); // bool output = false; // string timeline = TwitterHashTag.TwitterBoardHashTagSearch(keyword, null); // int i = 0; // if (!string.IsNullOrEmpty(timeline) && !timeline.Equals("[]")) // { // foreach (JObject obj in JArray.Parse(timeline)) // { // RssNewsContentsFeeds contentFeedsDet = new RssNewsContentsFeeds(); // // Domain.Socioboard.Models.Mongo.ContentFeeds contentFeedsDet = new Domain.Socioboard.Models.Mongo.ContentFeeds(); // contentFeedsDet.Id = ObjectId.GenerateNewId(); // i++; // try // { // contentFeedsDet.Link = JArray.Parse(obj["entities"]["expanded_url"].ToString())[0]["url"].ToString(); // //contentFeedsDet = JArray.Parse(obj["entities"]["expanded_url"].ToString())[0]["url"].ToString(); // } // catch // { // try // { // //contentFeedsDet.Link = JArray.Parse(obj["entities"]["urls"].ToString())[0]["expanded_url"].ToString(); // contentFeedsDet.Link = JArray.Parse(obj["entities"]["urls"].ToString())[0]["expanded_url"].ToString(); // } // catch (Exception e) // { // } // } // try // { // //contentFeedsDet.Image = JArray.Parse(obj["extended_entities"]["media"].ToString())[0]["media_url"].ToString(); // contentFeedsDet.Image = JArray.Parse(obj["extended_entities"]["media"].ToString())[0]["media_url"].ToString(); // } // catch // { // try // { // contentFeedsDet.Image = JArray.Parse(obj["entities"]["media"].ToString())[0]["media_url"].ToString(); // } // catch (Exception e) // { // } // } // try // { // contentFeedsDet.Title = obj["text"].ToString(); // //contentFeedsDet.Title = obj["text"].ToString(); // } // catch (Exception e) // { // } // try // { // string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy"; // contentFeedsDet.PublishingDate = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact((string)obj["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"))).ToString(); // //contentFeedsDet.CreatedDate = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.ParseExact((string)obj["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"))); // } // catch (Exception e) // { // } // contentFeedsDet.UserId = userId; // contentFeedsDet.keywords = keyword; // // var ret = mongorepo.Find<RssNewsContentsFeeds>(t => t.FeedId == contentFeedsDet.FeedId); // var ret = mongorepo.Find<RssNewsContentsFeeds>(t => t.UserId == userId && t.Image == contentFeedsDet.Image); // var task = Task.Run(async () => // { // return await ret; // }); // int count = task.Result.Count; // if (count < 1) // { // try // { // //mongorepo.Add<RssNewsContentsFeeds>(contentFeedsDet);ContentFeeds // mongorepo.Add<RssNewsContentsFeeds>(contentFeedsDet); // } // catch (Exception e) { } // } // else // { // //return "already data present"; // } // } // return "data successfully added"; // } // output = true; // return output.ToString(); //} public static bool addGplusContentfeedsdata(string keywords, string userId, Helper.AppSettings _appSettings) { MongoRepository mongorepo = new MongoRepository("RssNewsContentsFeeds", _appSettings); bool output = false; try { var discoveryResponse = GplusDiscoverySearchHelper.GooglePlus(keywords, _appSettings.GoogleApiKeyForRssFeed); JObject GplusActivities = JObject.Parse(discoveryResponse); foreach (JObject obj in JArray.Parse(GplusActivities["items"].ToString())) { RssNewsContentsFeeds contentGFeedsDet = new RssNewsContentsFeeds(); contentGFeedsDet.Id = ObjectId.GenerateNewId(); try { foreach (JObject att in JArray.Parse(obj["object"]["attachments"].ToString())) { contentGFeedsDet.Image = att["fullImage"]["url"].ToString(); contentGFeedsDet.Link = att["url"].ToString(); contentGFeedsDet.Title = att["displayName"].ToString(); } } catch { } try { contentGFeedsDet.PublishingDate = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.Parse(obj["published"].ToString())).ToString(); } catch { } contentGFeedsDet.UserId = userId; contentGFeedsDet.keywords = keywords; var ret = mongorepo.Find <RssNewsContentsFeeds>(t => t.Title == contentGFeedsDet.Title); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { try { mongorepo.Add(contentGFeedsDet); output = true; } catch { } } } return(output); } catch { } return(output); }
public void CustomIDTest() { var x = new MongoRepository <CustomIDEntity>(); var xm = new MongoRepositoryManager <CustomIDEntity>(); x.Add(new CustomIDEntity() { Id = "aaa" }); Assert.IsTrue(xm.Exists); Assert.IsInstanceOfType(x.GetById("aaa"), typeof(CustomIDEntity)); Assert.AreEqual("aaa", x.GetById("aaa").Id); x.Delete("aaa"); Assert.AreEqual(0, x.Count()); var y = new MongoRepository <CustomIDEntityCustomCollection>(); var ym = new MongoRepositoryManager <CustomIDEntityCustomCollection>(); y.Add(new CustomIDEntityCustomCollection() { Id = "xyz" }); Assert.IsTrue(ym.Exists); Assert.AreEqual(ym.Name, "MyTestCollection"); Assert.AreEqual(y.CollectionName, "MyTestCollection"); Assert.IsInstanceOfType(y.GetById("xyz"), typeof(CustomIDEntityCustomCollection)); y.Delete("xyz"); Assert.AreEqual(0, y.Count()); }
public void SaveTurn(HSTurnDto turnDto) { var turn = Mapper.Map <HSTurn>(turnDto); MongoRepository <HSTurn> turnRepository = new MongoRepository <HSTurn>(); turnRepository.Add(turn); }
public static Tasks AddTask(TasksViewModel _TasksViewModel, ILogger _logger, Helper.Cache _redisCache, Helper.AppSettings _appSettings) { try { Tasks _Tasks = new Tasks(); _Tasks.Id = ObjectId.GenerateNewId(); _Tasks.strId = ObjectId.GenerateNewId().ToString(); _Tasks.recipientUserId = _TasksViewModel.recipientUserId; _Tasks.senderUserId = _TasksViewModel.senderUserId; _Tasks.groupId = _TasksViewModel.groupId; _Tasks.readStaus = Domain.Socioboard.Enum.ReadStaus.Unread; _Tasks.taskMessage = _TasksViewModel.taskMessage; _Tasks.taskMessageImageUrl = _TasksViewModel.taskMessageImageUrl; _Tasks.taskStatus = Domain.Socioboard.Enum.TaskStatus.Pending; _Tasks.cratedOn = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); _Tasks.completeddOn = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); _Tasks.feedTableType = _TasksViewModel.feedTableType; _Tasks.feedTableId = _TasksViewModel.feedId; MongoRepository mongorepo = new MongoRepository("Tasks", _appSettings); mongorepo.Add <Tasks>(_Tasks); return(_Tasks); } catch (Exception ex) { throw; } }
public void RaspatoryFind() { IRepository ss = new MongoRepository("TestDb", "SystemTest"); ss.Add(this.system); var result = ss.Single(x => (x as SystemApplication).Name.Contains("works")); }
private void InsetTranslation(MongoRepository <Translation> mongoRepository, Translation item, string branch) { //new AddOrReplaceOne(mongoRepository, Log).Execute(item); new SetEnvironmentFromKey(item).Execute(); item.SetNewId(); var predicate = PredicateBuilder.True <Translation> (); predicate = predicate.And(x => x.Environment == item.Environment); if (!string.IsNullOrWhiteSpace(branch)) { predicate = predicate.And(x => x.Branch == branch); } predicate = predicate.And(x => x.Key == item.Key); var existing = mongoRepository.SingleOrDefault(x => x.Key == item.Key && x.Branch == branch); if (existing != null) { if (existing.Equals(item)) { Log.Debug($"the two objects are identical, continuing."); return; } item.Id = existing.Id; Log.Debug($"updateFromOldJson : Key {item.Key} allready exist, updating"); mongoRepository.Update(item); return; } Log.Debug($"updateFromOldJson : adding {item.ToString()}"); mongoRepository.Add(item); }
public static void CriaLogMongo(LogModel log) { using (MongoRepository repo = new MongoRepository()) { repo.Add <LogModel>(log); } }
public string ShareFeed(string fbAccesstoken, string feedId, string pageId, string message, string fbUserId, string fbPageName) { try { var mongoRepository = new MongoRepository("SharethonPagePost"); var link = "https://www.facebook.com/" + pageId + "/posts/" + feedId; var sharethonPagePostCollections = mongoRepository.Find <SharethonPagePost>(t => t.Facebookaccountid.Equals(fbUserId) && t.Facebookpageid.Equals(pageId) && t.PostId.Equals(feedId)); var task = Task.Run(async() => await sharethonPagePostCollections); var count = task.Result.Count; try { if (count < 1) { var pageAccessToken = FacebookApiHelper.GetPageAccessToken(pageId, fbAccesstoken, string.Empty); var response = FacebookApiHelper.PublishPostOnPage(pageAccessToken, pageId, string.Empty, string.Empty, link); var isPublished = response.Contains("id"); if (isPublished) { PageapiHitsCount++; } var objSharethonPagePost = new SharethonPagePost { Id = ObjectId.GenerateNewId(), Facebookaccountid = fbUserId, Facebookpageid = pageId, PostId = feedId, PostedTime = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow), Facebookpagename = fbPageName }; mongoRepository.Add(objSharethonPagePost); return("success"); } } catch (Exception ex) { Console.Write(ex.StackTrace); PageapiHitsCount = PageMaxapiHitsCount; return(string.Empty); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(string.Empty); }
public ITranslation Execute(Translation translation) { SetPredicate(translation); InsureTranslationsCanBeInserted(translation); Log.Debug($"Adding translation: {translation.ToString()}"); _mongoRepository.Add(translation); return(translation); }
public static string AddRssFeed(string TextUrl, long Userid, string profileId, Domain.Socioboard.Enum.SocialProfileType ProfileType, string profileimageurl, string profilename, Model.DatabaseRepository dbr, Helper.AppSettings _appSettings) { int UrlAdded = 0; string RetMsg = string.Empty; MongoRepository _RssRepository = new MongoRepository("Rss", _appSettings); Domain.Socioboard.Models.RssFeedUrl rssobj = new Domain.Socioboard.Models.RssFeedUrl(); rssobj = dbr.FindSingle <Domain.Socioboard.Models.RssFeedUrl>(t => t.ProfileId == profileId && t.rssurl == TextUrl); string rt = ParseFeedUrl(TextUrl, ProfileType, profileId, Userid, profilename, profileimageurl, _appSettings); var ret = _RssRepository.Find <Domain.Socioboard.Models.Mongo.Rss>(t => t.RssFeedUrl.Equals(TextUrl) && t.ProfileId.Contains(profileId) && t.ProfileType == ProfileType && t.UserId.Equals(Userid)); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { if (rt == "ok") { Domain.Socioboard.Models.Mongo.Rss _Rss = new Domain.Socioboard.Models.Mongo.Rss(); _Rss.Id = ObjectId.GenerateNewId(); _Rss.strId = ObjectId.GenerateNewId().ToString(); _Rss.RssFeedUrl = TextUrl; _Rss.ProfileType = ProfileType; _Rss.ProfileId = profileId; _Rss.UserId = Userid; _Rss.ProfileImageUrl = profileimageurl; _Rss.ProfileName = profilename; _Rss.rssFeedUrl = rssobj; _Rss.CreatedOn = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); _RssRepository.Add(_Rss); UrlAdded++; } else { return("Please Fill Correct Url For Feeds"); } } else { } if (UrlAdded == 1) { RetMsg = "Url for " + UrlAdded.ToString() + " account is added"; } else if (UrlAdded > 1) { RetMsg = "Url for " + UrlAdded.ToString() + " accounts is added"; } else { RetMsg = "Url has already added"; } return(RetMsg); }
public ActionResult Create(Caption caption) { try { if (caption.Title != null) { caption.Updated = DateTime.Now; //strip off the AA and set case string user = User.Identity.Name; if (user.Contains("\\")) { user = user.Substring(3).ToLower(); } caption.UpdatedBy = user; caption.Votes = 1; HashSet <string> voters = new HashSet <string>(); voters.Add(user); caption.Voters = voters; captionrepo.Add(caption); //now log it bool logged = logAction("Created Caption " + caption.Key, "Informational"); TempData["flash"] = buildFlash("success", "Caption Created", "Caption has been created"); } else { TempData["flash"] = buildFlash("oops", "Caption NOT Created", "Your caption was blank"); } return(RedirectToAction("CaptionContest", "Template", new { id = caption.Key })); } catch { ViewBag.flash = buildFlash("danger", "Error", "Error Creating Template"); return(View()); } }
public void TestCountOne() { var repository = new MongoRepository<ClassTest>(Configuration.TestCollection); repository.Add(new ClassTest()); var count = repository.Count(); Assert.AreEqual(1, count); }
public Account CreateAccount(string FriendlyName) { Account acc = new Account() { FriendlyName = FriendlyName }; try { accountRepo.Add(acc); } catch (Exception ex) { acc = new Account(); } return(acc); }
public void test_child_collection_match_using_any() { var mongoRepository = new MongoRepository<User>(collection: "UserCollection"); mongoRepository.RemoveAll(); mongoRepository.Linq().ToList().Should().BeEmpty(); var user = new User() { Name = "1", Accounts = new List<Account>() { new Account() { Name = "a1", Prop2 = "p1" } } }; var user2 = new User() { Name = "2", Accounts = new List<Account>() { new Account() { Name = "a2", Prop2 = "p2" } } }; mongoRepository.Add(user); mongoRepository.Add(user2); mongoRepository.Linq().ToList().Should().HaveCount(2); var match = mongoRepository.Linq().SingleOrDefault(x => x.Accounts.Any(a => a.Name == "a1" && a.Prop2 == "p1")); match.Should().NotBeNull(); }
public void Get_WhenObjectId_IsObjectId_ReturnsUser() { //arrange var mongoRepository = new MongoRepository<User>(); var user = new User() { Name = "Get_WhenObjectId_IsObjectId_ReturnsUser" }; user = mongoRepository.Add(user); //act var found = mongoRepository.Get(user.Id); //assert found.Should().NotBeNull(); found.Name.Should().Be(user.Name); found.Id.Should().Be(user.Id); }
public void AddAndUpdateTest() { IRepository<Customer> _customerRepo = new MongoRepository<Customer>(); IRepositoryManager<Customer> _customerMan = new MongoRepositoryManager<Customer>(); Assert.IsFalse(_customerMan.Exists); var customer = new Customer(); customer.FirstName = "Bob"; customer.LastName = "Dillon"; customer.Phone = "0900999899"; customer.Email = "*****@*****.**"; customer.HomeAddress = new Address { Address1 = "North kingdom 15 west", Address2 = "1 north way", PostCode = "40990", City = "George Town", Country = "Alaska" }; _customerRepo.Add(customer); Assert.IsTrue(_customerMan.Exists); Assert.IsNotNull(customer.Id); // fetch it back var alreadyAddedCustomer = _customerRepo.Where(c => c.FirstName == "Bob").Single(); Assert.IsNotNull(alreadyAddedCustomer); Assert.AreEqual(customer.FirstName, alreadyAddedCustomer.FirstName); Assert.AreEqual(customer.HomeAddress.Address1, alreadyAddedCustomer.HomeAddress.Address1); alreadyAddedCustomer.Phone = "10110111"; alreadyAddedCustomer.Email = "*****@*****.**"; _customerRepo.Update(alreadyAddedCustomer); // fetch by id now var updatedCustomer = _customerRepo.GetById(customer.Id); Assert.IsNotNull(updatedCustomer); Assert.AreEqual(alreadyAddedCustomer.Phone, updatedCustomer.Phone); Assert.AreEqual(alreadyAddedCustomer.Email, updatedCustomer.Email); Assert.IsTrue(_customerRepo.Exists(c => c.HomeAddress.Country == "Alaska")); }
public void AddSprint() { var repo = new MongoRepository<Concert>(); var newSprint = new Concert { Artist = new Artist { Name = "Eddie Meduza" } }; repo.Add(newSprint); var sprint = repo.All(c => c.Artist.Name == "Eddie Meduza"); Assert.That(sprint, Is.EqualTo(newSprint)); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); MongoRepository.MongoRepository<Basla> repo = new MongoRepository<Basla>(); repo.DeleteAll(); Basla b = new Basla(); FlowAction a = new FlowAction(); b.SonrakiEleman = a; repo.Add(b); var txxx = repo.Where(t => t.Id != null).ToList(); }
public void TestCountOne() { var repository = new MongoRepository<ClassTest>(Configuration.TestCollection); var classTest = new ClassTest() { IntProperty = 10, ChildClassTests = new List<ChildClassTest>() { new ChildClassTest() {StringProperty = "first string"}, new ChildClassTest() {StringProperty = "second string"} } }; repository.Add(classTest); var count = repository.Count(); Assert.AreEqual(1, count); }
public void GetInstagramFeeds(Domain.Socioboard.Domain.InstagramAccount objInsAccount) { MongoRepository instagarmCommentRepo = new MongoRepository("InstagramComment"); MongoRepository instagramFeedRepo = new MongoRepository("InstagramFeed"); try { GlobusInstagramLib.Instagram.Core.UsersMethods.Users userInstagram = new GlobusInstagramLib.Instagram.Core.UsersMethods.Users(); InstagramResponse<InstagramMedia[]> userinf2 = userInstagram.CurrentUserFeed("", "", "30", objInsAccount.AccessToken); InstagramResponse<Comment[]> usercmts = new InstagramResponse<Comment[]>(); CommentController objComment = new CommentController(); LikesController objLikes = new LikesController(); if (userinf2 != null) { for (int j = 0; j < userinf2.data.Count(); j++) { try { objInstagramFeed = new Domain.Socioboard.MongoDomain.InstagramFeed(); //objInstagramFeed.EntryDate = DateTime.Now; try { // objInstagramFeed.Id = ObjectId.GenerateNewId(); objInstagramFeed.strId = ObjectId.GenerateNewId().ToString(); } catch { } try { objInstagramFeed.FeedDate = userinf2.data[j].created_time.ToString(); } catch { } try { objInstagramFeed.FeedId = userinf2.data[j].id; } catch { } try { objInstagramFeed.Type = userinf2.data[j].type.ToString(); if (objInstagramFeed.Type == "video") { objInstagramFeed.VideoUrl = userinf2.data[j].videos.standard_resolution.url.ToString(); } } catch { } try { objInstagramFeed.FeedImageUrl = userinf2.data[j].images.low_resolution.url.ToString(); } catch { } try { objInstagramFeed.InstagramId = objInsAccount.InstagramId; } catch { } try { objInstagramFeed.LikeCount = userinf2.data[j].likes.count; } catch { } try { objInstagramFeed.CommentCount = userinf2.data[j].comments.count; } catch { } try { string str = userinf2.data[j].user_has_liked.ToString(); if (str == "False") { objInstagramFeed.IsLike = 0; } else { objInstagramFeed.IsLike = 1; } } catch { } try { objInstagramFeed.AdminUser = userinf2.data[j].caption.from.username; } catch { } try { objInstagramFeed.Feed = userinf2.data[j].caption.text; } catch { } try { objInstagramFeed.ImageUrl = userinf2.data[j].caption.from.profile_picture; } catch { } try { objInstagramFeed.FromId = userinf2.data[j].caption.from.id; } catch { } try { objInstagramFeed.FeedUrl = userinf2.data[j].link; } catch { } //try //{ // objInstagramFeed.UserId = objInsAccount.UserId.; //} //catch { } var ret = instagramFeedRepo.Find<Domain.Socioboard.MongoDomain.InstagramFeed>(t => t.FeedId.Equals(objInstagramFeed.FeedId) && t.InstagramId.Equals(objInstagramFeed.InstagramId)); var task = Task.Run(async () => { return await ret; }); int count = task.Result.Count; if (count < 1) { instagramFeedRepo.Add(objInstagramFeed); } else { FilterDefinition<BsonDocument> filter = new BsonDocument("FeedId", objInstagramFeed.FeedId); var update = Builders<BsonDocument>.Update.Set("IsLike", objInstagramFeed.IsLike).Set("CommentCount", objInstagramFeed.CommentCount).Set("LikeCount", objInstagramFeed.LikeCount).Set("Type", objInstagramFeed.Type).Set("VideoUrl", objInstagramFeed.VideoUrl); instagramFeedRepo.Update<Domain.Socioboard.MongoDomain.InstagramFeed>(update, filter); } //if (!objInstagramFeedRepository.checkInstagramFeedExists(userinf2.data[j].id, objInsAccount.UserId)) //{ // objInstagramFeedRepository.addInstagramFeed(objInstagramFeed); //} List<Domain.Socioboard.MongoDomain.InstagramComment> lstInstagramComment = new List<Domain.Socioboard.MongoDomain.InstagramComment>(); usercmts = objComment.GetComment(userinf2.data[j].id, objInsAccount.AccessToken); for (int cmt = 0; cmt < usercmts.data.Count(); cmt++) { try { Domain.Socioboard.MongoDomain.InstagramComment objInstagramComment = new Domain.Socioboard.MongoDomain.InstagramComment(); try { objInstagramComment.Comment = usercmts.data[cmt].text; } catch { } try { objInstagramComment.CommentDate = usercmts.data[cmt].created_time.ToString(); } catch { } try { objInstagramComment.CommentId = usercmts.data[cmt].id; } catch { } //try //{ // objInstagramComment.EntryDate = DateTime.UtcNow.ToString(); //} //catch { } try { objInstagramComment.FeedId = userinf2.data[j].id; } catch { } try { objInstagramComment.Id = ObjectId.GenerateNewId(); objInstagramComment.strId = ObjectId.GenerateNewId().ToString(); } catch { } try { objInstagramComment.InstagramId = objInsAccount.InstagramId; } catch { } try { // objInstagramComment.UserId = objInsAccount.UserId; } catch { } try { objInstagramComment.FromName = usercmts.data[cmt].from.username; } catch { } try { objInstagramComment.FromProfilePic = usercmts.data[cmt].from.profile_picture; } catch { } lstInstagramComment.Add(objInstagramComment); } catch (Exception ex) { logger.Error(ex.StackTrace); } } instagarmCommentRepo.AddList(lstInstagramComment); } catch (Exception ex) { logger.Error(ex.Message); } } } } catch (Exception ex) { logger.Error(ex.Message); } }
public void ComplexEntityTest() { IRepository<Customer> _customerRepo = new MongoRepository<Customer>(); IRepository<Product> _productRepo = new MongoRepository<Product>(); var customer = new Customer(); customer.FirstName = "Erik"; customer.LastName = "Swaun"; customer.Phone = "123 99 8767"; customer.Email = "*****@*****.**"; customer.HomeAddress = new Address { Address1 = "Main bulevard", Address2 = "1 west way", PostCode = "89560", City = "Tempare", Country = "Arizona" }; var order = new Order(); order.PurchaseDate = DateTime.Now.AddDays(-2); var orderItems = new List<OrderItem>(); var shampoo = _productRepo.Add(new Product() { Name = "Palmolive Shampoo", Price = 5 }); var paste = _productRepo.Add(new Product() { Name = "Mcleans Paste", Price = 4 }); var item1 = new OrderItem { Product = shampoo, Quantity = 1 }; var item2 = new OrderItem { Product = paste, Quantity = 2 }; orderItems.Add(item1); orderItems.Add(item2); order.Items = orderItems; customer.Orders = new List<Order> { order }; _customerRepo.Add(customer); Assert.IsNotNull(customer.Id); Assert.IsNotNull(customer.Orders[0].Items[0].Product.Id); // get the orders var theOrders = _customerRepo.Where(c => c.Id == customer.Id).Select(c => c.Orders).ToList(); var theOrderItems = theOrders[0].Select(o => o.Items); Assert.IsNotNull(theOrders); Assert.IsNotNull(theOrderItems); }
private List<Domain.Socioboard.Domain.MongoFacebookFeed> AddFacebookFeeds(string UserId, FacebookClient fb, dynamic profile) { //List of new Feeds List<Domain.Socioboard.Domain.MongoFacebookFeed> lstFacebookFeeds = new List<Domain.Socioboard.Domain.MongoFacebookFeed>(); try { // Domain.Socioboard.Domain.FacebookFeed objFacebookFeed = new Domain.Socioboard.Domain.FacebookFeed(); MongoFacebookFeed objFacebookFeed = new MongoFacebookFeed(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; string nexturl = "v2.0/me/feed";//"v2.0/me/posts"; //for (int i = 0; i < 10; i++) { dynamic feeds = fb.Get(nexturl); //dynamic feedss = fb.Get("/338818712957141/posts"); //dynamic feedsss = fb.Get("/338818712957141/feed"); if (feeds != null) { try { nexturl = feeds["paging"]["next"].ToString(); } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); } foreach (var result in feeds["data"]) { // objFacebookFeed = new Domain.Socioboard.Domain.FacebookFeed(); objFacebookFeed.Type = "fb_feed"; try { objFacebookFeed.UserId = UserId; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objFacebookFeed.ProfileId = profile["id"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objFacebookFeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; objFacebookFeed.FromName = result["from"]["name"].ToString(); objFacebookFeed.FromId = result["from"]["id"].ToString(); objFacebookFeed.FeedId = result["id"].ToString(); objFacebookFeed.FeedDate = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookFeed.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; objFacebookFeed.FbLike = "http://graph.facebook.com/" + result["id"] + "/likes"; //Commented as these cause errors on API //Added by Sumit Gupta [31-01-15] to get post Shares/Likes/Comments #region Added by Sumit Gupta [31-01-15] //try //{ // dynamic like = fb.Get("v2.0/" + objFbPagePost.PostId + "/likes?summary=1&limit=0"); // objFbPagePost.Likes = Convert.ToInt32(like["summary"]["total_count"]); //} //catch (Exception ex) //{ // Console.WriteLine(ex.StackTrace); //} //try //{ // dynamic comment = fb.Get("v2.0/" + objFbPagePost.PostId + "/comments?summary=1&limit=0"); // objFbPagePost.Comments = Convert.ToInt32(comment["summary"]["total_count"]); //} //catch (Exception ex) //{ // Console.WriteLine(ex.StackTrace); //} //try //{ // dynamic shares = fb.Get("v2.0/" + objFbPagePost.PostId); // objFbPagePost.Shares = Convert.ToInt32(shares["shares"]["count"]); //} //catch (Exception ex) //{ // Console.WriteLine(ex.StackTrace); // logger.Error(ex.StackTrace); //} #endregion //Added by Sumit Gupta [17-02-15] try { objFacebookFeed.Picture = result["picture"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); objFacebookFeed.Picture = ""; } string message = string.Empty; int lstfbcount = 0; if (lstfbcount < 25) { try { if (result["message"] != null) { message = result["message"]; lstfbcount++; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); try { if (result["description"] != null) { message = result["description"]; lstfbcount++; } } catch (Exception exx) { try { Console.WriteLine(exx.StackTrace); if (result["story"] != null) { message = result["story"]; lstfbcount++; } } catch (Exception exxx) { Console.WriteLine(exxx.StackTrace); message = string.Empty; } } } } if (message == null) { message = ""; } objFacebookFeed.FeedDescription = message; objFacebookFeed.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); //Check to avoid duplicacy //if (!objFacebookFeedRepository.checkFacebookFeedExists(objFacebookFeed.FeedId)) //{ // objFacebookFeedRepository.addFacebookFeed(objFacebookFeed); // lstFacebookFeeds.Add(objFacebookFeed); //} MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); mongorepo.Add<MongoFacebookFeed>(objFacebookFeed); } } else { //break; } } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); Console.Write(ex.StackTrace); } return lstFacebookFeeds; }
public void Basic_Save() { var mongoRepository = new MongoRepository<User>(); var user = new User() {Name = "Basic_Save"}; mongoRepository.Add(user); }
public string MoveInstagramCommentToMongo() { InstagramCommentRepository twtfeedrepo = new InstagramCommentRepository(); string output = string.Empty; bool exit = true; int skip = 0; MongoRepository mongorepo = new MongoRepository("InstagramComment"); while (exit) { List<Domain.Socioboard.Domain.InstagramComment> fbmsgs = twtfeedrepo.getAllInstagramCommentMongo(skip); if (fbmsgs.Count() == 0) { exit = false; } foreach (var item in fbmsgs) { Domain.Socioboard.MongoDomain.InstagramComment mfbmsg = new Domain.Socioboard.MongoDomain.InstagramComment(); mfbmsg.Id = MongoDB.Bson.ObjectId.GenerateNewId(); // mfbmsg.EntryDate = item.EntryDate.ToString(); mfbmsg.Comment = item.Comment; mfbmsg.CommentDate = item.CommentDate; mfbmsg.CommentId = item.CommentId; mfbmsg.FeedId = item.FeedId; mfbmsg.FromName = item.FromName; mfbmsg.FromProfilePic = item.FromProfilePic; mfbmsg.InstagramId = item.InstagramId; mfbmsg.strId = item.Id.ToString(); mongorepo.Add<Domain.Socioboard.MongoDomain.InstagramComment>(mfbmsg); } skip = skip + 50; } return output; }
public string MoveFbMessageToMongo() { string output = string.Empty; bool exit = true; int skip = 0; MongoRepository mongorepo = new MongoRepository("FacebookMessage"); while(exit) { List<Domain.Socioboard.Domain.FacebookMessage> fbmsgs = objFacebookMessageRepository.getAllFacebookMessagesMongo(skip); if (fbmsgs.Count() == 0) { exit = false; } foreach (var item in fbmsgs) { Domain.Socioboard.MongoDomain.FacebookMessage mfbmsg = new Domain.Socioboard.MongoDomain.FacebookMessage(); mfbmsg.Id = MongoDB.Bson.ObjectId.GenerateNewId(); mfbmsg.EntryDate = item.EntryDate.ToString("yyyy/MM/dd HH:mm:ss"); mfbmsg.FbComment = item.FbComment; mfbmsg.FbLike = item.FbLike; mfbmsg.FromId = item.FromId; mfbmsg.FromName = item.FromName; mfbmsg.FromProfileUrl = item.FromProfileUrl; mfbmsg.IsArchived = item.IsArchived.ToString(); mfbmsg.Message = item.Message; mfbmsg.MessageDate = item.MessageDate.ToString("yyyy/MM/dd HH:mm:ss"); mfbmsg.MessageId = item.MessageId; mfbmsg.Picture = item.Picture; mfbmsg.ProfileId = item.ProfileId; mfbmsg.Type = item.Type; mfbmsg.UserId = item.UserId.ToString(); mongorepo.Add<Domain.Socioboard.MongoDomain.FacebookMessage>(mfbmsg); } skip = skip + 50; } return output; }
public void OverrideCollectionName() { IRepository<Customer> _customerRepo = new MongoRepository<Customer>("mongodb://localhost/MongoRepositoryTests", "TestCustomers123"); _customerRepo.Add(new Customer() { FirstName = "Test" }); Assert.IsTrue(_customerRepo.Single().FirstName.Equals("Test")); Assert.AreEqual("TestCustomers123", _customerRepo.Collection.Name); Assert.AreEqual("TestCustomers123", ((MongoRepository<Customer>)_customerRepo).CollectionName); IRepositoryManager<Customer> _curstomerRepoManager = new MongoRepositoryManager<Customer>("mongodb://localhost/MongoRepositoryTests", "TestCustomers123"); Assert.AreEqual("TestCustomers123", _curstomerRepoManager.Name); }
public void CustomIDTest() { var x = new MongoRepository<CustomIDEntity>(); var xm = new MongoRepositoryManager<CustomIDEntity>(); x.Add(new CustomIDEntity() { Id = "aaa" }); Assert.IsTrue(xm.Exists); Assert.IsInstanceOfType(x.GetById("aaa"), typeof(CustomIDEntity)); Assert.AreEqual("aaa", x.GetById("aaa").Id); x.Delete("aaa"); Assert.AreEqual(0, x.Count()); var y = new MongoRepository<CustomIDEntityCustomCollection>(); var ym = new MongoRepositoryManager<CustomIDEntityCustomCollection>(); y.Add(new CustomIDEntityCustomCollection() { Id = "xyz" }); Assert.IsTrue(ym.Exists); Assert.AreEqual(ym.Name, "MyTestCollection"); Assert.AreEqual(y.CollectionName, "MyTestCollection"); Assert.IsInstanceOfType(y.GetById("xyz"), typeof(CustomIDEntityCustomCollection)); y.Delete("xyz"); Assert.AreEqual(0, y.Count()); }
public void GetInstagramSelfFeeds(string instagramId, string accessToken) { MongoRepository instagarmCommentRepo = new MongoRepository("InstagramComment"); MongoRepository instagramFeedRepo = new MongoRepository("InstagramFeed"); try { GlobusInstagramLib.Instagram.Core.UsersMethods.Users userInstagram = new GlobusInstagramLib.Instagram.Core.UsersMethods.Users(); GlobusInstagramLib.Instagram.Core.MediaMethods.Media _Media = new GlobusInstagramLib.Instagram.Core.MediaMethods.Media(); InstagramResponse<Comment[]> usercmts = new InstagramResponse<Comment[]>(); CommentController objComment = new CommentController(); LikesController objLikes = new LikesController(); string feeds = _Media.UserResentFeeds(instagramId, accessToken); if (feeds != null) { JObject feed_data = JObject.Parse(feeds); foreach (var item in feed_data["data"]) { try { Domain.Socioboard.MongoDomain.InstagramFeed objInstagramFeed = new Domain.Socioboard.MongoDomain.InstagramFeed(); try { objInstagramFeed.FeedDate = item["created_time"].ToString(); } catch { } try { objInstagramFeed.FeedId = item["id"].ToString(); } catch { } try { objInstagramFeed.Type = item["type"].ToString(); if (objInstagramFeed.Type == "video") { objInstagramFeed.VideoUrl = item["videos"]["standard_resolution"]["url"].ToString(); } } catch { } try { objInstagramFeed.FeedImageUrl = item["images"]["standard_resolution"]["url"].ToString(); } catch { } try { objInstagramFeed.InstagramId = instagramId; } catch { } try { objInstagramFeed.LikeCount = Int32.Parse(item["likes"]["count"].ToString()); } catch { } try { objInstagramFeed.CommentCount = Int32.Parse(item["comments"]["count"].ToString()); } catch { } try { string str = item["user_has_liked"].ToString(); if (str.ToLower() == "false") { objInstagramFeed.IsLike = 0; } else { objInstagramFeed.IsLike = 1; } } catch { } try { objInstagramFeed.AdminUser = item["user"]["username"].ToString(); } catch { } try { objInstagramFeed.Feed = item["caption"]["text"].ToString(); } catch { } try { objInstagramFeed.ImageUrl = item["user"]["profile_picture"].ToString(); } catch { } try { objInstagramFeed.FromId = item["user"]["id"].ToString(); } catch { } try { objInstagramFeed.FeedUrl = item["link"].ToString(); } catch { } var ret = instagramFeedRepo.Find<Domain.Socioboard.MongoDomain.InstagramFeed>(t => t.FeedId.Equals(objInstagramFeed.FeedId) && t.InstagramId.Equals(objInstagramFeed.InstagramId)); var task = Task.Run(async () => { return await ret; }); int count = task.Result.Count; if (count < 1) { instagramFeedRepo.Add(objInstagramFeed); } else { FilterDefinition<BsonDocument> filter = new BsonDocument("FeedId", objInstagramFeed.FeedId); var update = Builders<BsonDocument>.Update.Set("IsLike", objInstagramFeed.IsLike).Set("CommentCount", objInstagramFeed.CommentCount).Set("LikeCount", objInstagramFeed.LikeCount).Set("Type", objInstagramFeed.Type).Set("VideoUrl", objInstagramFeed.VideoUrl); instagramFeedRepo.Update<Domain.Socioboard.MongoDomain.InstagramFeed>(update, filter); } List<Domain.Socioboard.MongoDomain.InstagramComment> lstInstagramComment = new List<Domain.Socioboard.MongoDomain.InstagramComment>(); usercmts = objComment.GetComment(objInstagramFeed.FeedId, accessToken); for (int cmt = 0; cmt < usercmts.data.Count(); cmt++) { try { Domain.Socioboard.MongoDomain.InstagramComment objInstagramComment = new Domain.Socioboard.MongoDomain.InstagramComment(); try { objInstagramComment.Comment = usercmts.data[cmt].text; } catch { } try { objInstagramComment.CommentDate = usercmts.data[cmt].created_time.ToString(); } catch { } try { objInstagramComment.CommentId = usercmts.data[cmt].id; } catch { } try { objInstagramComment.FeedId = objInstagramFeed.FeedId; } catch { } try { objInstagramComment.InstagramId = instagramId; } catch { } try { objInstagramComment.FromName = usercmts.data[cmt].from.username; } catch { } try { objInstagramComment.FromProfilePic = usercmts.data[cmt].from.profile_picture; } catch { } lstInstagramComment.Add(objInstagramComment); } catch (Exception ex) { } } instagarmCommentRepo.AddList(lstInstagramComment); } catch (Exception ex) { } } } } catch (Exception ex) { } }
public ActionResult Populate() { var repo = new MongoRepository<Customer>(); repo.Collection.Drop(); string file = Server.MapPath("~/Controllers/interface1.xml"); var writer = new System.Xml.Serialization.XmlSerializer(typeof(g)); var wfile = new System.IO.StreamReader(file); var o = (g)writer.Deserialize(wfile); string file2 = Server.MapPath("~/Controllers/interface2.xml"); var writer2 = new System.Xml.Serialization.XmlSerializer(typeof(root)); var wfile2 = new System.IO.StreamReader(file2); var o2 = (root)writer2.Deserialize(wfile2); var kommuner = o2.län.SelectMany(x => x.kommun).ToList(); foreach (var customer in o.path) { string name = ""; var kommun = kommuner.FirstOrDefault(x => x.kommunkod == customer.id); if (kommun != null) { name = kommun.kommunnamn; } var c = new Customer() { InternalId = customer.id, IsCustomer = false, Path = customer.d, Name = name }; repo.Add(c); } return Content("!"); }
public void getTwitterFeeds(string UserId, oAuthTwitter OAuth) { //int J = 0; MongoRepository twitterfeedrepo = new MongoRepository("TwitterFeed"); TwitterUser twtuser; #region Add Twitter User Feed twtuser = new TwitterUser(); try { JArray Home_Timeline = twtuser.GetStatuses_Home_Timeline(OAuth); objTwitterFeed = new Domain.Socioboard.MongoDomain.TwitterFeed(); foreach (var item in Home_Timeline) { //objTwitterFeed.UserId = Guid.Parse(UserId); objTwitterFeed.Type = "twt_feeds"; try { objTwitterFeed.Feed = item["text"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.SourceUrl = item["source"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.ScreenName = objTwitterAccount.TwitterScreenName; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.ProfileId = objTwitterAccount.TwitterUserId; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.MessageId = item["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.FeedDate = Utility.ParseTwitterTime(item["created_at"].ToString().TrimStart('"').TrimEnd('"')).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.InReplyToStatusUserId = item["in_reply_to_status_id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.Id = ObjectId.GenerateNewId(); objTwitterFeed.strId = ObjectId.GenerateNewId().ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.FromProfileUrl = item["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.FromName = item["user"]["name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.FromId = item["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.FromScreenName = item["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objTwitterFeed.MediaUrl = item["extended_entities"]["media"][0]["media_url"].ToString(); } catch (Exception ex) { } var ret = twitterfeedrepo.Find<Domain.Socioboard.MongoDomain.TwitterFeed>(t => t.MessageId.Equals(objTwitterFeed.MessageId) && t.ProfileId.Equals(objTwitterFeed.ProfileId)); var task = Task.Run(async () => { return await ret; }); int count = task.Result.Count; if (count < 1) { twitterfeedrepo.Add(objTwitterFeed); } //if (!objTwitterFeedRepository.checkTwitterFeedExists(objTwitterFeed.MessageId)) //{ // try // { // J++; // objTwitterFeedRepository.addTwitterFeed(objTwitterFeed); // logger.Error("getTwitterFeedsCount>>>"+J); // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // Console.WriteLine(ex.StackTrace); // } //} // Edited by Antima[20/12/2014] //SentimentalAnalysis _SentimentalAnalysis = new SentimentalAnalysis(); //FeedSentimentalAnalysisRepository _FeedSentimentalAnalysisRepository = new FeedSentimentalAnalysisRepository(); //try //{ // //if (_FeedSentimentalAnalysisRepository.checkFeedExists(objTwitterFeed.ProfileId.ToString(), Guid.Parse(UserId), objTwitterFeed.Id.ToString())) // //{ // // if (!string.IsNullOrEmpty(objTwitterFeed.Feed)) // // { // // string Network = "twitter"; // // _SentimentalAnalysis.GetPostSentimentsFromUclassify(Guid.Parse(UserId), objTwitterFeed.ProfileId, objTwitterFeed.MessageId, objTwitterFeed.Feed, Network); // // } // //} //} //catch (Exception) //{ //} } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); logger.Error("twtuser.GetStatuses_Home_Timeline ex.StackTrace >> " + ex.StackTrace); logger.Error("twtuser.GetStatuses_Home_Timeline ex.Message >> " + ex.Message); } #endregion }
public void CustomIDTypeTest() { var xint = new MongoRepository<IntCustomer, int>(); xint.Add(new IntCustomer() { Id = 1, Name = "Test A" }); xint.Add(new IntCustomer() { Id = 2, Name = "Test B" }); var yint = xint.GetById(2); Assert.AreEqual(yint.Name, "Test B"); xint.Delete(2); Assert.AreEqual(1, xint.Count()); }
public string AddComment(string UserId, string FeedId, string Text, string InstagramId) { MongoRepository instagarmCommentRepo = new MongoRepository("InstagramComment"); Domain.Socioboard.MongoDomain.InstagramComment _InstagramComment = new Domain.Socioboard.MongoDomain.InstagramComment(); //GlobusInstagramLib.Authentication.ConfigurationIns configi = new GlobusInstagramLib.Authentication.ConfigurationIns("https://api.instagram.com/oauth/authorize/", ConfigurationManager.AppSettings["InstagramClientKey"], ConfigurationManager.AppSettings["InstagramClientSec"], ConfigurationManager.AppSettings["RedirectUrl"], "http://api.instagram.com/oauth/access_token", "https://api.instagram.com/v1/", ""); //oAuthInstagram _api = new oAuthInstagram(); //_api = oAuthInstagram.GetInstance(configi); objInstagramAccount = objInstagramAccountRepository.getInstagramAccountDetailsById(InstagramId); CommentController objComment = new CommentController(); string ret = objComment.PostCommentAdd(FeedId, Text, objInstagramAccount.AccessToken); if (!string.IsNullOrEmpty(ret)) { try { JObject JData = JObject.Parse(ret); string commentid = JData["data"]["id"].ToString(); string time = JData["data"]["created_time"].ToString(); string profilepic = JData["data"]["from"]["profile_picture"].ToString(); string username = JData["data"]["from"]["username"].ToString(); _InstagramComment.Id = ObjectId.GenerateNewId(); _InstagramComment.strId = ObjectId.GenerateNewId().ToString(); _InstagramComment.FeedId = FeedId; _InstagramComment.InstagramId = InstagramId; _InstagramComment.FromProfilePic = profilepic; _InstagramComment.FromName = username; _InstagramComment.CommentDate = time; _InstagramComment.Comment = Text; _InstagramComment.CommentId = commentid; //objInstagramCommentRepository.addInstagramComment(_InstagramComment); instagarmCommentRepo.Add(_InstagramComment); } catch (Exception ex) { logger.Error(ex.Message); return null; } } else { return null; } return new JavaScriptSerializer().Serialize(_InstagramComment); }
public void BatchTest() { IRepository<Customer> _customerRepo = new MongoRepository<Customer>(); var custlist = new List<Customer>(new Customer[] { new Customer() { FirstName = "Customer A" }, new Customer() { FirstName = "Client B" }, new Customer() { FirstName = "Customer C" }, new Customer() { FirstName = "Client D" }, new Customer() { FirstName = "Customer E" }, new Customer() { FirstName = "Client F" }, new Customer() { FirstName = "Customer G" }, }); //Insert batch _customerRepo.Add(custlist); var count = _customerRepo.Count(); Assert.AreEqual(7, count); foreach (Customer c in custlist) Assert.AreNotEqual(new string('0', 24), c.Id); //Update batch foreach (Customer c in custlist) c.LastName = c.FirstName; _customerRepo.Update(custlist); foreach (Customer c in _customerRepo) Assert.AreEqual(c.FirstName, c.LastName); //Delete by criteria _customerRepo.Delete(f => f.FirstName.StartsWith("Client")); count = _customerRepo.Count(); Assert.AreEqual(4, count); //Delete specific object _customerRepo.Delete(custlist[0]); //Test AsQueryable var selectedcustomers = from cust in _customerRepo where cust.LastName.EndsWith("C") || cust.LastName.EndsWith("G") select cust; Assert.AreEqual(2, selectedcustomers.ToList().Count); count = _customerRepo.Count(); Assert.AreEqual(3, count); //Drop entire repo new MongoRepositoryManager<Customer>().Drop(); count = _customerRepo.Count(); Assert.AreEqual(0, count); }
public HttpResponseMessage PostPangram([FromBody]string sentence) { CreatePangramResponse createPangramResponse = new CreatePangramResponse(); createPangramResponse.isPangram = false; IRepository<Pangram> _pangramRepo = new MongoRepository<Pangram>(); if (!String.IsNullOrEmpty(sentence)) { var pangram = new Pangram(sentence); if (pangram.isPangram) { var pangrams = _pangramRepo.Select(p => p).ToList(); var checkForSamePangramInRepo = pangrams.AsEnumerable().Where(p => p.Sentence == sentence).Select(p => p.Sentence).ToList(); if (checkForSamePangramInRepo.Count() == 0) { _pangramRepo.Add(pangram); } createPangramResponse.isPangram = true; } } return new HttpResponseMessage() { Content = new JsonContent2( createPangramResponse ) }; }
public string MovefbFeedsToMongo() { string output = string.Empty; List<Domain.Socioboard.Domain.FacebookFeed> fbfeeds = objFacebookFeedRepository.getAllFeedDetailForMongo(); MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); foreach (var item in fbfeeds) { Domain.Socioboard.Domain.MongoFacebookFeed Mongofbfeed = new Domain.Socioboard.Domain.MongoFacebookFeed(); Mongofbfeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); Mongofbfeed.EntryDate = item.EntryDate.ToString("yyyy/MM/dd HH:mm:ss"); Mongofbfeed.FbComment = item.FbComment; Mongofbfeed.FbLike = item.FbLike; Mongofbfeed.FeedDate = item.FeedDate.ToString("yyyy/MM/dd HH:mm:ss"); Mongofbfeed.FeedDescription = item.FeedDescription; Mongofbfeed.FeedId = item.FeedId; Mongofbfeed.FromId = item.FromId; Mongofbfeed.FromName = item.FromName; Mongofbfeed.FromProfileUrl = item.FromProfileUrl; Mongofbfeed.FromScreenName = item.FromScreenName; Mongofbfeed.InReplyToStatusUserId = item.InReplyToStatusUserId; Mongofbfeed.MessageDate = item.MessageDate.ToString(); Mongofbfeed.MessageId = item.MessageId; Mongofbfeed.Picture = item.Picture; Mongofbfeed.ProfileId = item.ProfileId; Mongofbfeed.ProfileType = item.ProfileType; Mongofbfeed.ReadStatus = item.ReadStatus; Mongofbfeed.ScreenName = item.ScreenName; Mongofbfeed.SourceUrl = item.SourceUrl; Mongofbfeed.TwitterMsg = item.TwitterMsg; Mongofbfeed.Type = item.Type; Mongofbfeed.UserId = item.UserId.ToString(); mongorepo.Add<Domain.Socioboard.Domain.MongoFacebookFeed>(Mongofbfeed); } return output; }
//Added by Avinash Verma & Sumit Gupta [30-01-15] private void AddFacebookFeedsWithPagination(string UserId, FacebookClient fb, dynamic profile) { int I = 0; try { //objFacebookFeed = new Domain.Socioboard.Domain.FacebookFeed(); MongoFacebookFeed objFacebookFeed = new MongoFacebookFeed(); System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; string nexturl = "v2.0/me/feed";//"v2.0/me/posts"; for (int i = 0; i < 50; i++) { dynamic feeds = fb.Get(nexturl); //dynamic feedss = fb.Get("/338818712957141/posts"); //dynamic feedsss = fb.Get("/338818712957141/feed"); if (feeds != null) { try { nexturl = feeds["paging"]["next"].ToString(); } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); } foreach (var result in feeds["data"]) { objFacebookFeed.Type = "fb_feed"; try { objFacebookFeed.UserId = UserId; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objFacebookFeed.ProfileId = profile["id"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objFacebookFeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; objFacebookFeed.FromName = result["from"]["name"].ToString(); objFacebookFeed.FromId = result["from"]["id"].ToString(); objFacebookFeed.FeedId = result["id"].ToString(); objFacebookFeed.FeedDate = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookFeed.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; objFacebookFeed.FbLike = "http://graph.facebook.com/" + result["id"] + "/likes"; //Added by Sumit Gupta [17-02-15] try { objFacebookFeed.Picture = result["picture"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); objFacebookFeed.Picture = null; } string message = string.Empty; int lstfbcount = 0; if (lstfbcount < 25) { try { if (result["message"] != null) { message = result["message"]; lstfbcount++; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); try { if (result["description"] != null) { message = result["description"]; lstfbcount++; } } catch (Exception exx) { try { Console.WriteLine(exx.StackTrace); if (result["story"] != null) { message = result["story"]; lstfbcount++; } } catch (Exception exxx) { Console.WriteLine(exxx.StackTrace); message = string.Empty; } } } } objFacebookFeed.FeedDescription = message; objFacebookFeed.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); //// Edited by Antima[20/12/2014] //SentimentalAnalysis _SentimentalAnalysis = new SentimentalAnalysis(); //FeedSentimentalAnalysisRepository _FeedSentimentalAnalysisRepository = new FeedSentimentalAnalysisRepository(); //try //{ // if (_FeedSentimentalAnalysisRepository.checkFeedExists(objFacebookFeed.ProfileId.ToString(), Guid.Parse(UserId), objFacebookFeed.Id.ToString())) // { // if (!string.IsNullOrEmpty(message)) // { // string Network = "facebook"; // _SentimentalAnalysis.GetPostSentimentsFromUclassify(Guid.Parse(UserId), objFacebookFeed.ProfileId, objFacebookFeed.MessageId, message, Network); // } // } //} //catch (Exception ex) //{ // logger.Error(ex.Message); // logger.Error(ex.StackTrace); //} //if (!objFacebookFeedRepository.checkFacebookFeedExists(objFacebookFeed.FeedId)) //{ // I++; // objFacebookFeedRepository.addFacebookFeed(objFacebookFeed); // logger.Error("AddFacebookFeedsWithPaginationCount>>>"+I); //} I++; MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); mongorepo.Add<MongoFacebookFeed>(objFacebookFeed); } } else { break; } } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); Console.Write(ex.StackTrace); } }
public string MoveTwitterMessagesTOMOngo() { TwitterMessageRepository twtfeedrepo = new TwitterMessageRepository(); string output = string.Empty; bool exit = true; int skip = 0; MongoRepository mongorepo = new MongoRepository("TwitterMessage"); while (exit) { List<Domain.Socioboard.Domain.TwitterMessage> fbmsgs = twtfeedrepo.getAllTwitterMessagesMongo(skip); if (fbmsgs.Count() == 0) { exit = false; } foreach (var item in fbmsgs) { Domain.Socioboard.MongoDomain.TwitterMessage mfbmsg = new Domain.Socioboard.MongoDomain.TwitterMessage(); mfbmsg.Id = MongoDB.Bson.ObjectId.GenerateNewId(); // mfbmsg.EntryDate = item.EntryDate.ToString(); mfbmsg.FromId = item.FromId; mfbmsg.FromName = item.FromName; mfbmsg.FromProfileUrl = item.FromProfileUrl; mfbmsg.FromScreenName = item.FromScreenName; mfbmsg.MessageId = item.MessageId; mfbmsg.InReplyToStatusUserId = item.InReplyToStatusUserId; mfbmsg.MessageDate = item.MessageDate.ToString("yyyy/MM/dd HH:mm:ss"); mfbmsg.IsArchived = item.IsArchived; mfbmsg.ProfileId = item.ProfileId; mfbmsg.Type = item.Type; mfbmsg.ScreenName = item.ScreenName; mfbmsg.SourceUrl = item.SourceUrl; mfbmsg.ReadStatus = mfbmsg.ReadStatus; mfbmsg.ProfileType = item.ProfileType; mfbmsg.TwitterMsg = item.TwitterMsg; mongorepo.Add<Domain.Socioboard.MongoDomain.TwitterMessage>(mfbmsg); } skip = skip + 50; } return output; }
//Added by Sumit Gupta [02-02-15] private void AddFacebookMessageWithPagination(string UserId, FacebookClient fb, dynamic profile) { int J = 0; Domain.Socioboard.MongoDomain.FacebookMessage objFacebookMessage = new Domain.Socioboard.MongoDomain.FacebookMessage(); try { string nexturl = "v2.0/me/inbox"; for (int i = 0; i < 50; i++) { dynamic messages = fb.Get(nexturl); if (messages != null) { try { nexturl = messages["paging"]["next"].ToString(); logger.Error("Facebook.asmx >> AddFacebookMessageWithPagination >> nexturl : " + nexturl); } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); } foreach (dynamic result in messages["data"]) { try { foreach (dynamic message in result["comments"]["data"]) { objFacebookMessage.MessageId = message["id"]; objFacebookMessage.FromName = message["from"]["name"]; objFacebookMessage.FromId = message["from"]["id"]; objFacebookMessage.Message = message["message"]; objFacebookMessage.MessageDate = DateTime.Parse(message["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookMessage.FromProfileUrl = "http://graph.facebook.com/" + message["from"]["id"] + "/picture?type=small"; objFacebookMessage.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); objFacebookMessage.Id = ObjectId.GenerateNewId(); objFacebookMessage.ProfileId = profile["id"].ToString(); objFacebookMessage.Type = "inbox_message"; objFacebookMessage.UserId = UserId; //if (!objFacebookMessageRepository.checkFacebookMessageExists(objFacebookMessage.MessageId)) //{ J++; // objFacebookMessageRepository.addFacebookMessage(objFacebookMessage); MongoRepository mongorepo = new MongoRepository("FacebookMessage"); mongorepo.Add<Domain.Socioboard.MongoDomain.FacebookMessage>(objFacebookMessage); logger.Error("AddFacebookMessageWithPaginationCount>>>>" + J); //} } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } } } catch (Exception ex) { logger.Error(ex.Message); logger.Error(ex.StackTrace); Console.WriteLine(ex.StackTrace); } }
public string MoveInstagramFeedToMongo() { InstagramFeedRepository twtfeedrepo = new InstagramFeedRepository(); string output = string.Empty; bool exit = true; int skip = 0; MongoRepository mongorepo = new MongoRepository("InstagramFeed"); while (exit) { List<Domain.Socioboard.Domain.InstagramFeed> fbmsgs = twtfeedrepo.getAllInstagramFeedMongo(skip); if (fbmsgs.Count() == 0) { exit = false; } foreach (var item in fbmsgs) { Domain.Socioboard.MongoDomain.InstagramFeed mfbmsg = new Domain.Socioboard.MongoDomain.InstagramFeed(); mfbmsg.Id = MongoDB.Bson.ObjectId.GenerateNewId(); // mfbmsg.EntryDate = item.EntryDate.ToString(); mfbmsg.AdminUser = item.AdminUser; mfbmsg.CommentCount = item.CommentCount; mfbmsg.Feed = item.Feed; mfbmsg.FeedId = item.FeedId; mfbmsg.FeedDate = item.FeedDate; mfbmsg.FeedId = item.FeedId; mfbmsg.InstagramId = item.InstagramId; mfbmsg.strId = item.Id.ToString(); mfbmsg.FeedImageUrl = item.FeedImageUrl; mfbmsg.FeedUrl = item.FeedUrl; mfbmsg.FromId = item.FromId; mfbmsg.ImageUrl = item.ImageUrl; mfbmsg.InstagramId = item.InstagramId; mfbmsg.IsLike = item.IsLike; mfbmsg.LikeCount = item.LikeCount; mfbmsg.strId = item.Id.ToString(); mongorepo.Add<Domain.Socioboard.MongoDomain.InstagramFeed>(mfbmsg); } skip = skip + 50; } return output; }
private void AddFacebookUserHome(string UserId, FacebookClient fb, dynamic profile) { int K = 0; Domain.Socioboard.MongoDomain.FacebookMessage objFacebookMessage = new Domain.Socioboard.MongoDomain.FacebookMessage(); try { dynamic home = fb.Get("v2.0/me/home"); if (home != null) { int lstfbcount = 0; foreach (dynamic result in home["data"]) { string message = string.Empty; string imgprof = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; objFacebookMessage.EntryDate = DateTime.UtcNow.ToString(); objFacebookMessage.MessageId = result["id"].ToString(); objFacebookMessage.FromId = result["from"]["id"].ToString(); objFacebookMessage.FromName = result["from"]["name"].ToString(); objFacebookMessage.FromProfileUrl = imgprof; objFacebookMessage.Id = ObjectId.GenerateNewId(); objFacebookMessage.MessageDate = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookMessage.UserId =UserId; try { objFacebookMessage.Picture = result["picture"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); objFacebookMessage.Picture = null; } try { if (result["message_tags"][0] != null) { if (result["to"] != null) { foreach (var item in result["to"]["data"]) { if (result["from"] != null) { if (item["id"] != profile["id"]) { if (result["from"]["id"] == profile["id"]) { objFacebookMessage.Type = "fb_tag"; } else { objFacebookMessage.Type = "fb_home"; } } else { objFacebookMessage.Type = "fb_home"; } } } } else { objFacebookMessage.Type = "fb_home"; } } else { objFacebookMessage.Type = "fb_home"; } } catch (Exception ex) { objFacebookMessage.Type = "fb_home"; Console.WriteLine(ex.StackTrace); } objFacebookMessage.ProfileId = profile["id"].ToString(); objFacebookMessage.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; dynamic likes = fb.Get("v2.0/" + result["id"].ToString() + "/likes?limit=50000000"); string likestatus = "likes"; foreach (dynamic like in likes["data"]) { try { if (profile["id"].ToString() == like["id"].ToString()) { likestatus = "unlike"; break; } } catch (Exception ex) { likestatus = "likes"; } } objFacebookMessage.FbLike = likestatus; if (lstfbcount < 25) { try { if (result["message"] != null) { message = result["message"]; lstfbcount++; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); try { if (result["description"] != null) { message = result["description"]; lstfbcount++; } } catch (Exception exx) { try { Console.WriteLine(exx.StackTrace); if (result["story"] != null) { message = result["story"]; lstfbcount++; } } catch (Exception exxx) { Console.WriteLine(exxx.StackTrace); message = string.Empty; } } } } objFacebookMessage.Message = message; //if (!objFacebookMessageRepository.checkFacebookMessageExists(objFacebookMessage.MessageId)) //{ K++; //objFacebookMessageRepository.addFacebookMessage(objFacebookMessage); MongoRepository mongorepo = new MongoRepository("FacebookMessage"); mongorepo.Add<Domain.Socioboard.MongoDomain.FacebookMessage>(objFacebookMessage); logger.Error("AddFacebookUserHomeCount>>>" + K); //} } } } catch (Exception ex) { Console.Write(ex.StackTrace); logger.Error(ex.Message); logger.Error(ex.StackTrace); } }