public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { // Run base method to handle Users and Roles filter parameters. // Grab the fundId from the request. var fundId = actionContext.ControllerContext.RouteData.Values["id"].ToString(); // Query for the fund. var fundRepository = new MongoRepository<Fund>(); var fund = fundRepository.GetById(fundId); // Ensure the supplied fund exists. if (fund == null) { throw new HttpException(404, "NotFound"); } if (this.IsAuthorizedToAccessArea(fund.AreaId)) { // Add the fund to the Items dictionary to avoid duplicating the query. HttpContext.Current.Items["fund"] = fund; } else { throw new HttpException(401, "Unauthorized. You are not authorized to access this area."); } }
private static async Task CellCounts() { var mongoConnection = new MongoRepository("genomics"); var tbfsCollection = mongoConnection.GetCollection<EncodeTbfsPeak>("encode.tbfs-peaks"); var aggregate = tbfsCollection.Aggregate() .Match(new BsonDocument { { "antibody", "CTCF" } }) .Group(new BsonDocument { { "_id", "$cell" }, { "count", new BsonDocument("$sum", 1) } }); var results = await aggregate.ToListAsync(); var ordered = results.OrderBy(x => x[0]); // var aggregate = tbfsCollection.Aggregate() // .Match(new BsonDocument { { "antibody", "CTCF" } }) // .Group(new BsonDocument { { "_id", "$chromosome" }, { "count", new BsonDocument("$sum", 1) } }); // var results = await aggregate.ToListAsync(); // var ordered = results.OrderBy(x => x[0]); using (var writer = new StreamWriter(File.Open("C:\\_dev\\data\\genomics\\results.csv", FileMode.Create))) { foreach (var doc in ordered) { var line = doc[0] + "," + doc[1]; writer.WriteLine(line); } } }
public void TestInsert() { var t = new Team {Name = "Test"}; var repo = new MongoRepository<Team>(_db); repo.Save(t); Assert.NotNull(t.Id); }
public void FirstDBTest() { using (var db = new MongoRepository<DBStub>()) { db.Add(new DBStub() { Name = "test" }); } }
private void ImportMotherboards() { IRepository<Motherboard> motherboardRepository = new MongoRepository<Motherboard>(this.dbContext); IRepository<Vendor> vendorRepository = new MongoRepository<Vendor>(this.dbContext); var vendorsList = vendorRepository.GetAll().ToList(); textWriter.Write("Importing motherboards"); for (int i = 0; i < 45; i++) { if (i % 2 == 0) { textWriter.Write("."); } motherboardRepository.Add(new Motherboard() { Id = ObjectId.GenerateNewId(), Model = RandomUtils.GenerateRandomString(RandomUtils.GenerateNumberInRange(2, 5)), Price = RandomUtils.GenerateNumberInRange(150, 350), VendorId = vendorsList[RandomUtils.GenerateNumberInRange(0, vendorsList.Count - 1)].Id }); } textWriter.WriteLine(); }
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(); }
static void Main(string[] args) { ZipExtractor zipReader = new ZipExtractor("../../../../../Matches - Results.zip"); zipReader.Extract("../../../../../"); MongoRepository mongoContext = new MongoRepository(); List<ReniumLeague.Entity.Mongo.Models.Team> allPlaces = mongoContext.GetAllTeams().ToList(); var xmlSerializer = new ReniumLeague.Entity.Serializer.XmlSerialzer(); var xmlString = xmlSerializer.Serialize < ReniumLeague.Entity.Mongo.Models.Team >> (allTeams); var xmlFilePath = "../../teams.xml"; using (var str = new StreamWriter(xmlFilePath)) { str.Write(xmlString); } var objectsFromXml = xmlSerializer.ParseXml < ReniumLeague.Entity.Mongo.Models.Team >> (xmlFilePath); Console.WriteLine(); }
public CompetitionService(MongoRepository<Competition> competitionRepo, NodeService nodeService, MongoRepository<Team> teamRepo, PriceService priceService) { _competitionRepo = competitionRepo; _nodeService = nodeService; _teamRepo = teamRepo; _priceService = priceService; }
public ActionResult Index() { var model = new DeploymentJointModel(); var Companies = new MongoRepository<Company>(); model.ModelForView.Company = Companies.Select(c => new SelectListItem { Value = c.CompanyKey, Text = c.CompanyName }); var Environments = new MongoRepository<Entities.Environment>(); model.ModelForView.Environment = Environments.Select(e => new SelectListItem { Value = e.Id, Text = e.Name }); var Revisions = new MongoRepository<Revision>(); model.ModelForView.Revision = Revisions.Select(r => new SelectListItem { Value = r.Id, Text = r.Tag }); return View(model); }
public void Drop_IfHaveCollection_ReturnTrue() { var repository = new MongoRepository<TestModel>(); repository.Insert(TestModel.CreateInstance()); var result = repository.Drop(); Assert.IsTrue(result); }
static void Main(string[] args) { string mongoUrl = "mongodb://127.0.0.1:27017/mongodemo"; string databaseName = "MongoDemo"; //IMongoClient _client; //IMongoDatabase db; //_client = new MongoClient("mongodb://127.0.0.1:27017/mongodemo"); //db = _client.GetDatabase("MongoDemo"); //var list = db.GetCollection<Restaurant>("restaurants").Find(x => true).ToListAsync<Restaurant>().Result; //foreach (var restaurant in list) //{ // Console.WriteLine(restaurant.Name); //} MongoRepository<Restaurant> restaurantRepo = new MongoRepository<Restaurant>(mongoUrl, databaseName, "restaurants"); //var list = restaurantRepo.GetAll<Restaurant>(); var t1 = restaurantRepo.GetByIdAsync(new ObjectId("55e69a970e6672a2fb2cc624")); var restaurant = restaurantRepo.GetById(new ObjectId("55e69a970e6672a2fb2cc624")); Console.ReadLine(); }
protected bool IsAuthorizedToAccessArea(string areaId) { // Ensure the request contains the areaId if (String.IsNullOrEmpty(areaId)) { throw new HttpException(400, "BadRequest. Area not supplied."); } // Query for the area to match up its number to the associated Role. var areaRepository = new MongoRepository<Area>(); var area = areaRepository.GetById(areaId); // Ensure the supplied area exists. if (area == null) { throw new HttpException(404, "NotFound. The requested area does not exist."); } // Ensure the user is in a role to allow accessing the area. foreach (var role in RoleValidator.GetAuthorizedRolesForArea(area)) { if (HttpContext.Current.User.IsInRole(role)) { // Add the area to the Items dictionary to avoid duplicating the query. HttpContext.Current.Items["area"] = area; return true; } } return false; }
public GetPangramResponse GetPangramsLimit(int limit) { IRepository<Pangram> _pangramRepo = new MongoRepository<Pangram>(); GetPangramResponse getPangramResponse = new GetPangramResponse(); if (limit > 0) { var pangrams = _pangramRepo.Select(p => p) .Take(limit) .ToList(); if (pangrams.Count() > 0) { foreach (var pa in pangrams) { getPangramResponse.pangrams.Add(pa.Sentence); } } } return new GetPangramResponse() { Content = new JsonContent2( getPangramResponse ) }; }
public static async Task SyncEncodeTbfsData(string databaseName) { var mongoConnection = new MongoRepository(databaseName); var sync = new EncodeWebDataSynchronizer(new JsonWrapper(), mongoConnection, new HttpWebRequestWrapper()); await sync.SyncTbfs(); }
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { // Grab the arguments from the request. var id = (string)actionContext.ActionArguments["id"]; var fundData = (Fund)actionContext.ActionArguments["fund"]; // Ensure the user has not mismatched the Id property. if (id != fundData.Id) { throw new HttpException(400, "BadRequest: Data does not match item associated with request id."); } var fundRepository = new MongoRepository<Fund>(); var fund = fundRepository.GetById(id); // Ensure the fund exists. if (fund == null) { throw new HttpException(404, "NotFound. The requested fund does not exist."); } // Ensure the user has not mismatched the AreaId property. if (fundData.AreaId != fund.AreaId) { throw new HttpException(400, "BadRequest: Data does not match item associated with request id."); } if (!this.IsAuthorizedToAccessArea(fund.AreaId)) { throw new HttpException(401, "Unauthorized. You are not authorized to access this area."); } }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); IRepository repository = new MongoRepository (ConfigurationManager.AppSettings.Get("db")); container.Register<IRepository>(repository); }
public void FirstTest() { var repository = new MongoRepository<ClassTest>(Configuration.TestCollection); var count = repository.Count(); Assert.AreEqual(0, count); }
private Book(MongoRepository.Book b) { this.Title = b.Title; this.Author = b.Author; this.Publisher = b.Publisher; this.Count = b.Count; this.Price = b.Price; }
private Order(MongoRepository.Order order) { double sum = 0; foreach (MongoRepository.Book b in order.Bucket) { sum += b.Price; } this._TotalPrice = sum; this.CountBookInBucket = order.Bucket.Count; this.Client.FromDataObject(order.Client); }
public ActionResult Index() { var repository = new MongoRepository<Revision>(); if (!repository.Any()) { return RedirectToAction("Update","Revision"); } return View(repository); }
public void TestCountOne() { var repository = new MongoRepository<ClassTest>(Configuration.TestCollection); repository.Add(new ClassTest()); var count = repository.Count(); Assert.AreEqual(1, count); }
public static List<Room> GetAllActiveRooms() { var mongoRepository = new MongoRepository<Room>(ConnectionString); var oldestDate = DateTime.Now.Subtract(Constants.ActiveRoomTimeSpan); var x = mongoRepository.All(); var y = x.Where(r => r.DateLastPost >= oldestDate).ToList(); return mongoRepository.All().Where(r => r.DateLastPost >= oldestDate).ToList(); }
public void AsQueryable_InserThreeItem_ReturnTwo() { var repository = new MongoRepository<TestModel4>(); repository.Drop(); repository.Insert(new TestModel4 { StringValue = "sinan" }); repository.Insert(new TestModel4 { StringValue = "sinan" }); repository.Insert(new TestModel4 { StringValue = "ali" }); var list = repository.AsQueryable().Where(x => x.StringValue == "sinan"); Assert.AreEqual(2, list.Count()); }
public void ExistsUniqueItem_OnlySelf_ReturnNull() { var repository = new MongoRepository<TestModel>(); repository.Drop(); var item = new TestModel { StringValue = "sinan" }; var item2 = new TestModel { StringValue = "sinan" }; repository.Insert(item); var result = repository.ExistsUniqueItem(item2); Assert.IsTrue(result); }
public void ExistsUniqueItem_Own_ReturnItem() { var repository = new MongoRepository<TestModel>(); repository.Drop(); var item = TestModel.CreateInstance(); repository.Insert(item); item.IntValue = 5; var result = repository.ExistsUniqueItem(item); Assert.IsFalse(result); }
protected void Page_Load(object sender, EventArgs e) { //test the MongoDB IRepository<Test> testRepo = new MongoRepository<Test>(); var t = new Test(); t.Name = "testMNG"; testRepo.Insert(t); }
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 ChatWindow(string user) { InitializeComponent(); this.repo = new MongoRepository(); this.user = user; this.LoadChatMessages(); this.timer = new DispatcherTimer(); this.timer.Interval = TimeSpan.FromSeconds(1); this.timer.Start(); this.timer.Tick += new EventHandler(OnTimeElapsed); }
//// GET: api/AvaliableList/5 //public string Get(int id) //{ // return "value"; //} // POST: api/AvaliableList public void Post([FromBody] string value) { using (MongoRepository _repository = new MongoRepository()) { DbReceipeType result = _repository.RetrieveLastInserted<DbReceipeType>("ReciepeType", "ReciepeID"); DbReceipeType document = new DbReceipeType((result.ReciepeID + 1), value); _repository.InsertCollection<DbReceipeType>("ReciepeType", document); } }
// POST: api/Reciepe public void Post([FromBody] Receipe value) { using (MongoRepository _repository = new MongoRepository()) { DbReceipe result =_repository.RetrieveLastInserted<DbReceipe>("Reciepe","ReciepeID"); DbReceipe document = new DbReceipe((result.ReciepeID + 1),value.ReceipeTypeID,value.Name,value.Ingredients,value.Instructions,value.CookingTime,value.PreparationTime,value.IsHealthy,value.IsDiabetic,false,value.ImageUrl); _repository.InsertCollection<DbReceipe>("Reciepe", document); } }
public DestaqueService(IOptions <Settings> settings) { _repository = new MongoRepository(settings); }
public static void CreateReports(long groupId, DateTime date) { MongoRepository mongoreppo = new MongoRepository("GroupdailyReports"); Domain.Socioboard.Models.Mongo.GroupdailyReports _GroupdailyReports = new Domain.Socioboard.Models.Mongo.GroupdailyReports(); string getsexratiodata = gettwittersexdivision(groupId, date); string[] ratiodata = getsexratiodata.Split(','); _GroupdailyReports.date = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); try { _GroupdailyReports.fbfan = getfbfans(groupId, date); } catch (Exception) { } _GroupdailyReports.femalecount = Convert.ToInt64(ratiodata[1]); _GroupdailyReports.GroupId = groupId; _GroupdailyReports.id = ObjectId.GenerateNewId(); try { _GroupdailyReports.inbox = getinboxcount(groupId, date); } catch (Exception) { _GroupdailyReports.inbox = 0; } try { _GroupdailyReports.interaction = getinteractions(groupId, date); } catch (Exception) { _GroupdailyReports.interaction = 0; } _GroupdailyReports.malecount = Convert.ToInt64(ratiodata[0]); try { _GroupdailyReports.sent = getsentmessage(groupId, date); } catch (Exception) { _GroupdailyReports.sent = 0; } try { _GroupdailyReports.twitterfollower = gettwitterfollowers(groupId, date); } catch { _GroupdailyReports.twitterfollower = 0; } try { _GroupdailyReports.twitter_account_count = total_twitter_accounts(groupId); } catch (Exception) { _GroupdailyReports.twitter_account_count = 0; } try { _GroupdailyReports.twtmentions = gettwtmentions(groupId, date); } catch (Exception) { _GroupdailyReports.twtmentions = 0; } try { _GroupdailyReports.twtretweets = gettwtretweets(groupId, date); } catch (Exception) { _GroupdailyReports.twtretweets = 0; } try { _GroupdailyReports.uniqueusers = uniquetwitteruser(groupId, date); } catch (Exception) { _GroupdailyReports.uniqueusers = 0; } try { _GroupdailyReports.plainText = getsentmessagePlainText(groupId, date); } catch (Exception ex) { _GroupdailyReports.plainText = 0; } try { _GroupdailyReports.photoLinks = getsentmessagephotoLinks(groupId, date); } catch (Exception) { _GroupdailyReports.photoLinks = 0; } try { _GroupdailyReports.linkstoPages = getsentmessagelinkstoPages(groupId, date); } catch (Exception) { _GroupdailyReports.linkstoPages = 0; } try { _GroupdailyReports.facebookPageCount = facebookPageCount(groupId); } catch (Exception) { _GroupdailyReports.facebookPageCount = 0; } var ret = mongoreppo.Find <Domain.Socioboard.Models.Mongo.GroupdailyReports>(t => t.date == SBHelper.ConvertToUnixTimestamp(date) && t.GroupId == groupId); var task = Task.Run(async() => { return(await ret); }); IList <Domain.Socioboard.Models.Mongo.GroupdailyReports> lstDailyReports = task.Result.ToList(); if (lstDailyReports.Count() > 0) { lstDailyReports.First().uniqueusers = _GroupdailyReports.uniqueusers; lstDailyReports.First().twtretweets = _GroupdailyReports.twtretweets; lstDailyReports.First().twtmentions = _GroupdailyReports.twtmentions; lstDailyReports.First().twitter_account_count = _GroupdailyReports.twitter_account_count; lstDailyReports.First().date = SBHelper.ConvertToUnixTimestamp(date); lstDailyReports.First().twitterfollower = _GroupdailyReports.twitterfollower; lstDailyReports.First().sent = _GroupdailyReports.sent; lstDailyReports.First().malecount = _GroupdailyReports.malecount; lstDailyReports.First().femalecount = _GroupdailyReports.femalecount; lstDailyReports.First().interaction = _GroupdailyReports.interaction; lstDailyReports.First().inbox = _GroupdailyReports.inbox; lstDailyReports.First().GroupId = _GroupdailyReports.GroupId; lstDailyReports.First().fbfan = _GroupdailyReports.fbfan; lstDailyReports.First().linkstoPages = _GroupdailyReports.linkstoPages; lstDailyReports.First().photoLinks = _GroupdailyReports.photoLinks; lstDailyReports.First().plainText = _GroupdailyReports.plainText; lstDailyReports.First().facebookPageCount = _GroupdailyReports.facebookPageCount; mongoreppo.UpdateReplace(lstDailyReports.First(), t => t.id == lstDailyReports.First().id); } else { mongoreppo.Add <Domain.Socioboard.Models.Mongo.GroupdailyReports>(_GroupdailyReports); } }
public Task <bool> UpdateVersions() { var repository = new MongoRepository <Revision>(); var req = WebRequest.Create("https://bitbucket.org/api/1.0/repositories/apcurium/mk-taxi/tags") as HttpWebRequest; var authInfo = "buildapcurium:apcurium5200!"; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); req.Headers["Authorization"] = "Basic " + authInfo; string result = null; using (var resp = req.GetResponse() as HttpWebResponse) { var reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } var revisionsFromBitBucket = JsonConvert.DeserializeObject <Dictionary <string, BitBucketRepoResponse> >(result) .Select(x => new Revision { Id = Guid.NewGuid().ToString(), Commit = x.Value.node, Tag = x.Key }).ToList(); revisionsFromBitBucket.Add(GetDefaultRevision()); //Existing Revisions, we ignore version number tags to prevent building a version from an alternate commit. //existing revisions => update var updatesRevisions = repository .AsEnumerable() .Where(revision => !IsVersionNumber(revision)) .Join(revisionsFromBitBucket, rev => rev.Tag, revBitbucket => revBitbucket.Tag, (rev, revBitbucket) => new Revision { Id = rev.Id, Tag = rev.Tag, Commit = revBitbucket.Commit, Hidden = rev.Hidden, CustomerVisible = rev.CustomerVisible, Inactive = rev.Inactive, }) .ToArray(); if (updatesRevisions.Any()) { repository.Update(updatesRevisions); } var tagsFromRepository = repository.Select(x => x.Tag).ToList(); //new revisions in bitbucket => add to repository var newRevisions = revisionsFromBitBucket.Where(x => !tagsFromRepository.Contains(x.Tag)).ToList(); if (newRevisions.Any()) { repository.Add(newRevisions); } return(Task.Run(() => { return false; })); }
public AppController() { this.amiliaClient = new AmiliaClient(); this.mongoRepo = new MongoRepository(); }
public WeatherForecastController(ILogger <WeatherForecastController> logger, MongoRepository mongoRepository) { _logger = logger; _mongoRepository = mongoRepository; }
public TestQueryHandler(MongoRepository mongoRepository) { this._mongoRepository = mongoRepository; }
public void groupshreathon(object o) { try { object[] arr = o as object[]; GroupShareathon shareathon = (GroupShareathon)arr[0]; Model.DatabaseRepository dbr = (Model.DatabaseRepository)arr[1]; MongoRepository _ShareathonRepository = (MongoRepository)arr[2]; string[] ids = shareathon.Facebookpageid.Split(','); foreach (string id in ids) { try { int groupapiHitsCountNew = 0; Domain.Socioboard.Models.Facebookaccounts fbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == shareathon.Facebookaccountid); Domain.Socioboard.Models.Facebookaccounts facebookPage = null; Domain.Socioboard.Models.Facebookaccounts lstFbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == id); if (fbAcc != null) { if (groupapiHitsCountNew < groupMaxapiHitsCount) { string feeds = string.Empty; if (fbAcc.GroupShareathonUpdate.AddHours(1) <= DateTime.UtcNow) { feeds = Socioboard.Facebook.Data.Fbpages.getFacebookRecentPost(fbAcc.AccessToken, id); string feedId = string.Empty; if (!string.IsNullOrEmpty(feeds) && !feeds.Equals("[]")) { groupapiHitsCountNew++; JObject fbpageNotes = JObject.Parse(feeds); foreach (JObject obj in JArray.Parse(fbpageNotes["data"].ToString())) { try { string feedid = obj["id"].ToString(); feedid = feedid.Split('_')[1]; feedId = feedid + "," + feedId; } catch { } } try { DateTime dt = SBHelper.ConvertFromUnixTimestamp(shareathon.Lastsharetimestamp); dt = dt.AddMinutes(shareathon.Timeintervalminutes); if (shareathon.Lastpostid == null || (!shareathon.Lastpostid.Equals(feedId) && SBHelper.ConvertToUnixTimestamp(dt) <= SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow))) { //if (groupapiHitsCountNew < groupMaxapiHitsCount) //{ ShareFeedonGroup(fbAcc.AccessToken, feedId, id, "", shareathon.Facebookgroupid, shareathon.Timeintervalminutes, shareathon.Facebookaccountid, shareathon.Lastsharetimestamp, shareathon.Facebooknameid); //} } fbAcc.GroupShareathonUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc); } catch (Exception ex) { } } else { FilterDefinition <BsonDocument> filter = new BsonDocument("strId", shareathon.strId); var update = Builders <BsonDocument> .Update.Set("FacebookStatus", 1); _ShareathonRepository.Update <Domain.Socioboard.Models.Mongo.GroupShareathon>(update, filter); groupapiHitsCount = groupMaxapiHitsCount; } } else { groupapiHitsCount = 0; } } } //fbAcc.SchedulerUpdate = DateTime.UtcNow; //dbr.Update<Domain.Socioboard.Models.Facebookaccounts>(fbAcc); } catch { groupapiHitsCount = groupMaxapiHitsCount; } } } catch (Exception e) { groupapiHitsCount = groupMaxapiHitsCount; } finally { noOfthread_groupshreathonRunning--; } }
private static void TwitterSchedulemessage(object o) { try { MongoRepository mongorepo = new Helper.MongoRepository("ContentFeedsShareathon"); int pageapiHitsCount; object[] arr = o as object[]; FacebookPageFeedShare shareathon = (FacebookPageFeedShare)arr[0]; Model.DatabaseRepository dbr = (Model.DatabaseRepository)arr[1]; MongoRepository _ShareathonRepository = (MongoRepository)arr[2]; string[] ids = shareathon.socialProfiles.Split(','); foreach (string id in ids) { Domain.Socioboard.Models.TwitterAccount _TwitterAccount = dbr.Single <Domain.Socioboard.Models.TwitterAccount>(t => t.twitterUserId == id && t.isActive); Domain.Socioboard.Models.LinkedInAccount _LinkedinAcc = dbr.Single <Domain.Socioboard.Models.LinkedInAccount>(t => t.LinkedinUserId == id && t.IsActive); Domain.Socioboard.Models.User _user = dbr.Single <Domain.Socioboard.Models.User>(t => t.Id == _TwitterAccount.userId); MongoRepository mongoshare = new Helper.MongoRepository("FacebookPageFeedShare"); if (_TwitterAccount != null || _LinkedinAcc != null) { var resultshare = _ShareathonRepository.Find <FacebookPageFeedShare>(t => t.pageId == shareathon.pageId && t.status != Domain.Socioboard.Enum.RealTimeShareFeedStatus.deleted); var task = Task.Run(async() => { return(await resultshare); }); int count = task.Result.Count; var feedsData = task.Result.ToList(); if (count != 0) { foreach (var item in feedsData) { if (item.socialmedia.StartsWith("tw")) { try { Console.WriteLine(item.socialProfiles + "Scheduling Started"); PostTwitterMessage(item, _TwitterAccount, null, _user); Console.WriteLine(item.socialProfiles + "Scheduling"); } catch (Exception) { Thread.Sleep(60000); } } if (item.socialmedia.StartsWith("lin")) { try { Console.WriteLine(item.socialProfiles + "Scheduling Started"); PostTwitterMessage(item, null, _LinkedinAcc, _user); Console.WriteLine(item.socialProfiles + "Scheduling"); } catch (Exception) { Thread.Sleep(60000); } } } //fbAcc.contenetShareathonUpdate = DateTime.UtcNow; //facebookPage.contenetShareathonUpdate = DateTime.UtcNow; //dbr.Update<Domain.Socioboard.Models.Facebookaccounts>(fbAcc); //dbr.Update<Domain.Socioboard.Models.Facebookaccounts>(facebookPage); } //_TwitterAccount.SchedulerUpdate = DateTime.UtcNow; // dbr.Update<Domain.Socioboard.Models.TwitterAccount>(_TwitterAccount); } } } catch (Exception ex) { Thread.Sleep(60000); } finally { noOfthreadRunning--; objSemaphore.Release(); Console.WriteLine(Thread.CurrentThread.Name + " Is Released"); } }
public void Page <TKey>(int pageIndex, int pageSize, Expression <Func <T, TKey> > orderBy, bool isOrderByAsc = true, Expression <Func <T, bool> > where = null, ISnapshotCollection snapshot = null) { var collection = GetCollectionSnapOrNon(snapshot); var repo = new MongoRepository <T>(collection); var result = repo.Pagination(pageIndex, pageSize, orderBy, isOrderByAsc, where); }
public IActionResult SchedulePagePost(string profileId, int TimeInterVal, long UserId) { int addedPageCount = 0; int invalidaccessToken = 0; profileId = profileId.TrimEnd(','); try { try { foreach (var items in profileId.Split(',')) { string pageUrls = Request.Form["pageUrls"]; Domain.Socioboard.Models.Facebookaccounts _Facebookaccounts = new Facebookaccounts(); DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); _Facebookaccounts = FacebookRepository.getFacebookAccount(items, _redisCache, dbr); List <Domain.Socioboard.Models.Mongo.PageDetails> pageid = Helper.FacebookHelper.GetFbPagePostDetails(pageUrls, _Facebookaccounts.AccessToken); if (pageid.Count == 0) { invalidaccessToken++; } foreach (Domain.Socioboard.Models.Mongo.PageDetails item in pageid) { addedPageCount++; if (_Facebookaccounts != null) { LinkShareathon _LinkShareathon = new LinkShareathon(); _LinkShareathon.Id = ObjectId.GenerateNewId(); _LinkShareathon.strId = ObjectId.GenerateNewId().ToString(); _LinkShareathon.Userid = UserId; _LinkShareathon.Facebookusername = _Facebookaccounts.FbUserName; _LinkShareathon.FacebookPageUrl = item.PageUrl; _LinkShareathon.TimeInterVal = TimeInterVal; _LinkShareathon.Facebookpageid = item.PageId; _LinkShareathon.IsActive = true; MongoRepository _ShareathonRepository = new MongoRepository("LinkShareathon", _appSettings); _ShareathonRepository.Add(_LinkShareathon); new Thread(delegate() { Helper.FacebookHelper.schedulePage_Post(_Facebookaccounts.AccessToken, item.PageId, TimeInterVal); }).Start(); } } } } catch (Exception ex) { } } catch (System.Exception ex) { } if (addedPageCount == profileId.Length) { return(Ok("successfully added")); } else if (invalidaccessToken > 0) { return(Ok(invalidaccessToken + "pages access token expired")); } return(Ok("successfully added")); }
//todo : need to write codes to get all comments public static string AddFbPostComments(string postid, string AccessToken) { MongoFbPostComment fbPostComment = new MongoFbPostComment(); string ret = string.Empty; try { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls; apiHitsCount++; //while (apiHitsCount < MaxapiHitsCount ) //{ //} dynamic post = Socioboard.Facebook.Data.FbUser.GetPostComments(AccessToken, postid); foreach (var item in post["data"]) { fbPostComment.Id = MongoDB.Bson.ObjectId.GenerateNewId(); fbPostComment.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); fbPostComment.PostId = postid; try { fbPostComment.CommentId = item["id"]; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.Comment = item["message"]; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.Likes = Convert.ToInt32(item["like_count"]); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.UserLikes = Convert.ToInt32(item["user_likes"]); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.Commentdate = DateTime.Parse(item["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { fbPostComment.Commentdate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); } try { fbPostComment.FromName = item["from"]["name"]; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.FromId = item["from"]["id"]; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { fbPostComment.PictureUrl = item["id"]; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { MongoRepository fbPostRepo = new MongoRepository("MongoFbPostComment"); var retur = fbPostRepo.Find <MongoFbPostComment>(t => t.CommentId == fbPostComment.CommentId && t.PostId == fbPostComment.PostId); var task = Task.Run(async() => { return(await retur); }); int count = task.Result.Count; if (count < 1) { fbPostRepo.Add <MongoFbPostComment>(fbPostComment); } } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } try { // AddFbPagePostCommentsLikes(objFbPageComment.CommentId, accesstoken, userid); } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } } } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } return(ret); }
public int updateFacebookFeeds(Domain.Socioboard.Models.Facebookaccounts fbAcc) { apiHitsCount = 0; var databaseRepository = new DatabaseRepository(); if (fbAcc.LastUpdate.AddHours(1) <= DateTime.UtcNow) { if (fbAcc.IsAccessTokenActive) { var feeds = FacebookApiHelper.GetOwnFeedDetails(fbAcc.AccessToken); dynamic profile = FacebookApiHelper.GetUserDetails(fbAcc.AccessToken); apiHitsCount++; if (Convert.ToString(profile) != "Invalid Access Token") { fbAcc.Friends = FacebookApiHelper.GetFriendCounts(fbAcc.AccessToken); apiHitsCount++; try { fbAcc.EmailId = Convert.ToString(profile["email"]); } catch { fbAcc.EmailId = fbAcc.EmailId; } try { fbAcc.ProfileUrl = (Convert.ToString(profile["link"])); } catch { fbAcc.ProfileUrl = (Convert.ToString(profile["picture"]["data"]["url"])); } try { fbAcc.Gender = (Convert.ToString(profile["gender"])); } catch { fbAcc.Gender = fbAcc.Gender; } try { fbAcc.Bio = (Convert.ToString(profile["bio"])); } catch { fbAcc.Bio = fbAcc.Bio; } try { fbAcc.About = (Convert.ToString(profile["about"])); } catch { fbAcc.About = fbAcc.About; } try { fbAcc.CoverPic = (Convert.ToString(profile["cover"]["source"])); } catch { fbAcc.CoverPic = fbAcc.CoverPic; } try { fbAcc.Birthday = (Convert.ToString(profile["birthday"])); } catch { fbAcc.Birthday = fbAcc.Birthday; } try { JArray arry = JArray.Parse(profile["education"]); if (arry.Count > 0) { fbAcc.College = Convert.ToString(arry[arry.Count - 1]["school"]["name"]); fbAcc.Education = Convert.ToString(arry[arry.Count - 1]["concentration"]["name"]); } } catch { fbAcc.College = fbAcc.College; fbAcc.Education = fbAcc.Education; } try { JArray arry = JArray.Parse(profile["work"]); if (arry.Count > 0) { fbAcc.WorkPosition = Convert.ToString(arry[0]["position"]["name"]); fbAcc.WorkCompany = Convert.ToString(arry[0]["employer"]["name"]); } } catch { fbAcc.WorkPosition = fbAcc.WorkPosition; fbAcc.WorkCompany = fbAcc.WorkCompany; } try { databaseRepository.Update(fbAcc); } catch { } if (apiHitsCount < MaxapiHitsCount && feeds != null && feeds["data"] != null) { apiHitsCount++; if (feeds["data"] != null) { Console.WriteLine(feeds["data"]); foreach (var result in feeds["data"]) { MongoFacebookFeed objFacebookFeed = new MongoFacebookFeed(); objFacebookFeed.Type = "fb_feed"; objFacebookFeed.ProfileId = fbAcc.FbUserId; objFacebookFeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); try { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; } catch (Exception) { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + fbAcc.FbUserId + "/picture?type=small"; } try { objFacebookFeed.FromName = result["from"]["name"].ToString(); } catch (Exception) { objFacebookFeed.FromName = fbAcc.FbUserName; } try { objFacebookFeed.FromId = result["from"]["id"].ToString(); } catch (Exception) { objFacebookFeed.FromId = fbAcc.FbUserId; } objFacebookFeed.FeedId = result["id"].ToString(); try { objFacebookFeed.FeedDateToshow = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); objFacebookFeed.FeedDate = Domain.Socioboard.Helpers.SBHelper.ConvertToUnixTimestamp(Convert.ToDateTime(objFacebookFeed.FeedDateToshow)).ToString(); objFacebookFeed.FeedDateToshow = Domain.Socioboard.Helpers.SBHelper.ConvertFromUnixTimestamp(Convert.ToDouble(objFacebookFeed.FeedDate)).ToString("yyyy/MM/dd HH:mm:ss"); } catch (Exception ex) { } try { objFacebookFeed.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; objFacebookFeed.FbLike = "http://graph.facebook.com/" + result["id"] + "/likes"; } catch (Exception) { } try { objFacebookFeed.Likecount = result["likes"]["summary"]["total_count"].ToString(); } catch (Exception ex) { } try { objFacebookFeed.Commentcount = result["comments"]["summary"]["total_count"].ToString(); } catch (Exception ex) { } try { objFacebookFeed.postType = result["type"].ToString(); } catch { objFacebookFeed.postType = "status"; } try { objFacebookFeed.postingFrom = result["application"]["name"].ToString(); } catch { objFacebookFeed.postingFrom = "Facebook"; } try { objFacebookFeed.Picture = result["picture"].ToString(); } catch (Exception ex) { objFacebookFeed.Picture = ""; } string message = string.Empty; try { if (result["message"] != null) { message = result["message"]; } } catch (Exception ex) { try { if (result["description"] != null) { message = result["description"]; } } catch (Exception exx) { try { if (result["story"] != null) { message = result["story"]; } } catch (Exception exxx) { message = string.Empty; } } } if (message == null) { message = ""; } dynamic comment; try { comment = result["comments"]; } catch (Exception) { comment = null; } objFacebookFeed.FeedDescription = message; objFacebookFeed.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); //objFacebookFeed._facebookComment = FbPostComments(objFacebookFeed.FeedId, fbAcc.AccessToken); objFacebookFeed._facebookComment = FbPostComments(objFacebookFeed.FeedId, comment); try { MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); var ret = mongorepo.Find <MongoFacebookFeed>(t => t.FeedId == objFacebookFeed.FeedId && t.ProfileId == objFacebookFeed.ProfileId); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { mongorepo.Add <MongoFacebookFeed>(objFacebookFeed); } else { try { FilterDefinition <BsonDocument> filter = new BsonDocument("FeedId", objFacebookFeed.FeedId); var update = Builders <BsonDocument> .Update.Set("postType", objFacebookFeed.postType).Set("postingFrom", objFacebookFeed.postingFrom).Set("Likecount", objFacebookFeed.Likecount).Set("Commentcount", objFacebookFeed.Commentcount).Set("_facebookComment", objFacebookFeed._facebookComment); mongorepo.Update <MongoFacebookFeed>(update, filter); } catch { } } } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } if (apiHitsCount < MaxapiHitsCount) { //AddFbPostComments(objFacebookFeed.FeedId, fbAcc.AccessToken); } } } else { apiHitsCount = MaxapiHitsCount; } try { feeds = Socioboard.Facebook.Data.FbUser.fbGet(fbAcc.AccessToken, feeds["paging"]["next"]); } catch { apiHitsCount = MaxapiHitsCount; } } fbAcc.LastUpdate = DateTime.UtcNow; databaseRepository.Update(fbAcc); } } } else { apiHitsCount = 0; } return(0); }
public void CollectionNamesTest() { var a = new MongoRepository <Animal>(); var am = new MongoRepositoryManager <Animal>(); var va = new Dog(); Assert.IsFalse(am.Exists); a.Update(va); Assert.IsTrue(am.Exists); Assert.IsInstanceOfType(a.GetById(va.Id), typeof(Dog)); Assert.AreEqual(am.Name, "AnimalsTest"); Assert.AreEqual(a.CollectionName, "AnimalsTest"); var cl = new MongoRepository <CatLike>(); var clm = new MongoRepositoryManager <CatLike>(); var vcl = new Lion(); Assert.IsFalse(clm.Exists); cl.Update(vcl); Assert.IsTrue(clm.Exists); Assert.IsInstanceOfType(cl.GetById(vcl.Id), typeof(Lion)); Assert.AreEqual(clm.Name, "Catlikes"); Assert.AreEqual(cl.CollectionName, "Catlikes"); var b = new MongoRepository <Bird>(); var bm = new MongoRepositoryManager <Bird>(); var vb = new Bird(); Assert.IsFalse(bm.Exists); b.Update(vb); Assert.IsTrue(bm.Exists); Assert.IsInstanceOfType(b.GetById(vb.Id), typeof(Bird)); Assert.AreEqual(bm.Name, "Birds"); Assert.AreEqual(b.CollectionName, "Birds"); var l = new MongoRepository <Lion>(); var lm = new MongoRepositoryManager <Lion>(); var vl = new Lion(); //Assert.IsFalse(lm.Exists); //Should already exist (created by cl) l.Update(vl); Assert.IsTrue(lm.Exists); Assert.IsInstanceOfType(l.GetById(vl.Id), typeof(Lion)); Assert.AreEqual(lm.Name, "Catlikes"); Assert.AreEqual(l.CollectionName, "Catlikes"); var d = new MongoRepository <Dog>(); var dm = new MongoRepositoryManager <Dog>(); var vd = new Dog(); //Assert.IsFalse(dm.Exists); d.Update(vd); Assert.IsTrue(dm.Exists); Assert.IsInstanceOfType(d.GetById(vd.Id), typeof(Dog)); Assert.AreEqual(dm.Name, "AnimalsTest"); Assert.AreEqual(d.CollectionName, "AnimalsTest"); var m = new MongoRepository <Bird>(); var mm = new MongoRepositoryManager <Bird>(); var vm = new Macaw(); //Assert.IsFalse(mm.Exists); m.Update(vm); Assert.IsTrue(mm.Exists); Assert.IsInstanceOfType(m.GetById(vm.Id), typeof(Macaw)); Assert.AreEqual(mm.Name, "Birds"); Assert.AreEqual(m.CollectionName, "Birds"); var w = new MongoRepository <Whale>(); var wm = new MongoRepositoryManager <Whale>(); var vw = new Whale(); Assert.IsFalse(wm.Exists); w.Update(vw); Assert.IsTrue(wm.Exists); Assert.IsInstanceOfType(w.GetById(vw.Id), typeof(Whale)); Assert.AreEqual(wm.Name, "Whale"); Assert.AreEqual(w.CollectionName, "Whale"); }
public static int UpdateLinkedInComanyPageFeed(Domain.Socioboard.Models.LinkedinCompanyPage linacc, oAuthLinkedIn _oauth) { DatabaseRepository dbr = new DatabaseRepository(); List <Domain.Socioboard.Models.Groupprofiles> _grpProfile = dbr.Find <Domain.Socioboard.Models.Groupprofiles>(t => t.profileId.Contains(linacc.LinkedinPageId)).ToList(); apiHitsCount = 0; if (linacc.lastUpdate.AddHours(1) <= DateTime.UtcNow) { if (linacc.IsActive) { dynamic profile = GetCompanyPageData(_oauth, linacc.LinkedinPageId); try { string NuberOfFollower = profile.num_followers.ToString(); linacc.NumFollowers = Convert.ToInt16(NuberOfFollower); } catch { linacc.NumFollowers = linacc.NumFollowers; } try { linacc.CompanyType = profile.company_type.ToString(); } catch { linacc.CompanyType = linacc.CompanyType; } try { linacc.LogoUrl = profile.logo_url.ToString(); _grpProfile.Select(s => { s.profilePic = linacc.LogoUrl; return(s); }).ToList(); } catch { linacc.LogoUrl = linacc.LogoUrl; _grpProfile.Select(s => { s.profilePic = linacc.LogoUrl; return(s); }).ToList(); } try { linacc.SquareLogoUrl = profile.square_logo_url.ToString(); } catch { linacc.SquareLogoUrl = linacc.SquareLogoUrl; } try { linacc.BlogRssUrl = profile.blog_rss_url.ToString(); } catch { linacc.BlogRssUrl = linacc.BlogRssUrl; } try { linacc.UniversalName = profile.universal_name.ToString(); } catch { linacc.UniversalName = linacc.UniversalName; } dbr.Update <Domain.Socioboard.Models.LinkedinCompanyPage>(linacc); foreach (var item_grpProfile in _grpProfile) { dbr.Update <Domain.Socioboard.Models.Groupprofiles>(item_grpProfile); } try { List <LinkedinPageUpdate.CompanyPagePosts> objcompanypagepost = objLinkedinPageUpdate.GetPagePosts(_oauth, linacc.LinkedinPageId); if (apiHitsCount < MaxapiHitsCount && objcompanypagepost != null) { apiHitsCount++; LinkedinCompanyPagePosts lipagepost = new LinkedinCompanyPagePosts(); if (objcompanypagepost != null) { 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 = linacc.UserId; lipagepost.Type = item.Type; lipagepost.PostId = item.PostId; lipagepost.UpdateKey = item.UpdateKey; lipagepost.PageId = linacc.LinkedinPageId; lipagepost.PostImageUrl = item.PostImageUrl; lipagepost.Likes = item.Likes; lipagepost.Comments = item.Comments; MongoRepository _CompanyPagePostsRepository = new MongoRepository("LinkedinCompanyPagePosts"); 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); } } } else { apiHitsCount = MaxapiHitsCount; } } } catch (Exception) { } linacc.lastUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.LinkedinCompanyPage>(linacc); } } else { apiHitsCount = 0; } return(0); }
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 HomeController(IConfiguration Configuration, IHttpContextAccessor httpContextAccessor, MongoRepository mr, GameLogic gl) { _repo = mr; _gl = gl; try { _current_user = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; } catch (NullReferenceException) { } }
public void pageshreathon(object o) { try { object[] arr = o as object[]; PageShareathon shareathon = (PageShareathon)arr[0]; Model.DatabaseRepository dbr = (Model.DatabaseRepository)arr[1]; MongoRepository _ShareathonRepository = (MongoRepository)arr[2]; string[] ids = shareathon.Facebookpageid.Split(','); foreach (string id in ids) { try { pageapiHitsCount = 0; Domain.Socioboard.Models.Facebookaccounts fbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == shareathon.Facebookaccountid); Domain.Socioboard.Models.Facebookaccounts facebookPage = null; Domain.Socioboard.Models.Facebookaccounts lstFbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == id); if (lstFbAcc != null) { facebookPage = lstFbAcc; } if (facebookPage != null) { if (pageapiHitsCount < pageMaxapiHitsCount) { string feeds = string.Empty; if (facebookPage.PageShareathonUpdate.AddHours(1) <= DateTime.UtcNow) { feeds = Socioboard.Facebook.Data.Fbpages.getFacebookRecentPost(fbAcc.AccessToken, facebookPage.FbUserId); string feedId = string.Empty; if (!string.IsNullOrEmpty(feeds) && !feeds.Equals("[]")) { pageapiHitsCount++; JObject fbpageNotes = JObject.Parse(feeds); foreach (JObject obj in JArray.Parse(fbpageNotes["data"].ToString())) { try { feedId = obj["id"].ToString(); feedId = feedId.Split('_')[1]; DateTime dt = SBHelper.ConvertFromUnixTimestamp(shareathon.Lastsharetimestamp); dt = dt.AddMinutes(shareathon.Timeintervalminutes); if ((!shareathon.Lastpostid.Equals(feedId) && SBHelper.ConvertToUnixTimestamp(dt) <= SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow))) { //if (pageapiHitsCount < pageMaxapiHitsCount) //{ string ret = ShareFeed(fbAcc.AccessToken, feedId, facebookPage.FbUserId, "", fbAcc.FbUserId, facebookPage.FbUserName); if (!string.IsNullOrEmpty(ret)) { Thread.Sleep(1000 * 60 * shareathon.Timeintervalminutes); } // } } } catch { pageapiHitsCount = pageMaxapiHitsCount; } } fbAcc.PageShareathonUpdate = DateTime.UtcNow; facebookPage.PageShareathonUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc); dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(facebookPage); } else { FilterDefinition <BsonDocument> filter = new BsonDocument("strId", shareathon.strId); var update = Builders <BsonDocument> .Update.Set("FacebookStatus", 1); _ShareathonRepository.Update <Domain.Socioboard.Models.Mongo.PageShareathon>(update, filter); } } else { pageapiHitsCount = 0; } } } } catch { pageapiHitsCount = pageMaxapiHitsCount; } } try { if (!string.IsNullOrEmpty(shareathon.FacebookPageUrlId)) { string[] urlsIds = shareathon.FacebookPageUrlId.Split(','); foreach (string id_url in urlsIds) { try { pageapiHitsCount = 0; Domain.Socioboard.Models.Facebookaccounts fbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == shareathon.Facebookaccountid); string pagename = Socioboard.Facebook.Data.Fbpages.getFbPageData(fbAcc.AccessToken, id_url); if (pageapiHitsCount < pageMaxapiHitsCount) { string feeds = string.Empty; feeds = Socioboard.Facebook.Data.Fbpages.getFacebookRecentPost(fbAcc.AccessToken, id_url); string feedId = string.Empty; if (!string.IsNullOrEmpty(feeds) && !feeds.Equals("[]")) { pageapiHitsCount++; JObject fbpageNotes = JObject.Parse(feeds); foreach (JObject obj in JArray.Parse(fbpageNotes["data"].ToString())) { try { feedId = obj["id"].ToString(); feedId = feedId.Split('_')[1]; DateTime dt = SBHelper.ConvertFromUnixTimestamp(shareathon.Lastsharetimestamp); dt = dt.AddMinutes(shareathon.Timeintervalminutes); if ((!shareathon.Lastpostid.Equals(feedId) && SBHelper.ConvertToUnixTimestamp(dt) <= SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow))) { string ret = ShareFeed(fbAcc.AccessToken, feedId, id_url, "", fbAcc.FbUserId, pagename); if (!string.IsNullOrEmpty(ret)) { Thread.Sleep(1000 * 60 * shareathon.Timeintervalminutes); } } } catch { pageapiHitsCount = pageMaxapiHitsCount; } } fbAcc.PageShareathonUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc); } else { FilterDefinition <BsonDocument> filter = new BsonDocument("strId", shareathon.strId); var update = Builders <BsonDocument> .Update.Set("FacebookStatus", 1); _ShareathonRepository.Update <Domain.Socioboard.Models.Mongo.PageShareathon>(update, filter); } } } catch { pageapiHitsCount = pageMaxapiHitsCount; } } } } catch (Exception) { } } catch (Exception e) { pageapiHitsCount = pageMaxapiHitsCount; } finally { noOfthread_pageshreathonRunning--; } }
public void Constructor_ValidArgument_Success() { _ = new MongoRepository <A>(_collection.Object); }
public SecurityGateway(MongoReqTrackDatabase database) { _securityRightsRepository = new MongoRepository <MongoSecurityRights>(database.SecurityRightsCollection); _userRepository = new MongoRepository <MongoUser>(database.UserCollection); _projectRepository = new MongoRepository <MongoProject>(database.ProjectCollection); }
public int updateFacebookFeeds(Domain.Socioboard.Models.Facebookaccounts fbAcc) { apiHitsCount = 0; Model.DatabaseRepository dbr = new DatabaseRepository(); if (fbAcc.LastUpdate.AddHours(1) <= DateTime.UtcNow) { if (fbAcc.IsAccessTokenActive) { dynamic feeds = Socioboard.Facebook.Data.FbUser.getFeeds(fbAcc.AccessToken); dynamic profile = Socioboard.Facebook.Data.FbUser.getFbUser(fbAcc.AccessToken); apiHitsCount++; if (Convert.ToString(profile) != "Invalid Access Token") { fbAcc.Friends = Socioboard.Facebook.Data.FbUser.getFbFriends(fbAcc.AccessToken); apiHitsCount++; try { fbAcc.EmailId = (Convert.ToString(profile["email"])); } catch { fbAcc.EmailId = fbAcc.EmailId; } try { fbAcc.ProfileUrl = (Convert.ToString(profile["link"])); } catch { fbAcc.ProfileUrl = fbAcc.ProfileUrl; } try { fbAcc.gender = (Convert.ToString(profile["gender"])); } catch { fbAcc.gender = fbAcc.gender; } try { fbAcc.bio = (Convert.ToString(profile["bio"])); } catch { fbAcc.bio = fbAcc.bio; } try { fbAcc.about = (Convert.ToString(profile["about"])); } catch { fbAcc.about = fbAcc.about; } try { fbAcc.coverPic = (Convert.ToString(profile["cover"]["source"])); } catch { fbAcc.coverPic = fbAcc.coverPic; } try { fbAcc.birthday = (Convert.ToString(profile["birthday"])); } catch { fbAcc.birthday = fbAcc.birthday; } try { JArray arry = JArray.Parse(profile["education"]); if (arry.Count > 0) { fbAcc.college = Convert.ToString(arry[arry.Count - 1]["school"]["name"]); fbAcc.education = Convert.ToString(arry[arry.Count - 1]["concentration"]["name"]); } } catch { fbAcc.college = fbAcc.college; fbAcc.education = fbAcc.education; } try { JArray arry = JArray.Parse(profile["work"]); if (arry.Count > 0) { fbAcc.workPosition = Convert.ToString(arry[0]["position"]["name"]); fbAcc.workCompany = Convert.ToString(arry[0]["employer"]["name"]); } } catch { fbAcc.workPosition = fbAcc.workPosition; fbAcc.workCompany = fbAcc.workCompany; } try { dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc); } catch { } while (apiHitsCount < MaxapiHitsCount && feeds != null && feeds["data"] != null) { apiHitsCount++; if (feeds["data"] != null) { Console.WriteLine(feeds["data"]); foreach (var result in feeds["data"]) { MongoFacebookFeed objFacebookFeed = new MongoFacebookFeed(); objFacebookFeed.Type = "fb_feed"; objFacebookFeed.ProfileId = fbAcc.FbUserId; objFacebookFeed.Id = MongoDB.Bson.ObjectId.GenerateNewId(); try { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + result["from"]["id"] + "/picture?type=small"; } catch (Exception) { objFacebookFeed.FromProfileUrl = "http://graph.facebook.com/" + fbAcc.FbUserId + "/picture?type=small"; } try { objFacebookFeed.FromName = result["from"]["name"].ToString(); } catch (Exception) { objFacebookFeed.FromName = fbAcc.FbUserName; } try { objFacebookFeed.FromId = result["from"]["id"].ToString(); } catch (Exception) { objFacebookFeed.FromId = fbAcc.FbUserId; } objFacebookFeed.FeedId = result["id"].ToString(); objFacebookFeed.FeedDate = DateTime.Parse(result["created_time"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); try { objFacebookFeed.FbComment = "http://graph.facebook.com/" + result["id"] + "/comments"; objFacebookFeed.FbLike = "http://graph.facebook.com/" + result["id"] + "/likes"; } catch (Exception) { } try { objFacebookFeed.Picture = result["picture"].ToString(); } catch (Exception ex) { objFacebookFeed.Picture = ""; } string message = string.Empty; try { if (result["message"] != null) { message = result["message"]; } } catch (Exception ex) { try { if (result["description"] != null) { message = result["description"]; } } catch (Exception exx) { try { if (result["story"] != null) { message = result["story"]; } } catch (Exception exxx) { message = string.Empty; } } } if (message == null) { message = ""; } objFacebookFeed.FeedDescription = message; objFacebookFeed.EntryDate = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"); try { MongoRepository mongorepo = new MongoRepository("MongoFacebookFeed"); var ret = mongorepo.Find <MongoFacebookFeed>(t => t.FeedId == objFacebookFeed.FeedId && t.ProfileId == objFacebookFeed.ProfileId); var task = Task.Run(async() => { return(await ret); }); int count = task.Result.Count; if (count < 1) { mongorepo.Add <MongoFacebookFeed>(objFacebookFeed); } } catch (Exception ex) { //_logger.LogInformation(ex.Message); //_logger.LogError(ex.StackTrace); } if (apiHitsCount < MaxapiHitsCount) { AddFbPostComments(objFacebookFeed.FeedId, fbAcc.AccessToken); } } } else { apiHitsCount = MaxapiHitsCount; } try { feeds = Socioboard.Facebook.Data.FbUser.fbGet(fbAcc.AccessToken, feeds["paging"]["next"]); } catch { apiHitsCount = MaxapiHitsCount; } } fbAcc.LastUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc); } } } else { apiHitsCount = 0; } return(0); }
private static void recordExplore <T>() where T : IGUIDable { if (string.IsNullOrEmpty(dbConnectionString)) { Console.WriteLine("> ERROR: You need to specify a connection string first."); Thread.Sleep(3000); } else { Console.WriteLine("> Connecting to database..."); MongoDbConnection dbConnection = new MongoDbConnection(dbConnectionString); MongoRepository <T> repository = new MongoRepository <T>(dbConnection); Console.WriteLine($"Exploring {typeof(T).Name} objects"); long objCount = repository.Count(); Console.WriteLine($"Total count: {objCount}"); Console.Write("Dump to console [yN]?"); if (Console.ReadLine().ToLower() == "y") { foreach (T obj in repository.GetAll()) { Console.WriteLine(System.Text.Json.JsonSerializer.Serialize <T>(obj, new JsonSerializerOptions() { WriteIndented = true })); } Console.WriteLine("\n\nPress any key to continue..."); Console.ReadKey(); } Console.Write("Dump to json files? [yN]?"); if (Console.ReadLine().ToLower() == "y") { Console.WriteLine("Name of new directory where json files will be stored (if exists it will be deleted)"); Console.Write($"Directory name: [{typeof(T).Name}]: "); string dirname = Console.ReadLine(); if (string.IsNullOrEmpty(dirname)) { dirname = typeof(T).Name; } Console.WriteLine($"Creating folder {dirname}"); if (Directory.Exists(dirname)) { Directory.Delete(dirname, true); } if (!Directory.Exists(dirname)) { Directory.CreateDirectory(dirname); } Console.WriteLine("Dumping objects..."); foreach (T obj in repository.GetAll()) { using (StreamWriter fileStream = File.CreateText(Path.Combine(dirname, $"{obj.Id}.json"))) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Formatting = Formatting.Indented; serializer.Serialize(fileStream, obj, typeof(T)); } } Console.WriteLine("Done!"); Console.WriteLine("\n\nPress any key to go back to main menu..."); Console.ReadKey(); } } }
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); }
public MongoDBFileStore(MongoRepository mongoRepository, ILogger <MongoDBFileStore> logger) { _mongoRepository = mongoRepository; _logger = logger; }
public void Discussion433878() { var specialRepository = new MongoRepository <SpecialA>(); }
private static void schoolReimport() { bool wipe = false; string filename = string.Empty; if (string.IsNullOrEmpty(dbConnectionString)) { Console.WriteLine("> ERROR: You need to specify a connection string first."); Thread.Sleep(3000); } else { Console.WriteLine("> Connecting to database..."); MongoDbConnection dbConnection = new MongoDbConnection(dbConnectionString); MongoRepository <School> schoolRepository = new MongoRepository <School>(dbConnection); Console.Write("Enter filename to import (must be a JSON file): "); filename = Console.ReadLine(); if (!string.IsNullOrEmpty(filename)) { Console.WriteLine($"> Attempting to load {filename}"); // Verify that the file exists if (File.Exists(filename)) { // Attempt to load the file try { using (StreamReader importFile = new StreamReader(filename)) { // Attempt to deserialize the file List <School> importedSchools = new List <School>(); importedSchools = System.Text.Json.JsonSerializer.Deserialize <List <School> >(importFile.ReadToEnd()); Console.WriteLine($"> Loaded {importedSchools.Count} School objects from file"); Console.WriteLine("Dump JSON to console window [yN]?: "); if (Console.ReadLine().ToLower() == "y") { Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(importedSchools, new JsonSerializerOptions() { WriteIndented = true })); } Console.Write("\nWipe existing school data [Yn]: "); wipe = !(Console.ReadLine().ToLower() == "n"); Console.WriteLine("Perform the import [yN]?: "); if (Console.ReadLine().ToLower() == "y") { Console.WriteLine("> Performing import..."); // Perform the import if (wipe) { Console.WriteLine("> Wiping existing data..."); schoolRepository.DeleteAll(); } Console.WriteLine("> Importing..."); schoolRepository.Insert(importedSchools); } } } catch (Exception ex) { Console.WriteLine("> ERROR: " + ex.Message); Console.WriteLine("(Press any key to continue...)"); Console.ReadKey(); } } else { Console.WriteLine("> ERROR: File not found"); Thread.Sleep(3000); } } else { Console.WriteLine("> ERROR: Filename empty"); Thread.Sleep(3000); } } }
public ValuesController(MongoRepository <User> userMongoRepository) { _userMongoRepository = userMongoRepository; }
public static void CreateReports(string ProfileId, string AccessToken, bool is90daysupdated, long userId) { int day = 1; if (!is90daysupdated) { day = 90; } double since = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow.AddDays(-day)); double until = SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow); JObject pageobj = new JObject(); JArray likesobj = new JArray(); JArray unlikesobj = new JArray(); JArray impressionobj = new JArray(); JArray uniqueobj = new JArray(); JArray facebookstory_typeUrlobj90 = new JArray(); JArray facebookorganicobj90 = new JArray(); JArray facebookviralobj90 = new JArray(); JArray facebookpaidobj90 = new JArray(); JArray facebookimpressionbyageobj = new JArray(); JArray facebookstoriesobj = new JArray(); JArray facebooksharing_typeUrlobj = new JArray(); JArray facebookagegenderUrlobj = new JArray(); JObject jounlikes = new JObject(); JObject joimpressionobj = new JObject(); JObject jouniqueobj = new JObject(); JObject jofacebookstory_typeUrlobj = new JObject(); JObject jofacebookorganicobj = new JObject(); JObject jofacebookviralobj = new JObject(); JObject jofacebookpaidobj = new JObject(); JObject jofacebookimpressionbyageobj = new JObject(); JObject jofacebookstoriesobj = new JObject(); JObject jofacebooksharing_typeUrlobj = new JObject(); JObject jofacebookagegenderUrlobj = new JObject(); MongoRepository mongorepofb = new MongoRepository("FacebookPasswordChangeUserDetail"); string errormsg = null; string ispasschange = null; string msg = null; #region likes try { string facebookpageUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "?fields=fan_count,name,talking_about_count&access_token=" + AccessToken; string outputfacepageUrl = getFacebookResponse(facebookpageUrl); pageobj = JObject.Parse(outputfacepageUrl); } catch (Exception ex) { } try { string facebooknewfanUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_fan_adds?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputface = getFacebookResponse(facebooknewfanUrl); ispasschange = outputface; likesobj = JArray.Parse(JArray.Parse(JObject.Parse(outputface)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { errormsg = ispasschange; msg = getBetween(errormsg, "e\":\"", ":"); } #endregion #region unlikes try { string facebookunlikjeUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_fan_removes?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceunlike = getFacebookResponse(facebookunlikjeUrl); ispasschange = outputfaceunlike; unlikesobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceunlike)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { errormsg = ispasschange; } #endregion #region impression try { string facebookimpressionUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceunimpression = getFacebookResponse(facebookimpressionUrl); impressionobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceunimpression)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region impression user try { string facebookuniqueUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_unique?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceununoque = getFacebookResponse(facebookuniqueUrl); uniqueobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceununoque)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region impression breakdown try { string facebookstory_typeUrl90 = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_by_story_type?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceunstory_type90 = getFacebookResponse(facebookstory_typeUrl90); facebookstory_typeUrlobj90 = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceunstory_type90)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region impression breakdown organic try { string facebookorganic90 = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_organic?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceorganic90 = getFacebookResponse(facebookorganic90); facebookorganicobj90 = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceorganic90)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region imression breakdowm viral try { string facebookviral90 = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_viral?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceviral90 = getFacebookResponse(facebookviral90); facebookviralobj90 = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceviral90)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region impression breakdown paid try { string facebookpaid90 = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_paid?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfacepaid90 = getFacebookResponse(facebookpaid90); facebookpaidobj90 = JArray.Parse(JArray.Parse(JObject.Parse(outputfacepaid90)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region page imression by age and gender try { string facebookimpressionbyage = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_impressions_by_age_gender_unique?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceimpressionbyage = getFacebookResponse(facebookimpressionbyage); facebookimpressionbyageobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceimpressionbyage)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region story sharing try { string facebookstories = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_stories?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfacestories = getFacebookResponse(facebookstories); facebookstoriesobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfacestories)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region sroty sharing by share type try { string facebooksharing_typeUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_stories_by_story_type?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceunsharing_type = getFacebookResponse(facebooksharing_typeUrl); facebooksharing_typeUrlobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceunsharing_type)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } #endregion #region story sharing by age and gender try { string facebooksharingagegenderUrl = "https://graph.facebook.com/v2.7/" + ProfileId + "/insights/page_storytellers_by_age_gender?pretty=0&since=" + since.ToString() + "&suppress_http_code=1&until=" + until.ToString() + "&access_token=" + AccessToken; string outputfaceunagegender = getFacebookResponse(facebooksharingagegenderUrl); facebookagegenderUrlobj = JArray.Parse(JArray.Parse(JObject.Parse(outputfaceunagegender)["data"].ToString())[0]["values"].ToString()); } catch (Exception ex) { } try { if (msg == "Error validating access token") { DatabaseRepository dbr = new DatabaseRepository(); Domain.Socioboard.Models.Facebookaccounts lstFbAcc = dbr.Single <Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == ProfileId); Domain.Socioboard.Models.User lstUser = dbr.Single <Domain.Socioboard.Models.User>(t => t.Id == lstFbAcc.UserId); Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail fbdetailpass = new Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail(); fbdetailpass.Id = ObjectId.GenerateNewId(); fbdetailpass.strId = ObjectId.GenerateNewId().ToString(); fbdetailpass.userId = userId; fbdetailpass.profileId = ProfileId; fbdetailpass.message = msg; fbdetailpass.FbEmail = lstUser.EmailId; fbdetailpass.dateValue = DateTime.Today.ToString(); fbdetailpass.status = false; try { MongoRepository mongorepo = new MongoRepository("FacebookPasswordChangeUserDetail"); var ret = mongorepo.Find <Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail>(t => t.profileId == fbdetailpass.profileId); var task = Task.Run(async() => { return(await ret); }); if (task.Result != null) { if (task.Result.Count() < 1) { mongorepo.Add <Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail>(fbdetailpass); } } } catch (Exception ex) { } } } catch (Exception ex) { } #endregion foreach (JObject obj in likesobj) { Domain.Socioboard.Models.Mongo.FacaebookPageDailyReports facebookReportViewModal = new Domain.Socioboard.Models.Mongo.FacaebookPageDailyReports(); string key = obj["end_time"].ToString(); try { jounlikes = unlikesobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { joimpressionobj = impressionobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jouniqueobj = uniqueobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookstory_typeUrlobj = facebookstory_typeUrlobj90.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookorganicobj = facebookorganicobj90.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookviralobj = facebookviralobj90.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookpaidobj = facebookpaidobj90.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookimpressionbyageobj = facebookimpressionbyageobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookstoriesobj = facebookstoriesobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebooksharing_typeUrlobj = facebooksharing_typeUrlobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } try { jofacebookagegenderUrlobj = facebookagegenderUrlobj.Children <JObject>().FirstOrDefault(o => o["end_time"].ToString() == key); } catch (Exception ex) { } DateTime dt = DateTime.Parse(key).Date; facebookReportViewModal.pageId = ProfileId; facebookReportViewModal.date = SBHelper.ConvertToUnixTimestamp(dt); try { facebookReportViewModal.totalLikes = pageobj["fan_count"].ToString(); } catch { facebookReportViewModal.totalLikes = "0"; } try { facebookReportViewModal.name = pageobj["name"].ToString(); } catch { facebookReportViewModal.name = ""; } try { facebookReportViewModal.talkingAbout = pageobj["talking_about_count"].ToString(); } catch { facebookReportViewModal.talkingAbout = "0"; } try { facebookReportViewModal.perDayLikes = obj["value"].ToString(); } catch { facebookReportViewModal.perDayLikes = "0"; } try { facebookReportViewModal.likes = Int32.Parse(obj["value"].ToString()); } catch { facebookReportViewModal.likes = 0; } try { facebookReportViewModal.unlikes = Int32.Parse(jounlikes["value"].ToString()); } catch { facebookReportViewModal.unlikes = 0; } try { facebookReportViewModal.perDayUnlikes = jounlikes["value"].ToString(); } catch { facebookReportViewModal.perDayUnlikes = "0"; } try { facebookReportViewModal.impression = Int32.Parse(joimpressionobj["value"].ToString()); } catch { facebookReportViewModal.impression = 0; } try { facebookReportViewModal.perDayImpression = joimpressionobj["value"].ToString(); } catch { facebookReportViewModal.perDayImpression = "0"; } try { facebookReportViewModal.uniqueUser = Int32.Parse(jouniqueobj["value"].ToString()); } catch { facebookReportViewModal.uniqueUser = 0; } try { facebookReportViewModal.uniqueUser = Int32.Parse(jouniqueobj["value"].ToString()); } catch { facebookReportViewModal.uniqueUser = 0; } try { facebookReportViewModal.impressionFans = Int32.Parse(jofacebookstory_typeUrlobj["value"]["fan"].ToString()); } catch { facebookReportViewModal.impressionFans = 0; } try { facebookReportViewModal.impressionPagePost = Int32.Parse(jofacebookstory_typeUrlobj["value"]["page post"].ToString()); } catch { facebookReportViewModal.impressionPagePost = 0; } try { facebookReportViewModal.impressionuserPost = Int32.Parse(jofacebookstory_typeUrlobj["value"]["user post"].ToString()); } catch { facebookReportViewModal.impressionuserPost = 0; } try { facebookReportViewModal.impressionCoupn = Int32.Parse(jofacebookstory_typeUrlobj["value"]["coupon"].ToString()); } catch { facebookReportViewModal.impressionCoupn = 0; } try { facebookReportViewModal.impressionOther = Int32.Parse(jofacebookstory_typeUrlobj["value"]["other"].ToString()); } catch { facebookReportViewModal.impressionOther = 0; } try { facebookReportViewModal.impressionMention = Int32.Parse(jofacebookstory_typeUrlobj["value"]["mention"].ToString()); } catch { facebookReportViewModal.impressionMention = 0; } try { facebookReportViewModal.impressionCheckin = Int32.Parse(jofacebookstory_typeUrlobj["value"]["checkin"].ToString()); } catch { facebookReportViewModal.impressionCheckin = 0; } try { facebookReportViewModal.impressionQuestion = Int32.Parse(jofacebookstory_typeUrlobj["value"]["question"].ToString()); } catch { facebookReportViewModal.impressionQuestion = 0; } try { facebookReportViewModal.impressionEvent = Int32.Parse(jofacebookstory_typeUrlobj["value"]["event"].ToString()); } catch { facebookReportViewModal.impressionEvent = 0; } try { facebookReportViewModal.viral = Int32.Parse(jofacebookviralobj["value"].ToString()); } catch { facebookReportViewModal.viral = 0; } try { facebookReportViewModal.organic = Int32.Parse(jofacebookorganicobj["value"].ToString()); } catch { facebookReportViewModal.organic = 0; } try { facebookReportViewModal.paid = Int32.Parse(jofacebookpaidobj["value"].ToString()); } catch { facebookReportViewModal.paid = 0; } try { facebookReportViewModal.f_13_17 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.13-17"].ToString()); } catch { facebookReportViewModal.f_13_17 = 0; } try { facebookReportViewModal.f_18_24 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.18-24"].ToString()); } catch { facebookReportViewModal.f_18_24 = 0; } try { facebookReportViewModal.f_25_34 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.25-34"].ToString()); } catch { facebookReportViewModal.f_25_34 = 0; } try { facebookReportViewModal.f_35_44 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.35-44"].ToString()); } catch { facebookReportViewModal.f_35_44 = 0; } try { facebookReportViewModal.f_45_54 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.45-54"].ToString()); } catch { facebookReportViewModal.f_45_54 = 0; } try { facebookReportViewModal.f_55_64 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.55-64"].ToString()); } catch { facebookReportViewModal.f_55_64 = 0; } try { facebookReportViewModal.f_65 = Int32.Parse(jofacebookimpressionbyageobj["value"]["F.65+"].ToString()); } catch { facebookReportViewModal.f_65 = 0; } try { facebookReportViewModal.m_13_17 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.13-17"].ToString()); } catch { facebookReportViewModal.m_13_17 = 0; } try { facebookReportViewModal.m_18_24 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.18-24"].ToString()); } catch { facebookReportViewModal.m_18_24 = 0; } try { facebookReportViewModal.m_25_34 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.25-34"].ToString()); } catch { facebookReportViewModal.m_25_34 = 0; } try { facebookReportViewModal.m_35_44 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.35-44"].ToString()); } catch { facebookReportViewModal.m_35_44 = 0; } try { facebookReportViewModal.m_45_54 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.45-54"].ToString()); } catch { facebookReportViewModal.m_45_54 = 0; } try { facebookReportViewModal.m_55_64 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.55-64"].ToString()); } catch { facebookReportViewModal.m_55_64 = 0; } try { facebookReportViewModal.m_65 = Int32.Parse(jofacebookimpressionbyageobj["value"]["M.65+"].ToString()); } catch { facebookReportViewModal.m_65 = 0; } try { facebookReportViewModal.storyShare = Int32.Parse(jofacebookstoriesobj["value"].ToString()); } catch { facebookReportViewModal.storyShare = 0; } try { facebookReportViewModal.perDayStoryShare = jofacebookstoriesobj["value"].ToString(); } catch { facebookReportViewModal.perDayStoryShare = "0"; } try { facebookReportViewModal.story_Fans = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["fan"].ToString()); } catch { facebookReportViewModal.story_Fans = 0; } try { facebookReportViewModal.story_PagePost = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["page post"].ToString()); } catch { facebookReportViewModal.story_PagePost = 0; } try { facebookReportViewModal.story_UserPost = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["user post"].ToString()); } catch { facebookReportViewModal.story_UserPost = 0; } try { facebookReportViewModal.story_Question = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["question"].ToString()); } catch { facebookReportViewModal.story_Question = 0; } try { facebookReportViewModal.story_Mention = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["mention"].ToString()); } catch { facebookReportViewModal.story_Mention = 0; } try { facebookReportViewModal.story_Other = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["other"].ToString()); } catch { facebookReportViewModal.story_Other = 0; } try { facebookReportViewModal.story_Coupon = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["coupon"].ToString()); } catch { facebookReportViewModal.story_Coupon = 0; } try { facebookReportViewModal.story_Event = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["event"].ToString()); } catch { facebookReportViewModal.story_Event = 0; } try { facebookReportViewModal.story_Checkin = Int32.Parse(jofacebooksharing_typeUrlobj["value"]["checkin"].ToString()); } catch { facebookReportViewModal.story_Checkin = 0; } try { facebookReportViewModal.sharing_F_13_17 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.13-17"].ToString()); } catch { facebookReportViewModal.sharing_F_13_17 = 0; } try { facebookReportViewModal.sharing_F_18_24 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.18-24"].ToString()); } catch { facebookReportViewModal.sharing_F_18_24 = 0; } try { facebookReportViewModal.sharing_F_25_34 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.25-34"].ToString()); } catch { facebookReportViewModal.sharing_F_25_34 = 0; } try { facebookReportViewModal.sharing_F_35_44 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.35-44"].ToString()); } catch { facebookReportViewModal.sharing_F_35_44 = 0; } try { facebookReportViewModal.sharing_F_45_54 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.45-54"].ToString()); } catch { facebookReportViewModal.sharing_F_45_54 = 0; } try { facebookReportViewModal.sharing_F_55_64 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.55-64"].ToString()); } catch { facebookReportViewModal.sharing_F_55_64 = 0; } try { facebookReportViewModal.sharing_F_65 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.65+"].ToString()); } catch { facebookReportViewModal.sharing_F_65 = 0; } try { facebookReportViewModal.sharing_M_13_17 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.13-17"].ToString()); } catch { facebookReportViewModal.sharing_M_13_17 = 0; } try { facebookReportViewModal.sharing_M_18_24 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.18-24"].ToString()); } catch { facebookReportViewModal.sharing_M_18_24 = 0; } try { facebookReportViewModal.sharing_M_25_34 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.25-34"].ToString()); } catch { facebookReportViewModal.sharing_M_25_34 = 0; } try { facebookReportViewModal.sharing_M_35_44 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.35-44"].ToString()); } catch { facebookReportViewModal.sharing_M_35_44 = 0; } try { facebookReportViewModal.sharing_M_45_54 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.45-54"].ToString()); } catch { facebookReportViewModal.sharing_M_45_54 = 0; } try { facebookReportViewModal.sharing_M_55_64 = Int32.Parse(jofacebookagegenderUrlobj["value"]["M.55-64"].ToString()); } catch { facebookReportViewModal.sharing_M_55_64 = 0; } try { facebookReportViewModal.sharing_M_65 = Int32.Parse(jofacebookagegenderUrlobj["value"]["F.65+"].ToString()); } catch { facebookReportViewModal.sharing_M_65 = 0; } facebookReportViewModal.id = ObjectId.GenerateNewId(); try { MongoRepository mongorepo = new MongoRepository("FacaebookPageDailyReports"); var ret = mongorepo.Find <Domain.Socioboard.Models.Mongo.FacaebookPageDailyReports>(t => t.date == facebookReportViewModal.date && t.pageId == facebookReportViewModal.pageId); var task = Task.Run(async() => { return(await ret); }); if (task.Result != null) { if (task.Result.Count() < 1) { mongorepo.Add <Domain.Socioboard.Models.Mongo.FacaebookPageDailyReports>(facebookReportViewModal); } } } catch (Exception ex) { } } }
public void UpdateYAnalyticsReports() { while (true) { try { Helper.DatabaseRepository dbr = new Helper.DatabaseRepository(); string apiKey = AppSettings.GoogleApiKey; oAuthTokenYoutube ObjoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.GoogleConsumerKey, AppSettings.GoogleConsumerSecret, AppSettings.GoogleRedirectUri); oAuthToken objToken = new oAuthToken(AppSettings.GoogleConsumerKey, AppSettings.GoogleConsumerSecret, AppSettings.GoogleRedirectUri); YAnalytics ObjYAnalytics = new YAnalytics(AppSettings.GoogleConsumerKey, AppSettings.GoogleConsumerSecret, AppSettings.GoogleRedirectUri); List <Domain.Socioboard.Models.YoutubeChannel> lstYtChannels = dbr.Find <Domain.Socioboard.Models.YoutubeChannel>(t => t.IsActive).ToList(); long count = 0; Console.WriteLine("---------------- Youtube Analytics Dataservices Started ----------------"); foreach (var item in lstYtChannels) { #region count for mongo data MongoRepository mongoreposs = new MongoRepository("YoutubeReportsData"); var result = mongoreposs.Find <Domain.Socioboard.Models.Mongo.YoutubeReports>(t => t.channelId.Equals(item.YtubeChannelId)); var task = Task.Run(async() => { return(await result); }); IList <Domain.Socioboard.Models.Mongo.YoutubeReports> lstYanalytics = task.Result; int count90AnalyticsUpdated = lstYanalytics.Count(); #endregion try { if (!item.Days90Update || count90AnalyticsUpdated < 90) { if (item.IsActive) { try { ////////code of reports here/////////////////////// DateTime to_Date = DateTime.UtcNow; string to_dd = "0" + Convert.ToString(to_Date.Day); to_dd = to_dd.Substring(to_dd.Length - 2); string to_mm = "0" + Convert.ToString(to_Date.Month); to_mm = to_mm.Substring(to_mm.Length - 2); string to_yyyy = Convert.ToString(to_Date.Year); DateTime from_Date = DateTime.UtcNow.AddDays(-90); string from_dd = "0" + Convert.ToString(from_Date.Day); from_dd = from_dd.Substring(from_dd.Length - 2); string from_mm = "0" + Convert.ToString(from_Date.Month); from_mm = from_mm.Substring(from_mm.Length - 2); string from_yyyy = Convert.ToString(from_Date.Year); string YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd; string YaTo_Date = to_yyyy + "-" + to_mm + "-" + to_dd; MongoRepository mongorepo = new MongoRepository("YoutubeReportsData"); string AnalyticData = ObjYAnalytics.Get_YAnalytics_ChannelId(item.YtubeChannelId, item.RefreshToken, YaFrom_Date, YaTo_Date); JObject JAnalyticData = JObject.Parse(AnalyticData); JArray dataArray = (JArray)JAnalyticData["rows"]; List <string> datesJdata = new List <string>(); if (dataArray != null) { foreach (var rows in dataArray) { datesJdata.Add(rows[0].ToString()); } foreach (var items in dataArray) { YoutubeReports _YReports = new YoutubeReports(); string date = items[0].ToString(); string channelIdd = items[1].ToString(); int SubscribersGained = Convert.ToInt32(items[2]); int views = Convert.ToInt32(items[3]); int likes = Convert.ToInt32(items[4]); int comments = Convert.ToInt32(items[5]); int shares = Convert.ToInt32(items[6]); int dislikes = Convert.ToInt32(items[7]); int subscribersLost = Convert.ToInt32(items[8]); double averageViewDuration = Convert.ToInt64(items[9]); double estimatedMinutesWatched = Convert.ToInt64(items[10]); double annotationClickThroughRate = Convert.ToInt64(items[11]); double annotationCloseRate = Convert.ToInt64(items[12]); string uniqueIdentifier = item.YtubeChannelId + "_" + date; double datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(date))); _YReports.Id = ObjectId.GenerateNewId(); _YReports.date = date; _YReports.channelId = channelIdd; _YReports.SubscribersGained = SubscribersGained; _YReports.views = views; _YReports.likes = likes; _YReports.comments = comments; _YReports.dislikes = dislikes; _YReports.subscribersLost = subscribersLost; _YReports.averageViewDuration = averageViewDuration; _YReports.estimatedMinutesWatched = estimatedMinutesWatched; _YReports.annotationClickThroughRate = annotationClickThroughRate; _YReports.annotationCloseRate = annotationCloseRate; _YReports.uniqueIdentifier = uniqueIdentifier; _YReports.datetime_unix = datetime_unix; mongorepo.Add(_YReports); } } else { datesJdata.Add("Null"); } for (int i = 1; i <= 90; i++) { YoutubeReports _YReports = new YoutubeReports(); DateTime dateTimeTemp = DateTime.UtcNow.AddDays(-i); string now_dd = "0" + Convert.ToString(dateTimeTemp.Day); now_dd = now_dd.Substring(now_dd.Length - 2); string now_mm = "0" + Convert.ToString(dateTimeTemp.Month); now_mm = now_mm.Substring(now_mm.Length - 2); string now_yyyy = Convert.ToString(dateTimeTemp.Year); string Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd; if (!(datesJdata.Contains(Ynow_Date))) { _YReports.Id = ObjectId.GenerateNewId(); _YReports.date = Ynow_Date; _YReports.channelId = item.YtubeChannelId; _YReports.SubscribersGained = 0; _YReports.views = 0; _YReports.likes = 0; _YReports.comments = 0; _YReports.dislikes = 0; _YReports.subscribersLost = 0; _YReports.averageViewDuration = 0; _YReports.estimatedMinutesWatched = 0; _YReports.annotationClickThroughRate = 0; _YReports.annotationCloseRate = 0; _YReports.uniqueIdentifier = item.YtubeChannelId + "_" + Ynow_Date; _YReports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date))); mongorepo.Add(_YReports); } } item.Days90Update = true; item.LastReport_Update = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item); } catch (Exception) { Thread.Sleep(600000); } } } else { if (item.LastReport_Update.AddHours(24) < DateTime.UtcNow) { //dailyReport Code here// if (item.IsActive) { try { //code of reports here// DateTime to_Date = DateTime.UtcNow; string to_dd = "0" + Convert.ToString(to_Date.Day); to_dd = to_dd.Substring(to_dd.Length - 2); string to_mm = "0" + Convert.ToString(to_Date.Month); to_mm = to_mm.Substring(to_mm.Length - 2); string to_yyyy = Convert.ToString(to_Date.Year); DateTime from_Date = DateTime.UtcNow.AddDays(-4); string from_dd = "0" + Convert.ToString(from_Date.Day); from_dd = from_dd.Substring(from_dd.Length - 2); string from_mm = "0" + Convert.ToString(from_Date.Month); from_mm = from_mm.Substring(from_mm.Length - 2); string from_yyyy = Convert.ToString(from_Date.Year); string YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd; string YaTo_Date = to_yyyy + "-" + to_mm + "-" + to_dd; string AnalyticData = ObjYAnalytics.Get_YAnalytics_ChannelId(item.YtubeChannelId, item.RefreshToken, YaFrom_Date, YaTo_Date); JObject JAnalyticData = JObject.Parse(AnalyticData); JArray dataArray = (JArray)JAnalyticData["rows"]; List <string> datesJdata = new List <string>(); if (dataArray != null) { foreach (var rows in dataArray) { datesJdata.Add(rows[0].ToString()); } foreach (var items in dataArray) { YoutubeReports _YReports = new YoutubeReports(); string date = items[0].ToString(); string channelIdd = items[1].ToString(); int SubscribersGained = Convert.ToInt32(items[2]); int views = Convert.ToInt32(items[3]); int likes = Convert.ToInt32(items[4]); int comments = Convert.ToInt32(items[5]); int shares = Convert.ToInt32(items[6]); int dislikes = Convert.ToInt32(items[7]); int subscribersLost = Convert.ToInt32(items[8]); double averageViewDuration = Convert.ToInt64(items[9]); double estimatedMinutesWatched = Convert.ToInt64(items[10]); double annotationClickThroughRate = Convert.ToInt64(items[11]); double annotationCloseRate = Convert.ToInt64(items[12]); string uniqueIdentifier = item.YtubeChannelId + "_" + date; double datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(date))); _YReports.Id = ObjectId.GenerateNewId(); _YReports.date = date; _YReports.channelId = channelIdd; _YReports.SubscribersGained = SubscribersGained; _YReports.views = views; _YReports.likes = likes; _YReports.comments = comments; _YReports.dislikes = dislikes; _YReports.subscribersLost = subscribersLost; _YReports.averageViewDuration = averageViewDuration; _YReports.estimatedMinutesWatched = estimatedMinutesWatched; _YReports.annotationClickThroughRate = annotationClickThroughRate; _YReports.annotationCloseRate = annotationCloseRate; _YReports.uniqueIdentifier = uniqueIdentifier; _YReports.datetime_unix = datetime_unix; try { MongoRepository mongoRepotsRepo = new MongoRepository("YoutubeReportsData"); var ret = mongoRepotsRepo.Find <YoutubeReports>(t => t.uniqueIdentifier.Equals(_YReports.uniqueIdentifier)); var task_Reports = Task.Run(async() => { return(await ret); }); int count_Reports = task_Reports.Result.Count; if (count_Reports < 1) { try { mongoRepotsRepo.Add(_YReports); } catch { } } else { try { FilterDefinition <BsonDocument> filter = new BsonDocument("uniqueIdentifier", _YReports.uniqueIdentifier); var update = Builders <BsonDocument> .Update.Set("SubscribersGained", _YReports.SubscribersGained).Set("views", _YReports.views).Set("likes", _YReports.likes).Set("comments", _YReports.comments).Set("dislikes", _YReports.dislikes).Set("subscribersLost", _YReports.subscribersLost).Set("averageViewDuration", _YReports.averageViewDuration).Set("estimatedMinutesWatched", _YReports.estimatedMinutesWatched).Set("annotationClickThroughRate", _YReports.annotationClickThroughRate).Set("annotationCloseRate", _YReports.annotationCloseRate); mongoRepotsRepo.Update <YoutubeReports>(update, filter); } catch { } } } catch { } } } else { datesJdata.Add("Null"); } for (int i = 1; i <= 4; i++) { YoutubeReports _YReports = new YoutubeReports(); DateTime dateTimeTemp = DateTime.UtcNow.AddDays(-i); string now_dd = "0" + Convert.ToString(dateTimeTemp.Day); now_dd = now_dd.Substring(now_dd.Length - 2); string now_mm = "0" + Convert.ToString(dateTimeTemp.Month); now_mm = now_mm.Substring(now_mm.Length - 2); string now_yyyy = Convert.ToString(dateTimeTemp.Year); string Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd; if (!(datesJdata.Contains(Ynow_Date))) { _YReports.Id = ObjectId.GenerateNewId(); _YReports.date = Ynow_Date; _YReports.channelId = item.YtubeChannelId; _YReports.SubscribersGained = 0; _YReports.views = 0; _YReports.likes = 0; _YReports.comments = 0; _YReports.dislikes = 0; _YReports.subscribersLost = 0; _YReports.averageViewDuration = 0; _YReports.estimatedMinutesWatched = 0; _YReports.annotationClickThroughRate = 0; _YReports.annotationCloseRate = 0; _YReports.uniqueIdentifier = item.YtubeChannelId + "_" + Ynow_Date; _YReports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date))); MongoRepository mongoRepotsRepo = new MongoRepository("YoutubeReportsData"); mongoRepotsRepo.Add(_YReports); } } item.LastReport_Update = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item); } catch (Exception) { Thread.Sleep(600000); } } } } } catch (Exception ex) { Thread.Sleep(600000); } long oldcount = count; count++; long newcount = count; long totalcount = lstYtChannels.Count(); long percentagenew = (newcount * 100) / totalcount; long percentageold = (oldcount * 100) / totalcount; if (percentagenew != percentageold) { Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew); } } Thread.Sleep(600000); } catch (Exception ex) { Console.WriteLine("issue in web api calling" + ex.StackTrace); Thread.Sleep(600000); } } }
public AddOnNewBranchTranslation(MongoRepository <Translation> baseRepository) { _mongoRepository = baseRepository; }
public static List <Domain.Socioboard.Models.Mongo.totalfbPagePostDetails> getfbPagePostAllDetails(string[] profileId, int daysCount, Helper.Cache _redisCache, Helper.AppSettings _appSettings) { MongoRepository mongorepo = new MongoRepository("FacebookPagePost", _appSettings); //string[] profileId = lstfanpageacc.Select(t => t.FbUserId).ToArray(); List <Domain.Socioboard.Models.Mongo.totalfbPagePostDetails> inMemFacaebookPageDailyReports = _redisCache.Get <List <Domain.Socioboard.Models.Mongo.totalfbPagePostDetails> >(Domain.Socioboard.Consatants.SocioboardConsts.CacheInstagramDailyReport + profileId); if (inMemFacaebookPageDailyReports != null) { return(inMemFacaebookPageDailyReports); } else { List <Domain.Socioboard.Models.Mongo.totalfbPagePostDetails> reportdata = new List <totalfbPagePostDetails>(); DateTime dayStart = new DateTime(DateTime.UtcNow.AddDays(-90).Year, DateTime.UtcNow.AddDays(-90).Month, DateTime.UtcNow.AddDays(-90).Day, 0, 0, 0, DateTimeKind.Utc); DateTime dayEnd = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59, DateTimeKind.Utc); var ret = mongorepo.Find <Domain.Socioboard.Models.Mongo.FacebookPagePost>(t => profileId.Contains(t.PageId) && (t.CreatedTime <= Helper.DateExtension.ToUnixTimestamp(dayEnd) && t.CreatedTime >= Helper.DateExtension.ToUnixTimestamp(dayStart))); var task = Task.Run(async() => { return(await ret); }); if (task.Result != null) { IList <Domain.Socioboard.Models.Mongo.FacebookPagePost> lstfacebookpagepost = task.Result.ToList(); var facebookId = lstfacebookpagepost.GroupBy(x => x.PageId).Select(x => x.Last()).ToList(); var random = new Random(); foreach (Domain.Socioboard.Models.Mongo.FacebookPagePost lstcolordata in facebookId) { List <Domain.Socioboard.Models.Facebookaccounts> lstacc = new List <Domain.Socioboard.Models.Facebookaccounts>(); var randomColor = String.Format("#{0:X6}", random.Next(0x1000000)); Domain.Socioboard.Models.Mongo.totalfbPagePostDetails fbreportData = new totalfbPagePostDetails(); string comments = lstfacebookpagepost.ToList().Where(t => t.PageId == lstcolordata.PageId).Sum(t => Convert.ToInt64(t.Comments)).ToString(); string likes = lstfacebookpagepost.ToList().Where(t => t.PageId == lstcolordata.PageId).Sum(t => Convert.ToInt64(t.Likes)).ToString(); string posts = null; try { posts = lstfacebookpagepost.ToList().Where(t => t.PageId == lstcolordata.PageId).Count(t => Convert.ToBoolean(int.Parse(t.PostId))).ToString(); } catch (Exception ex) { } string talkings = lstfacebookpagepost.ToList().Where(t => t.PageId == lstcolordata.PageId).Sum(t => Convert.ToInt64(t.Talking)).ToString(); string shares = lstfacebookpagepost.ToList().Where(t => t.PageId == lstcolordata.PageId).Sum(t => Convert.ToInt64(t.Shares)).ToString(); // lstacc = lstfanpageacc.Where<Domain.Socioboard.Models.Facebookaccounts>(t => t.FbUserId == lstcolordata.pageId).ToList(); fbreportData.startDate = dayStart; fbreportData.endDate = dayEnd; fbreportData.profileId = lstcolordata.PageId; fbreportData.name = lstcolordata.PageName; fbreportData.commnets = comments; fbreportData.likes = likes; fbreportData.shares = shares; //fbreportData.post = posts; fbreportData.color = Convert.ToString(randomColor); reportdata.Add(fbreportData); } return(reportdata.OrderBy(t => t.startDate).ToList()); } return(new List <Domain.Socioboard.Models.Mongo.totalfbPagePostDetails>()); } }