예제 #1
0
        public List<OtherResource> GetOtherResources(string countryCode)
        {
            return LogTime(() =>
            {
                var db = new DatabaseRepository();
                var data = db.GetOtherResources(countryCode);

                return
                    data.Select(d => new OtherResource {Name = d.Name, Link = d.Link, OrderId = d.OrderId})
                        .ToList();
            }, "other resources request for country {0}", countryCode);
        }
예제 #2
0
        public List<Document> GetDocuments(string countryCode)
        {
            return LogTime(() =>
            {
                var db = new DatabaseRepository();
                var data = db.GetDocuments(countryCode).OrderBy(d => d.DocType).ThenBy(d => d.DocName);

                return
                    data.Select(d => new Document {Name = d.DocName, Link = d.DocLink, Type = d.DocTypeDescription})
                        .ToList();
            }, "documents request for country {0}", countryCode);
        }
예제 #3
0
 public IList<Model.Country> GetCountries()
 {
     var db = new DatabaseRepository();
     return
         db.GetCountries()
             .Select(
                 c =>
                     new Model.Country
                     {
                         Code = c.CountryCode,
                         Name = c.CountryAlias ?? c.CountryName,
                         IsHighIncome = c.IncomeId == 3 || c.IncomeId == 5
                     })
             .OrderBy(c => c.IsHighIncome)
             .ThenBy(c => c.Name)
             .ToList();
 }
예제 #4
0
        public List<Project> GetProjects(string countryCode)
        {
            return LogTime(() =>
            {
                var db = new DatabaseRepository();
                var result = db.GetBankProjects(countryCode).Select(d => new Project
                {
                    Amount = d.Amount,
                    ApprovalDate = d.ApprovalDate,
                    CountryCode = d.CountryCode,
                    ProjectId = d.ProjectId,
                    ProjectLink = d.ProjectLink,
                    ProjectName = d.ProjectName,
                    ProjectType = d.ProjectType,
                    ProjectStatus = d.ProjectStatus
                }).ToList();

                return result;
            }, "project request for country {0}", countryCode);
        }
예제 #5
0
        private static void ProcessPOData()
        {
            try
            {
                OdbcConnection cn;
                var            notifiedlist = new ArrayList();

                // user_1 = receiving rack location
                // user_2 = Receiver
                // user_3 = Received Date
                // user_4 = Bin Cleared Date
                // user_5 = Notified
                //                POQuery = "Select icpo.buyer, icpo.ponum, icpo.user_1, icpo.user_2, icpo.user_3, icpo.user_4, icpo.user_5, icpo.defaultjobnum, vendor.name as vendorName, icpo.user_6, icpo.defaultworkorder, icpo.attachid from icpo inner join vendor on vendor.vennum = icpo.vennum where icpo.user_3 is not null and icpo.user_5 = 0 order by icpo.ponum asc";

                OdbcConnectionStringBuilder just = new OdbcConnectionStringBuilder
                {
                    Driver = "ComputerEase"
                };
                just.Add("Dsn", "Company 0");
                just.Add("Uid", config.Uid);
                just.Add("Pwd", config.Pwd);

                cn = new OdbcConnection(just.ConnectionString);
                cn.Open();
                log.Info("[ProcessPOData] Connection to database opened successfully");
                var dbRepository = new DatabaseRepository(cn, log, config.POAttachmentBasePath);

                List <PurchaseOrder> purchaseOrdersToNotify;
                try
                {
                    purchaseOrdersToNotify = dbRepository.GetPurchaseOrdersToNotify();
                    log.Info("purchaseOrdersToNotify found " + purchaseOrdersToNotify.Count.ToString() + " items.");

                    foreach (PurchaseOrder po in purchaseOrdersToNotify)
                    {
                        var job                    = dbRepository.GetEmailBodyInformation(po.JobNumber, po.PurchaseOrderNumber, po.WorkOrderNumber);
                        var buyerEmployee          = EmployeeLookup.FindEmployeeFromAllEmployees(dbRepository.GetEmployees(), po.Buyer);
                        var projectManagerEmployee = job.ProjectManagerName.Length > 0 ? EmployeeLookup.FindEmployeeFromAllEmployees(dbRepository.GetEmployees(), job.ProjectManagerName) : new Employee();

                        log.Info("[ProcessPOData] ----------------- Found PO Number " + po.PurchaseOrderNumber + " -------------------");

                        var emailSubject = String.Format(EmailSubject, po.PurchaseOrderNumber, po.Vendor);
                        var emailBody    = FormatEmailBody(po.ReceivedOnDate, po.PurchaseOrderNumber, po.ReceivedBy, po.Bin, buyerEmployee.Name, po.Vendor, job, po.Notes);

                        ArrayList primaryRecipients = new ArrayList();
                        ArrayList bccList           = new ArrayList();
                        if ((config.Mode == live) || (config.Mode == monitor))
                        {
                            primaryRecipients.Add(buyerEmployee.EmailAddress);
                            if (projectManagerEmployee.EmailAddress.Length > 0 && buyerEmployee.EmailAddress != projectManagerEmployee.EmailAddress)
                            {
                                primaryRecipients.Add(projectManagerEmployee.EmailAddress);
                            }
                        }

                        if (((config.Mode == monitor) || (config.Mode == debug)) &&
                            (config.MonitorEmailAddresses != null && config.MonitorEmailAddresses.Count > 0))
                        {
                            foreach (string monitorEmailAddress in config.MonitorEmailAddresses)
                            {
                                bccList.Add(monitorEmailAddress);
                            }
                        }

                        if ((primaryRecipients.Count == 0) && (bccList.Count > 0))
                        {
                            primaryRecipients.Add(bccList[0]);
                        }

                        if (sendEmail(primaryRecipients, bccList, emailSubject, emailBody, po.Attachments))
                        {
                            notifiedlist.Add(po.PurchaseOrderNumber);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Info(ex.Message);
                }

                foreach (string poNum in notifiedlist)
                {
                    try
                    {
                        dbRepository.MarkPOAsNotified(poNum);
                    }
                    catch (Exception x)
                    {
                        log.Error(String.Format("[ProcessPOData] Error updating PO {0} to be Notified: {1}", poNum, x.Message));
                    }
                }

                cn.Close();
            }
            catch (Exception x)
            {
                log.Error("[ProcessPOData] Exception: " + x.Message);
                return;
            }

            return;
        }
예제 #6
0
        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 = (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
                        {
                            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.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;

                        dbr.Update <Domain.Socioboard.Models.Facebookaccounts>(fbAcc);
                    }
                }
            }
            else
            {
                apiHitsCount = 0;
            }
            return(0);
        }
예제 #7
0
        /// <summary>
        /// To Get the top three profile with given group Id
        /// </summary>
        /// <param name="groupId">group Id</param>
        /// <param name="redisCache">redis cache database</param>
        /// <param name="dbr">database object</param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static List <profilesdetail> GetTop3GroupProfiles(long groupId, Cache redisCache, DatabaseRepository dbr)
        {
            var getTop3GroupProfiles = new List <profilesdetail>();

            var groupProfiles = dbr.Find <Groupprofiles>(t => t.groupId == groupId && t.profileType != SocialProfileType.GPlus).ToList();

            if (groupProfiles.Count == 0)
            {
                return(getTop3GroupProfiles);
            }

            var userDetails = redisCache.Get <User>("User") ?? dbr.FindFirstMatch <User>(t => t.Id == groupProfiles[0].profileOwnerId);

            redisCache.Set(SocioboardConsts.CacheGroupProfiles + groupId, groupProfiles);

            var addedProfile = new List <SocialProfileType>();

            foreach (var profile in groupProfiles)
            {
                if (getTop3GroupProfiles.Count >= 3)
                {
                    break;
                }

                if (userDetails.AccountType == SBAccountType.Free && addedProfile.Contains(profile.profileType))
                {
                    continue;
                }

                addedProfile.Add(profile.profileType);

                AddedProfileDetails(redisCache, dbr, getTop3GroupProfiles, profile);
            }

            return(getTop3GroupProfiles);
        }
        public IActionResult AddProfileToGroup(string profileId, long groupId, long userId, Domain.Socioboard.Enum.SocialProfileType profileType)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
            List <Domain.Socioboard.Models.Groupprofiles> lstGroupProfiles = GroupProfilesRepository.getGroupProfiles(groupId, _redisCache, dbr);

            if (lstGroupProfiles.Where(t => t.profileId.Equals(profileId)).Count() > 0)
            {
                return(BadRequest("profile already added"));
            }
            else
            {
                Domain.Socioboard.Models.Groups grp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.id == groupId).FirstOrDefault();
                if (grp == null)
                {
                    return(BadRequest("Invalid groupId"));
                }
                else
                {
                    Domain.Socioboard.Models.Groupprofiles grpProfile = new Domain.Socioboard.Models.Groupprofiles();
                    if (profileType == Domain.Socioboard.Enum.SocialProfileType.Facebook || profileType == Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage || profileType == Domain.Socioboard.Enum.SocialProfileType.FacebookPublicPage)
                    {
                        Domain.Socioboard.Models.Facebookaccounts fbAcc = Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);
                        if (fbAcc == null)
                        {
                            return(BadRequest("Invalid profileId"));
                        }
                        if (fbAcc.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = fbAcc.FbUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = "http://graph.facebook.com/" + fbAcc.FbUserId + "/picture?type=small";
                        grpProfile.profileType    = profileType;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.Twitter)
                    {
                        Domain.Socioboard.Models.TwitterAccount twtAcc = Repositories.TwitterRepository.getTwitterAccount(profileId, _redisCache, dbr);
                        if (twtAcc == null)
                        {
                            return(BadRequest("Invalid profileId"));
                        }
                        if (twtAcc.userId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = twtAcc.twitterScreenName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = twtAcc.profileImageUrl;
                        grpProfile.profileType    = Domain.Socioboard.Enum.SocialProfileType.Twitter;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.GPlus)
                    {
                        Domain.Socioboard.Models.Googleplusaccounts gplusAccount = Repositories.GplusRepository.getGPlusAccount(profileId, _redisCache, dbr);
                        if (gplusAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (gplusAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = gplusAccount.GpUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = gplusAccount.GpProfileImage;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.Instagram)
                    {
                        Domain.Socioboard.Models.Instagramaccounts _Instagramaccounts = Repositories.InstagramRepository.getInstagramAccount(profileId, _redisCache, dbr);
                        if (_Instagramaccounts == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_Instagramaccounts.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _Instagramaccounts.InsUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _Instagramaccounts.ProfileUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.LinkedIn)
                    {
                        Domain.Socioboard.Models.LinkedInAccount _LinkedInAccount = Repositories.LinkedInAccountRepository.getLinkedInAccount(profileId, _redisCache, dbr);
                        if (_LinkedInAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_LinkedInAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _LinkedInAccount.LinkedinUserName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _LinkedInAccount.ProfileImageUrl;
                    }
                    else if (profileType == Domain.Socioboard.Enum.SocialProfileType.LinkedInComapanyPage)
                    {
                        Domain.Socioboard.Models.LinkedinCompanyPage _LinkedInAccount = Repositories.LinkedInAccountRepository.getLinkedinCompanyPage(profileId, _redisCache, dbr);
                        if (_LinkedInAccount == null)
                        {
                            return(BadRequest("Invalid ProfileId"));
                        }
                        if (_LinkedInAccount.UserId != userId)
                        {
                            return(BadRequest("profile is added by other user"));
                        }
                        grpProfile.profileName    = _LinkedInAccount.LinkedinPageName;
                        grpProfile.profileOwnerId = userId;
                        grpProfile.profilePic     = _LinkedInAccount.LogoUrl;
                    }
                    grpProfile.entryDate   = DateTime.UtcNow;
                    grpProfile.groupId     = grp.id;
                    grpProfile.profileId   = profileId;
                    grpProfile.profileType = profileType;
                    dbr.Add <Domain.Socioboard.Models.Groupprofiles>(grpProfile);
                    //codes to clear cache
                    _redisCache.Delete(Domain.Socioboard.Consatants.SocioboardConsts.CacheGroupProfiles + groupId);
                    //end codes to clear cache
                    return(Ok("Added Successfully"));
                }
            }
        }
예제 #9
0
        public IActionResult AddFacebookPages(long userId, long groupId)
        {
            string data = Request.Form["profileaccesstoken"];

            string[] accesstoken        = data.Split(',');
            int      addedPageCount     = 0;
            int      invalidaccessToken = 0;

            foreach (var item in accesstoken)
            {
                dynamic profile         = Fbpages.getFbPageData(item);
                string  subscribed_apps = Fbpages.subscribed_apps(item, Convert.ToString(profile["id"]));
                try
                {
                    string x = Convert.ToString(profile);
                    _logger.LogError(x);
                }
                catch { }
                if (Convert.ToString(profile) == "Invalid Access Token")
                {
                    invalidaccessToken++;
                    //  return Ok("Invalid Access Token");
                }
                else
                {
                    DatabaseRepository dbr = new DatabaseRepository(_logger, _env);
                    Domain.Socioboard.Models.Facebookaccounts fbacc = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr);
                    if (fbacc != null && fbacc.IsActive == true)
                    {
                        addedPageCount++;
                        //return Ok("Facebook Page added by other user.");
                    }
                    else
                    {
                        Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();
                        if (ngrp == null)
                        {
                            return(Ok("Wrong Group Id"));
                        }
                        // Adding Facebook Page
                        int res = Api.Socioboard.Repositories.FacebookRepository.AddFacebookPage(profile, dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookPage, item, _redisCache, _appSettings, _logger);
                    }
                }
            }
            if (addedPageCount == accesstoken.Length)
            {
                return(Ok("Facebook Pages added by other user."));
            }
            else if (addedPageCount == accesstoken.Length)
            {
                return(Ok("Facebook Pages having Invalid Access Token."));
            }
            else if (invalidaccessToken > 0 && addedPageCount > 0)
            {
                return(Ok("Pages added successfully and " + addedPageCount + " pages added by other user or " + invalidaccessToken + " pages having invalid access token issue"));
            }
            else if (invalidaccessToken > 0)
            {
                return(Ok("Pages added successfully" + invalidaccessToken + " pages having invalid access token issue"));
            }
            else if (addedPageCount > 0)
            {
                return(Ok("Pages added successfully and " + addedPageCount + " pages added by other user"));
            }
            return(Ok("Page added successfully"));
        }
예제 #10
0
        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"));
        }
        public IActionResult GetGroupProfiles(long groupId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupProfilesRepository.getGroupProfiles(groupId, _redisCache, dbr)));
        }
예제 #12
0
        public IActionResult DeleteGroup(long groupId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupMembersRepository.adminDelete(groupId, _redisCache, dbr)));
        }
예제 #13
0
        public IActionResult LeaveGroup(long groupId, long userId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupMembersRepository.LeaveTeam(groupId, userId, _redisCache, dbr)));
        }
예제 #14
0
        public static string ComposeMessage(Domain.Socioboard.Enum.FbProfileType profiletype, string accessToken, string fbUserId, string message, string profileId, long userId, string imagePath, string link, Domain.Socioboard.Enum.MediaType mediaType, string profileName, DatabaseRepository dbr, ILogger _logger)
        {
            string         ret = "";
            FacebookClient fb  = new FacebookClient();

            fb.AccessToken = accessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
            {
                args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);
            }
            try
            {
                if (string.IsNullOrEmpty(link))
                {
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        if (!imagePath.Contains("mp4") && !imagePath.Contains("mov") && !imagePath.Contains("mpeg") && !imagePath.Contains("wmv") && !imagePath.Contains("avi") && !imagePath.Contains("flv") && !imagePath.Contains("3gp"))
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                            var media = new FacebookMediaObject
                            {
                                FileName    = "filename",
                                ContentType = "image/" + extension
                            };
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["source"] = media;
                            ret            = fb.Post("v2.7/" + fbUserId + "/photos", args).ToString();
                        }
                        else
                        {
                            Uri    u         = new Uri(imagePath);
                            string filename  = string.Empty;
                            string extension = string.Empty;
                            filename = imagePath.Substring(imagePath.IndexOf("get?id=") + 7);
                            if (!string.IsNullOrWhiteSpace(filename))
                            {
                                extension = filename.Substring(filename.IndexOf(".") + 1);
                            }
                            var media = new FacebookMediaObject
                            {
                                FileName    = filename,
                                ContentType = "video/" + extension
                            };
                            //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                            var    webClient = new WebClient();
                            byte[] img       = webClient.DownloadData(imagePath);
                            media.SetValue(img);
                            args["title"]       = message;
                            args["description"] = message;
                            args["source"]      = media;
                            ret = fb.Post("v2.7/" + fbUserId + "/videos", args).ToString();//v2.1
                        }
                    }
                    else
                    {
                        args["message"] = message;
                        ret             = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    if (!string.IsNullOrEmpty(imagePath))
                    {
                        args["picture"] = imagePath.Replace("&amp;", "&");
                    }
                    ret = fb.Post("v2.7/" + fbUserId + "/feed", args).ToString();//v2.1
                }
                ScheduledMessage scheduledMessage = new ScheduledMessage();
                scheduledMessage.createTime = DateTime.UtcNow;
                scheduledMessage.picUrl     = "https://graph.facebook.com/" + fbUserId + "/picture?type=small";//imagePath;
                scheduledMessage.profileId  = profileId;
                if (profiletype == Domain.Socioboard.Enum.FbProfileType.FacebookProfile)
                {
                    scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.Facebook;
                }
                else
                {
                    scheduledMessage.profileType = Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage;
                }
                scheduledMessage.scheduleTime      = DateTime.UtcNow;
                scheduledMessage.shareMessage      = message;
                scheduledMessage.userId            = userId;
                scheduledMessage.status            = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                scheduledMessage.url               = imagePath;//"https://graph.facebook.com/"+ fbUserId + "/picture?type=small";
                scheduledMessage.mediaType         = mediaType;
                scheduledMessage.socialprofileName = profileName;
                dbr.Add <ScheduledMessage>(scheduledMessage);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _logger.LogError(ex.StackTrace);
            }
            return(ret);
        }
예제 #15
0
        public IActionResult GetGroupAdmin(long groupId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupMembersRepository.getGroupadmin(groupId, _redisCache, dbr)));
        }
        public IActionResult GetAdvanceSearchData(string keywords)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(Repositories.ContentStudioRepository.GetAdvanceSearchdata(keywords, _redisCache, _appSettings)));
        }
        public IActionResult ReconnectFbAccount(string accessToken, long groupId, long userId, string reconnect, string profileId)
        {
            dynamic profile = FbUser.getFbUser(accessToken);


            try
            {
                string x = Convert.ToString(profile);
                _logger.LogError(x);
            }
            catch { }
            if (Convert.ToString(profile) == "Invalid Access Token")
            {
                return(Ok("Invalid Access Token"));
            }
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            Domain.Socioboard.Models.Facebookaccounts fbacc  = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(Convert.ToString(profile["id"]), _redisCache, dbr);
            Domain.Socioboard.Models.Facebookaccounts fbaccw = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);
            //fbacc = fbacc.Where(t => t.FbUserId.Contains("127471161024815")).ToList();

            try
            {
                if (fbacc.FbUserId == profileId)
                {
                    if (fbacc != null && fbacc.IsActive == true)
                    {
                        if (fbacc.UserId == userId)
                        {
                            Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();
                            if (ngrp == null)
                            {
                                return(Ok("Wrong Group Id"));
                            }
                            int res = Api.Socioboard.Repositories.FacebookRepository.ReFacebookAccount(profile, FbUser.getFbFriends(accessToken), dbr, userId, ngrp.id, Domain.Socioboard.Enum.FbProfileType.FacebookProfile, accessToken, reconnect, _redisCache, _appSettings, _logger);
                            if (res == 1)
                            {
                                MongoRepository repofb = new MongoRepository("FacebookPasswordChangeUserDetail", _appSettings);
                                try
                                {
                                    var result = repofb.Find <Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail>(t => t.profileId == fbacc.FbUserId);
                                    var task   = Task.Run(async() =>
                                    {
                                        return(await result);
                                    });
                                    int count = task.Result.Count;

                                    IList <Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail> lstFbFeeds = task.Result;
                                    if (count > 0)
                                    {
                                        FilterDefinition <BsonDocument> filter = new BsonDocument("profileId", lstFbFeeds.FirstOrDefault().profileId);
                                        var update = Builders <BsonDocument> .Update.Set("status", true);

                                        repofb.Update <Domain.Socioboard.Models.Mongo.FacebookPasswordChangeUserDetail>(update, filter);
                                    }
                                }
                                catch (Exception ex)
                                {
                                }

                                return(Ok("Facebook account Reconnect Successfully"));
                            }
                            else
                            {
                                return(Ok("Error while Reconnecting Account"));
                            }
                        }
                    }
                }
                else
                {
                    return(Ok("Oops! login information is wrong , login the profile which has to be reconnected"));
                }
            }
            catch (Exception ex)
            {
                return(Ok("Oops! login information is wrong , login the profile which has to be reconnected"));
            }



            return(Ok());
        }
예제 #18
0
        public void GetLatestTrendsFromTwiter()
        {
            try
            {
                string homepageUrl = "https://twitter.com/";
                string trendsUrl   = "https://twitter.com/i/trends?k=0b49e0976b&pc=true&personalized=false&show_context=true&src=module&woeid=23424977";

                string homePageResponse = getHtmlfromUrl(trendsUrl);

                try
                {
                    string[] GetTrends = Regex.Split(homePageResponse, "data-trend-name=");
                    GetTrends = GetTrends.Skip(1).ToArray();
                    foreach (string item in GetTrends)
                    {
                        try
                        {
                            string temptrend = string.Empty;
                            string trend     = getBetween(item, "\"", "\\\"").Replace("&#39;", "'");
                            trend = Regex.Replace(trend, @"\\u[\d\w]{4}", String.Empty);
                            trend = trend.Replace("#", "");
                            if (!string.IsNullOrEmpty(trend) && !trend.Contains("_") && !trend.Contains("__"))
                            {
                                if (trend.ToLower().Contains(" "))
                                {
                                    temptrend = trend.Replace(" ", "_");
                                }
                                else if (trend.ToLower().Contains("/"))
                                {
                                    temptrend = trend.Replace("/", "_");
                                }
                                else if (trend.ToLower().Contains("'\'"))
                                {
                                    temptrend = trend.Replace("'\'", "_");
                                }
                                else
                                {
                                    temptrend = trend.ToLower();
                                }
                                //Trendingkeyword _Trendingkeyword = new Trendingkeyword();
                                //_Trendingkeyword.Id = ObjectId.GenerateNewId();
                                //_Trendingkeyword.strId = ObjectId.GenerateNewId().ToString();
                                //_Trendingkeyword.keyword = trend;
                                //_Trendingkeyword.TrendingType = Domain.Socioboard.Enum.TrendingType.twitter;
                                //_Trendingkeyword.trendingdate= SBHelper.ConvertToUnixTimestamp(DateTime.UtcNow);
                                //MongoRepository mongorepo = new MongoRepository("Trendingkeyword");
                                //var ret=mongorepo.Find<Trendingkeyword>(t => t.keyword == trend && t.TrendingType==Domain.Socioboard.Enum.TrendingType.twitter);
                                //var task = Task.Run(async () =>
                                //{
                                //    return await ret;
                                //});
                                //int count = task.Result.Count;
                                //if(count<1)
                                //{
                                //    mongorepo.Add<Trendingkeyword>(_Trendingkeyword);
                                //    AddTwittertrendingHashTagFeeds(trend, _Trendingkeyword.strId, "");
                                //}
                                DatabaseRepository dbr = new DatabaseRepository();
                                List <Domain.Socioboard.Models.MongoBoards> boards = new List <Domain.Socioboard.Models.MongoBoards>();
                                try
                                {
                                    boards = dbr.Find <Domain.Socioboard.Models.MongoBoards>(t => t.boardName.Equals(trend.ToLower()) && t.isActive == Domain.Socioboard.Enum.boardStatus.active).ToList();
                                    string Bid = string.Empty;
                                    if (boards == null || boards.Count() == 0)
                                    {
                                        //Bid = boards.First().boardId;
                                        Domain.Socioboard.Models.MongoBoards board = new Domain.Socioboard.Models.MongoBoards();
                                        board.TempboardName    = temptrend.ToLower();
                                        board.isActive         = Domain.Socioboard.Enum.boardStatus.active;
                                        board.boardName        = trend.ToLower();
                                        board.trendingtype     = Domain.Socioboard.Enum.TrendingType.twitter;
                                        board.createDate       = DateTime.UtcNow;
                                        board.boardId          = Guid.NewGuid().ToString();
                                        board.twitterHashTag   = AddTwitterHashTag(trend, board.boardId);
                                        board.instagramHashTag = AddInstagramHashTag(trend, board.boardId);
                                        board.gplusHashTag     = AddGplusHashTag(trend, board.boardId);
                                        dbr.Add <Domain.Socioboard.Models.MongoBoards>(board);
                                        string boardcreation = getHtmlfromUrl("https://api.socioboard.com/api/BoardMe/AddTOSiteMap?boardName=" + board.boardName);
                                        if (boardcreation.Contains("true"))
                                        {
                                            Console.WriteLine("created new sitemap for twitter trending keyword" + boardcreation);
                                        }

                                        Console.WriteLine("created new bord for twitter trending keyword" + board.boardName);
                                    }
                                    else
                                    {
                                        Bid = boards.First().boardId;
                                        Domain.Socioboard.Models.MongoBoards board = dbr.Single <Domain.Socioboard.Models.MongoBoards>(t => t.boardId == Bid);
                                        // board.TempboardName = temptrend;
                                        board.isActive   = Domain.Socioboard.Enum.boardStatus.active;
                                        board.createDate = DateTime.UtcNow;
                                        //board.boardId = board.boardId;
                                        //board.facebookHashTag = AddFacebookHashTag(trds[0], trds[1], board.boardId, ref HttpHelper, ref facebookUser);
                                        //board.twitterHashTag = AddTwitterHashTag(trend, board.boardId);
                                        //board.instagramHashTag = AddInstagramHashTag(trend, board.boardId);
                                        //board.gplusHashTag = AddGplusHashTag(trend, board.boardId);
                                        dbr.Update <Domain.Socioboard.Models.MongoBoards>(board);
                                        string boardcreation = getHtmlfromUrl("https://api.socioboard.com/api/BoardMe/AddTOSiteMap?boardName=" + board.boardName);
                                        if (boardcreation.Contains("true"))
                                        {
                                            Console.WriteLine("created new sitemap for twitter trending keyword" + boardcreation);
                                        }

                                        Console.WriteLine("created new bord for twitter trending keyword" + board.boardName);
                                    }
                                }

                                catch (Exception e)
                                {
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
예제 #19
0
 public IActionResult PluginScheduleMessage(string profile, string twitterText, string tweetId, string tweetUrl, string facebookText, string url, string imgUrl, long userId, string scheduleTime, string localscheduleTime)
 {
     string[] profiles = profile.Split(',');
     foreach (var item in profiles)
     {
         string[] ids = item.Split('~');
         if (ids[1] == "facebook")
         {
             try
             {
                 string updatedtext = "";
                 string postmessage = "";
                 if (!string.IsNullOrEmpty(facebookText))
                 {
                     string[] updatedmessgae = Regex.Split(facebookText, "<br>");
                     foreach (var items in updatedmessgae)
                     {
                         if (!string.IsNullOrEmpty(items))
                         {
                             if (items.Contains("https://") || items.Contains("http://"))
                             {
                                 if (string.IsNullOrEmpty(url))
                                 {
                                     url = items;
                                     if (items.Contains("https://"))
                                     {
                                         string link = getBetween(url + "###", "https", "###");
                                         link = "https" + link;
                                         url  = link;
                                     }
                                     if (items.Contains("http://"))
                                     {
                                         string link = getBetween(url + "###", "http", "###");
                                         link = "http" + link;
                                         url  = link;
                                     }
                                 }
                             }
                             if (items.Contains("hhh") || items.Contains("nnn"))
                             {
                                 if (items.Contains("hhh"))
                                 {
                                     postmessage = postmessage + "\n\r" + items.Replace("hhh", "#");
                                 }
                                 else
                                 {
                                     postmessage = postmessage + "\n\r" + items;
                                 }
                             }
                             else
                             {
                                 postmessage = postmessage + "\n\r" + items;
                             }
                         }
                     }
                 }
                 updatedtext = postmessage;
                 DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
                 Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(ids[0], _redisCache, dbr);
                 Helper.ScheduleMessageHelper.ScheduleMessage(ids[0], objFacebookAccount.FbUserName, updatedtext.ToString(), Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, userId, url, imgUrl, "https://graph.facebook.com/" + ids[0] + "/picture?type=small", scheduleTime, localscheduleTime, _appSettings, _redisCache, dbr, _logger);
             }
             catch (Exception ex)
             {
             }
         }
         else
         {
             try
             {
                 DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
                 if (!string.IsNullOrEmpty(twitterText) || !string.IsNullOrEmpty(imgUrl))
                 {
                     twitterText = twitterText + " " + tweetUrl;
                     Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Api.Socioboard.Repositories.TwitterRepository.getTwitterAccount(ids[0], _redisCache, dbr);
                     Helper.ScheduleMessageHelper.ScheduleMessage(ids[0], objTwitterAccount.twitterScreenName, twitterText, Domain.Socioboard.Enum.SocialProfileType.Twitter, userId, "", imgUrl, objTwitterAccount.profileImageUrl, scheduleTime, localscheduleTime, _appSettings, _redisCache, dbr, _logger);
                 }
                 else
                 {
                     string data = TwitterRepository.TwitterRetweet_post(ids[0], tweetId, userId, 0, dbr, _logger, _redisCache, _appSettings);
                 }
             }
             catch (Exception ex)
             {
             }
         }
     }
     return(Ok());
 }
예제 #20
0
        public IActionResult RetainGrpMber(long userId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupMembersRepository.RetainGrpMber(userId, _redisCache, dbr)));
        }
예제 #21
0
        public async Task <IActionResult> ComposeMessage(string message, string profileId, long userId, string imagePath, string link, IFormFile files)
        {
            var    filename    = "";
            var    apiimgPath  = "";
            var    uploads     = string.Empty;
            string postmessage = "";

            if (files != null)
            {
                if (files.Length > 0)
                {
                    var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
                    // await file.s(Path.Combine(uploads, fileName));
                    filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                               .Parse(files.ContentDisposition)
                               .FileName
                               .Trim('"');
                    var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];
                    //apiimgPath = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}";

                    filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}";

                    uploads = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}";
                    // size += file.Length;
                    try
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            files.CopyTo(fs);
                            fs.Flush();
                        }
                        filename = uploads;
                    }
                    catch (System.Exception ex)
                    {
                        if (!string.IsNullOrEmpty(imagePath))
                        {
                            uploads = imagePath;
                        }
                    }
                }
            }
            else if (!string.IsNullOrEmpty(imagePath))
            {
                uploads = imagePath;
            }

            //string[] updatedmessgae = Regex.Split(message, "<br>");

            //message = postmessage;
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            string[] lstProfileIds = null;
            if (profileId != null)
            {
                lstProfileIds = profileId.Split(',');
                profileId     = lstProfileIds[0];
            }
            else
            {
                return(Ok("profileId required"));
            }

            foreach (var item in lstProfileIds)
            {
                if (item.StartsWith("fb"))
                {
                    try
                    {
                        new Thread(delegate()
                        {
                            string prId = item.Substring(3, item.Length - 3);
                            Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr);
                            string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, message, prId, userId, uploads, link, dbr, _logger);
                        }).Start();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                if (item.StartsWith("tw"))
                {
                    try
                    {
                        new Thread(delegate()
                        {
                            string prId = item.Substring(3, item.Length - 3);
                            string ret  = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, message, prId, userId, uploads, true, dbr, _logger);
                        }).Start();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                if (item.StartsWith("lin"))
                {
                    try
                    {
                        new Thread(delegate()
                        {
                            string prId = item.Substring(4, item.Length - 4);
                            string ret  = Helper.LinkedInHelper.PostLinkedInMessage(uploads, userId, message, prId, filename, _redisCache, _appSettings, dbr);
                        }).Start();
                    }
                    catch (Exception ex)
                    {
                    }
                }
                if (item.StartsWith("Cmpylinpage"))
                {
                    try
                    {
                        new Thread(delegate()
                        {
                            string prId = item.Substring(12, item.Length - 12);
                            string ret  = Helper.LinkedInHelper.PostLinkedInCompanyPagePost(uploads, userId, message, prId, _redisCache, dbr, _appSettings);
                        }).Start();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(Ok("Posted"));
        }
예제 #22
0
        public IActionResult InviteGroupMembers(long groupId, string members)
        {
            List <Groupmembers> lstGrpMembers = new List <Groupmembers>();

            if (string.IsNullOrEmpty(members))
            {
                return(BadRequest("members should not be null."));
            }
            else
            {
                string[] lstmem = members.Split(';');
                foreach (var item in lstmem)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        Groupmembers grpMember = new Groupmembers();
                        string[]     memData   = item.Split(':');
                        grpMember.email     = memData[2];
                        grpMember.firstName = memData[0];
                        grpMember.lastName  = memData[1];
                        lstGrpMembers.Add(grpMember);
                    }
                }
            }


            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            Domain.Socioboard.Models.Groups grp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.id == groupId).FirstOrDefault();
            if (grp == null)
            {
                return(BadRequest("wrong group Id"));
            }
            else if (grp.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName))
            {
                return(BadRequest("you can't invite members to default group."));
            }
            foreach (var member in lstGrpMembers)
            {
                User inMemUser = _redisCache.Get <User>(member.email.Trim());
                if (inMemUser == null)
                {
                    inMemUser = dbr.Find <User>(t => t.EmailId.Equals(member.email.Trim())).FirstOrDefault();
                }
                member.groupid      = groupId;
                member.memberCode   = Domain.Socioboard.Helpers.SBHelper.RandomString(15);
                member.isAdmin      = false;
                member.memberStatus = Domain.Socioboard.Enum.GroupMemberStatus.MailSent;
                if (inMemUser != null)
                {
                    member.userId     = inMemUser.Id;
                    member.profileImg = inMemUser.ProfilePicUrl;
                    //todo : code to add in user notification list.
                }
                Groupmembers temp = dbr.Find <Groupmembers>(t => t.groupid == groupId && t.email == member.email).FirstOrDefault();
                if (temp == null)
                {
                    dbr.Add <Groupmembers>(member);

                    var savedMembers = dbr.Find <Groupmembers>(t => t.groupid == groupId && t.email == member.email).FirstOrDefault();

                    var lstnotifications = dbr.Single <Notifications>(t => t.MsgId == savedMembers.id);

                    if (lstnotifications == null && savedMembers != null)
                    {
                        var notify = new Notifications
                        {
                            MsgId            = savedMembers.id,
                            MsgStatus        = "Invited",
                            notificationtime = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
                            NotificationType = grp.groupName,
                            ReadOrUnread     = "Unread",
                            UserId           = member.userId
                        };
                        dbr.Add <Notifications>(notify);
                    }


                    _redisCache.Delete(Domain.Socioboard.Consatants.SocioboardConsts.CacheGroupMembers + groupId);
                    string path = _appEnv.WebRootPath + "\\views\\mailtemplates\\groupinvitation.html";
                    string html = System.IO.File.ReadAllText(path);
                    html = html.Replace("[FirstName]", member.firstName);
                    html = html.Replace("[JoinLink]", _appSettings.Domain + "/Home/GroupInvite?Token=" + member.memberCode + "&email=" + member.email);
                    _emailSender.SendMailSendGrid(_appSettings.frommail, "", member.email, "", "", "Socioboard Team Invitation Link", html, _appSettings.SendgridUserName, _appSettings.SendGridPassword);
                }
            }

            return(Ok());
        }
예제 #23
0
        public async Task <ActionResult> DraftScheduleMessage(string message, long userId, string scheduledatetime, long groupId, IFormFile files)
        {
            var    uploads     = _appEnv.WebRootPath + "\\wwwwroot\\upload\\";
            var    filename    = "";
            string postmessage = "";

            if (files != null)
            {
                if (files.Length > 0)
                {
                    var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
                    // await file.s(Path.Combine(uploads, fileName));
                    filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                               .Parse(files.ContentDisposition)
                               .FileName
                               .Trim('"');
                    var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];
                    //filename = _appEnv.WebRootPath + $@"\{tempName}";
                    filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}";
                    uploads  = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}";

                    // size += file.Length;
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        files.CopyTo(fs);
                        fs.Flush();
                    }
                    filename = uploads;
                }
            }


            string[] updatedmessgae = Regex.Split(message, "<br>");
            foreach (var item in updatedmessgae)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    if (item.Contains("hhh") || item.Contains("nnn"))
                    {
                        if (item.Contains("hhh"))
                        {
                            postmessage = postmessage + "\n\r" + item.Replace("hhh", "#");
                        }
                    }
                    else
                    {
                        postmessage = postmessage + "\n\r" + item;
                    }
                }
            }
            if (scheduledatetime == null)
            {
                scheduledatetime = DateTime.UtcNow.ToString();
            }

            message = postmessage;
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            Helper.ScheduleMessageHelper.DraftScheduleMessage(message, userId, groupId, filename, scheduledatetime, _appSettings, _redisCache, dbr, _logger);
            return(Ok());
        }
        public IActionResult PostCommentOnLinkedinCompanyPage(string pageId, long userId, string updatekey, string comment)
        {
            string             postmessage = "";
            DatabaseRepository dbr         = new DatabaseRepository(_logger, _env);

            comment = comment.Replace("hhh", "#").Replace("nnn", "&");
            string[] updatedmessgae = Regex.Split(comment, "<br>");
            foreach (var item in updatedmessgae)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    if (item.Contains("https://") || item.Contains("http://"))
                    {
                        try
                        {
                            comment = "http" + Utility.getBetween(item, "http", " ");
                            try
                            {
                                comment = comment.Split(' ')[0].ToString();
                            }
                            catch (Exception)
                            {
                                comment = "http" + Utility.getBetween(item, "http", " ");
                            }
                        }
                        catch
                        {
                            string temp_item = item + "###";
                            comment = "http" + Utility.getBetween(temp_item, "http", "###");
                            try
                            {
                                comment = comment.Split(' ')[0].ToString();
                            }
                            catch (Exception)
                            {
                                comment = "http" + Utility.getBetween(temp_item, "http", "###");
                            }
                        }
                    }
                    if (item.Contains("hhh"))
                    {
                        if (item.Contains("hhh"))
                        {
                            postmessage = postmessage + "\n\r" + item.Replace("hhh", "#");
                        }
                    }
                    else
                    {
                        //postmessage = postmessage + "\n\r" + item;
                    }
                    if (item.Contains("nnn"))
                    {
                        postmessage = postmessage + "\n\r" + item.Replace("nnn", "&");
                    }
                    else
                    {
                        //postmessage = postmessage + "\n\r" + item;
                    }
                    postmessage = postmessage + "\n\r" + item;
                }
            }
            try
            {
                //comment = "";
                //updatedtext = postmessage.Replace(url, "");
                // updatedtext = postmessage;
                comment = postmessage;
            }
            catch (Exception ex)
            {
                comment = postmessage;
            }
            string postdata = Repositories.LinkedInAccountRepository.PostCommentOnLinkedinCompanyPage(pageId, updatekey, comment, userId, _redisCache, _appSettings, dbr);

            return(Ok(postdata));
        }
        public IActionResult DeleteProfile(long groupId, long userId, string profileId)
        {
            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            return(Ok(GroupProfilesRepository.DeleteProfile(groupId, userId, profileId, _redisCache, dbr, _appSettings)));
        }
예제 #26
0
        public IActionResult AddGoogleAccount(string code, long groupId, long userId)
        {
            string             ret          = string.Empty;
            string             objRefresh   = string.Empty;
            string             refreshToken = string.Empty;
            string             access_token = string.Empty;
            DatabaseRepository dbr          = new DatabaseRepository(_logger, _appEnv);

            oAuthTokenGPlus ObjoAuthTokenGPlus = new oAuthTokenGPlus(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            oAuthToken      objToken           = new oAuthToken(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            JObject         userinfo           = new JObject();

            try
            {
                objRefresh = ObjoAuthTokenGPlus.GetRefreshToken(code);
                JObject objaccesstoken = JObject.Parse(objRefresh);
                _logger.LogInformation(objaccesstoken.ToString());
                try
                {
                    refreshToken = objaccesstoken["refresh_token"].ToString();
                }
                catch { }
                access_token = objaccesstoken["access_token"].ToString();
                string user = objToken.GetUserInfo("self", access_token.ToString());
                //_logger.LogInformation(user);
                userinfo = JObject.Parse(JArray.Parse(user)[0].ToString());
                string people = objToken.GetPeopleInfo("self", access_token.ToString(), Convert.ToString(userinfo["id"]));
                userinfo = JObject.Parse(JArray.Parse(people)[0].ToString());
            }
            catch (Exception ex)
            {
                //access_token = objaccesstoken["access_token"].ToString();
                //ObjoAuthTokenGPlus.RevokeToken(access_token);
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
                ret = "Access Token Not Found";
                return(Ok(ret));
            }
            Domain.Socioboard.Models.Googleplusaccounts gplusAcc = Api.Socioboard.Repositories.GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);

            if (gplusAcc != null && gplusAcc.IsActive == true)
            {
                if (gplusAcc.UserId == userId)
                {
                    return(Ok("GPlus account already added by you."));
                }
                return(Ok("GPlus account added by other user."));
            }
            Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == userId && t.id == groupId).FirstOrDefault();

            if (ngrp == null)
            {
                return(Ok("group not exist"));
            }
            // Adding GPlus Profile
            int x = Api.Socioboard.Repositories.GplusRepository.AddGplusAccount(userinfo, dbr, userId, ngrp.id, access_token, refreshToken, _redisCache, _appSettings, _logger);

            if (x == 1)
            {
                return(Ok("Gplus Account Added Successfully"));
            }
            else
            {
                return(Ok("Issues while adding account"));
            }
        }
예제 #27
0
        public IActionResult ComposeMessage(string message, string profileId, long userId, string imagePath, string link)
        {
            if (profileId != null)
            {
                string[] lstProfileIds = profileId.Split(',');
                profileId = lstProfileIds[0];
            }
            else
            {
                return(Ok("profileId required"));
            }
            string             ret = "";
            DatabaseRepository dbr = new DatabaseRepository(_logger, _env);

            Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(profileId, _redisCache, dbr);

            FacebookClient fb = new FacebookClient();

            fb.AccessToken = objFacebookAccount.AccessToken;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
            var args = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(message))
            {
                args["message"] = message;
            }
            args["privacy"] = FbUser.SetPrivacy("Public", fb, profileId);


            try
            {
                if (!string.IsNullOrEmpty(imagePath))
                {
                    Uri    u         = new Uri(imagePath);
                    string filename  = string.Empty;
                    string extension = string.Empty;
                    extension = System.IO.Path.GetExtension(u.AbsolutePath).Replace(".", "");
                    var media = new FacebookMediaObject
                    {
                        FileName    = "filename",
                        ContentType = "image/" + extension
                    };
                    //byte[] img = System.IO.File.ReadAllBytes(imagepath);
                    var    webClient = new WebClient();
                    byte[] img       = webClient.DownloadData(imagePath);
                    media.SetValue(img);
                    args["source"] = media;
                    ret            = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(link))
                    {
                        args["link"] = link;
                    }
                    ret = fb.Post("v2.0/" + objFacebookAccount.FbUserId + "/feed", args).ToString();
                }
                ScheduledMessage scheduledMessage = new ScheduledMessage();
                scheduledMessage.createTime   = DateTime.UtcNow;
                scheduledMessage.picUrl       = imagePath;
                scheduledMessage.profileId    = profileId;
                scheduledMessage.profileType  = Domain.Socioboard.Enum.SocialProfileType.Facebook;
                scheduledMessage.scheduleTime = DateTime.UtcNow;
                scheduledMessage.shareMessage = message;
                scheduledMessage.userId       = userId;
                scheduledMessage.status       = Domain.Socioboard.Enum.ScheduleStatus.Compleated;
                scheduledMessage.url          = ret;
                dbr.Add <ScheduledMessage>(scheduledMessage);

                ret = "success";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                ret = "failure";
            }

            return(Ok(ret));
        }
예제 #28
0
        public IActionResult GoogleLogin(string code, Domain.Socioboard.Enum.SBAccountType accType)
        {
            string ret          = string.Empty;
            string objRefresh   = string.Empty;
            string refreshToken = string.Empty;
            string access_token = string.Empty;

            oAuthTokenGPlus ObjoAuthTokenGPlus = new oAuthTokenGPlus(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            oAuthToken      objToken           = new oAuthToken(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri);
            JObject         userinfo           = new JObject();

            try
            {
                objRefresh = ObjoAuthTokenGPlus.GetRefreshToken(code);
                JObject objaccesstoken = JObject.Parse(objRefresh);
                _logger.LogInformation(objaccesstoken.ToString());
                try
                {
                    refreshToken = objaccesstoken["refresh_token"].ToString();
                }
                catch { }
                access_token = objaccesstoken["access_token"].ToString();
                string user = objToken.GetUserInfo("self", access_token.ToString());
                _logger.LogInformation(user);
                userinfo = JObject.Parse(JArray.Parse(user)[0].ToString());
            }
            catch (Exception ex)
            {
                //access_token = objaccesstoken["access_token"].ToString();
                //ObjoAuthTokenGPlus.RevokeToken(access_token);
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
                ret = "Access Token Not Found";
                return(Ok(ret));
            }

            string EmailId = string.Empty;

            try
            {
                EmailId = (Convert.ToString(userinfo["email"]));
            }
            catch { }
            if (string.IsNullOrEmpty(EmailId))
            {
                return(Ok("Google Not retuning Email"));
            }


            try
            {
                User inMemUser = _redisCache.Get <User>(EmailId);
                if (inMemUser != null)
                {
                    return(Ok(inMemUser));
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                _logger.LogError(ex.StackTrace);
            }



            DatabaseRepository dbr     = new DatabaseRepository(_logger, _appEnv);
            IList <User>       lstUser = dbr.Find <User>(t => t.EmailId.Equals(EmailId));

            if (lstUser != null && lstUser.Count() > 0)
            {
                DateTime d1 = DateTime.UtcNow;
                //User userTable = dbr.Single<User>(t => t.EmailId == EmailId);
                //userTable.LastLoginTime = d1;
                lstUser.First().LastLoginTime = d1;
                dbr.Update <User>(lstUser.First());
                _redisCache.Set <User>(lstUser.First().EmailId, lstUser.First());
                return(Ok(lstUser.First()));
            }
            else
            {
                Domain.Socioboard.Models.Googleplusaccounts gplusAcc = Api.Socioboard.Repositories.GplusRepository.getGPlusAccount(Convert.ToString(userinfo["id"]), _redisCache, dbr);
                if (gplusAcc != null && gplusAcc.IsActive == true)
                {
                    return(Ok("GPlus account added by other user."));
                }


                Domain.Socioboard.Models.User user = new Domain.Socioboard.Models.User();
                if (accType == Domain.Socioboard.Enum.SBAccountType.Free)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Free;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Deluxe)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Deluxe;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Premium)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Premium;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Topaz)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Topaz;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Platinum)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Platinum;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Gold)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Gold;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Ruby)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Ruby;
                }
                else if (accType == Domain.Socioboard.Enum.SBAccountType.Standard)
                {
                    user.AccountType = Domain.Socioboard.Enum.SBAccountType.Standard;
                }
                user.PaymentType        = Domain.Socioboard.Enum.PaymentType.paypal;
                user.ActivationStatus   = Domain.Socioboard.Enum.SBUserActivationStatus.Active;
                user.CreateDate         = DateTime.UtcNow;
                user.EmailId            = EmailId;
                user.ExpiryDate         = DateTime.UtcNow.AddDays(1);
                user.UserName           = "******";
                user.EmailValidateToken = "Google";
                user.UserType           = "User";
                user.LastLoginTime      = DateTime.UtcNow;
                user.PaymentStatus      = Domain.Socioboard.Enum.SBPaymentStatus.UnPaid;
                try
                {
                    user.FirstName = (Convert.ToString(userinfo["name"]));
                }
                catch { }
                user.RegistrationType = Domain.Socioboard.Enum.SBRegistrationType.Google;

                int  SavedStatus = dbr.Add <Domain.Socioboard.Models.User>(user);
                User nuser       = dbr.Single <User>(t => t.EmailId.Equals(user.EmailId));
                if (SavedStatus == 1 && nuser != null)
                {
                    Groups group = new Groups();
                    group.adminId     = nuser.Id;
                    group.createdDate = DateTime.UtcNow;
                    group.groupName   = Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName;
                    SavedStatus       = dbr.Add <Groups>(group);
                    if (SavedStatus == 1)
                    {
                        Groups ngrp = dbr.Find <Domain.Socioboard.Models.Groups>(t => t.adminId == nuser.Id && t.groupName.Equals(Domain.Socioboard.Consatants.SocioboardConsts.DefaultGroupName)).FirstOrDefault();
                        GroupMembersRepository.createGroupMember(ngrp.id, nuser, _redisCache, dbr);
                        // Adding GPlus Profile
                        Api.Socioboard.Repositories.GplusRepository.AddGplusAccount(userinfo, dbr, nuser.Id, ngrp.id, access_token, refreshToken, _redisCache, _appSettings, _logger);
                    }
                }
                return(Ok(nuser));
            }
        }
        public static List <Domain.Socioboard.Models.Mongo.Rss> GetRssDataByUser(long userId, long groupId, Helper.AppSettings _appSettings, DatabaseRepository dbr)
        {
            string[]        profileids     = null;
            MongoRepository _RssRepository = new MongoRepository("Rss", _appSettings);
            List <Domain.Socioboard.Models.Mongo.Rss>     lstRss           = new List <Domain.Socioboard.Models.Mongo.Rss>();
            List <Domain.Socioboard.Models.Groupprofiles> lstGroupprofiles = dbr.Find <Domain.Socioboard.Models.Groupprofiles>(t => t.groupId == groupId).ToList();

            profileids = lstGroupprofiles.Select(t => t.profileId).ToArray();
            var ret  = _RssRepository.Find <Domain.Socioboard.Models.Mongo.Rss>(t => profileids.Contains(t.ProfileId));
            var task = Task.Run(async() =>
            {
                return(await ret);
            });

            return(lstRss = task.Result.ToList());
        }
예제 #30
0
 public BaseClassImpl()
 {
     this.databaseRepository = new DatabaseRepository();
 }
        public static List <Domain.Socioboard.Models.Mongo.twtfollowfollowing> gettwtfollofollowingReport(string[] profileId, int daysCount, Helper.Cache _redisCache, Helper.AppSettings _appSettings, DatabaseRepository dbr)
        {
            MongoRepository mongorepo = new MongoRepository("MongoTwitterDailyReports", _appSettings);
            List <Domain.Socioboard.Models.Mongo.twtfollowfollowing> inMemtwtDailyReports = _redisCache.Get <List <Domain.Socioboard.Models.Mongo.twtfollowfollowing> >(Domain.Socioboard.Consatants.SocioboardConsts.CacheInstagramDailyReport + profileId);

            if (inMemtwtDailyReports != null)
            {
                return(inMemtwtDailyReports);
            }
            else
            {
                List <Domain.Socioboard.Models.Mongo.twtfollowfollowing> reportdata = new List <twtfollowfollowing>();
                DateTime dayStart = new DateTime(DateTime.UtcNow.AddDays(-daysCount).Year, DateTime.UtcNow.AddDays(-daysCount).Month, DateTime.UtcNow.AddDays(-daysCount).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.MongoTwitterDailyReports>(t => profileId.Contains(t.profileId) && t.timeStamp <= Helper.DateExtension.ConvertToUnixTimestamp(dayEnd) && t.timeStamp >= Helper.DateExtension.ConvertToUnixTimestamp(dayStart));
                var      task     = Task.Run(async() =>
                {
                    return(await ret);
                });

                if (task.Result != null)
                {
                    IList <Domain.Socioboard.Models.Mongo.MongoTwitterDailyReports> lstfbpagereportdata = task.Result.ToList();
                    var Instapid = lstfbpagereportdata.GroupBy(x => x.profileId).Select(x => x.First()).ToList();
                    var random   = new Random();
                    foreach (Domain.Socioboard.Models.Mongo.MongoTwitterDailyReports twtprofiledata in Instapid)
                    {
                        // DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
                        List <Domain.Socioboard.Models.TwitterAccount> lstTwtAcc = new List <Domain.Socioboard.Models.TwitterAccount>();
                        Domain.Socioboard.Models.TwitterAccount        twtAcc    = Repositories.TwitterRepository.getTwitterAccount(twtprofiledata.profileId, _redisCache, dbr);
                        //Domain.Socioboard.Models.TwitterAccount twtAccname = dbr.Find().twtAccname();
                        var randomColor = String.Format("#{0:X6}", random.Next(0x1000000));
                        Domain.Socioboard.Models.Mongo.twtfollowfollowing repo = new twtfollowfollowing();
                        long twtFollowerCount  = lstfbpagereportdata.ToList().Where(t => t.profileId == twtprofiledata.profileId).Sum(t => t.newFollowers);
                        long twtFollowingCount = lstfbpagereportdata.ToList().Where(t => t.profileId == twtprofiledata.profileId).Sum(t => t.newFollowing);
                        repo.startdate          = dayStart;
                        repo.endtdate           = dayEnd;
                        repo.twtFollowerCounts  = twtFollowerCount;
                        repo.twtFollowingCounts = twtFollowingCount;
                        repo.profileId          = twtprofiledata.profileId;

                        repo.twtName    = twtAcc.twitterScreenName;
                        repo.profilepic = twtAcc.profileImageUrl;
                        repo.colors     = Convert.ToString(randomColor);
                        reportdata.Add(repo);
                    }
                    // long TwitterFollowerCount = lstfbpagereportdata.ToList().Where(t => profileId.Contains(t.profileId)).Sum(t => t.followcount);
                    if (lstfbpagereportdata.Count > 0)
                    {
                        _redisCache.Set(Domain.Socioboard.Consatants.SocioboardConsts.CacheInstagramDailyReport + profileId, lstfbpagereportdata.ToList());
                    }
                    return(reportdata.OrderBy(t => t.startdate).ToList());
                    // return lstfbpagereportdata.OrderBy(t => t.date).ToList();
                }
                return(new List <Domain.Socioboard.Models.Mongo.twtfollowfollowing>());
            }
        }
예제 #32
0
        public static List <Groupprofiles> getGroupProfiles(long groupId, Cache _redisCache, DatabaseRepository dbr)
        {
            return(GetAllGroupProfiles(groupId, _redisCache, dbr));
            //try
            //{
            //    var inMemGroupProfiles = _redisCache.Get<List<Groupprofiles>>(SocioboardConsts.CacheGroupProfiles + groupId);

            //    if (inMemGroupProfiles != null)
            //        return inMemGroupProfiles;
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}

            //var topgroupProfiles = dbr.Find<Groupprofiles>(t => t.groupId == groupId).ToList();
            //var groupProfiles = topgroupProfiles.Take(3).ToList();
            //_redisCache.Set(SocioboardConsts.CacheGroupProfiles + groupId, groupProfiles);
            //return groupProfiles;
        }
예제 #33
0
        public List<Tab> GetTabs(string countryCode)
        {
            return LogTime(() =>
            {
                var db = new DatabaseRepository();
                var data = db.GetAllTabs();
                var result =
                    data.GroupBy(t => new Tuple<string, string>(t.TabCode, t.TabName))
                        .Select(
                            r =>
                                new Tab
                                {
                                    Code = r.Key.Item1,
                                    Name = r.Key.Item2,
                                    Sections =
                                        r.GroupBy(g => g.SectionName)
                                            .Select(
                                                t =>
                                                    new Section
                                                    {
                                                        OrderId = t.First().SectionOrderId.Value,
                                                        SectionType = t.First().SectionType,
                                                        Id = t.First().SectionId,
                                                        Name = t.Key,
                                                        Description = t.First().SectionDescription,
                                                        ChartIds =
                                                            t.Where(c => c.ChartId != null)
                                                                .OrderBy(c => c.ChartOrderId)
                                                                .Select(c => c.ChartId)
                                                                .ToList()
                                                    })
                                            .ToList()
                                }).ToList();
                foreach (var t in result)
                {
                    t.Sections = t.Sections.OrderBy(s => s.OrderId).ToList();
                }

                var projects = GetProjects(countryCode);
                var documents = GetDocuments(countryCode);
                var other = GetOtherResources(countryCode);
                var keyStats = GetKeyStatistics(countryCode);

                var sections = result.SelectMany(t => t.Sections);
                foreach (var section in sections)
                {
                    switch (section.SectionType)
                    {
                        case "IFC":
                        case "Bank":
                        case "Knowledge Product":
                            section.Data = projects.Where(p => p.ProjectType == section.SectionType).ToList();
                            break;
                        case "Document":
                            section.Data = documents;
                            break;
                        case "Other":
                            section.Data = other;
                            break;
                        case "Key Statistics":
                            section.Data = keyStats;
                            break;
                    }
                }
                return result;
            }, "tab info request for country {0}", countryCode);
        }
예제 #34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="redisCache"></param>
        /// <param name="dbr"></param>
        /// <returns></returns>
        public static List <Groupprofiles> GetAllGroupProfiles(long groupId, Cache redisCache, DatabaseRepository dbr)
        {
            var addedProfile = new List <SocialProfileType>();

            var groupProfilesPerUserPlan = new List <Groupprofiles>();

            try
            {
                var inMemGroupProfiles = redisCache.Get <List <Groupprofiles> >(SocioboardConsts.CacheGroupProfiles + groupId);

                if (inMemGroupProfiles != null && inMemGroupProfiles.Count > 0)
                {
                    var userDetails = redisCache.Get <User>("User") ?? dbr.FindFirstMatch <User>(t => t.Id == inMemGroupProfiles[0].profileOwnerId);

                    foreach (var profile in inMemGroupProfiles)
                    {
                        if (userDetails.AccountType == SBAccountType.Free && addedProfile.Contains(profile.profileType))
                        {
                            continue;
                        }

                        if (userDetails.AccountType != SBAccountType.Free)
                        {
                            var maxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(userDetails.AccountType);
                            if (groupProfilesPerUserPlan.Count >= maxCount)
                            {
                                return(groupProfilesPerUserPlan);
                            }
                        }

                        addedProfile.Add(profile.profileType);

                        groupProfilesPerUserPlan.Add(profile);
                    }

                    return(groupProfilesPerUserPlan);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var groupProfiles = dbr.Find <Groupprofiles>(t => t.groupId == groupId).ToList();

            redisCache.Set(SocioboardConsts.CacheGroupProfiles + groupId, groupProfiles);

            if (groupProfiles.Count == 0)
            {
                return(groupProfilesPerUserPlan);
            }

            var currentUserDetails = redisCache.Get <User>("User") ?? dbr.FindFirstMatch <User>(t => t.Id == groupProfiles[0].profileOwnerId);

            foreach (var profile in groupProfiles)
            {
                if (currentUserDetails.AccountType == SBAccountType.Free && addedProfile.Contains(profile.profileType))
                {
                    continue;
                }

                if (currentUserDetails.AccountType != SBAccountType.Free)
                {
                    var maxCount = Domain.Socioboard.Helpers.SBHelper.GetMaxProfileCount(currentUserDetails.AccountType);
                    if (groupProfilesPerUserPlan.Count >= maxCount)
                    {
                        return(groupProfilesPerUserPlan);
                    }
                }

                addedProfile.Add(profile.profileType);

                groupProfilesPerUserPlan.Add(profile);
            }

            return(groupProfilesPerUserPlan);
        }
예제 #35
0
        public async Task <ActionResult> ScheduleMessage(string message, string profileId, long userId, string imagePath, string link, string scheduledatetime, string localscheduletime, IFormFile files)
        {
            var    filename    = "";
            string postmessage = "";
            var    uploads     = _appEnv.WebRootPath + "\\wwwwroot\\upload\\" + profileId;

            if (files != null)
            {
                if (files.Length > 0)
                {
                    var fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');
                    // await file.s(Path.Combine(uploads, fileName));
                    filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                               .Parse(files.ContentDisposition)
                               .FileName
                               .Trim('"');
                    //apiimgPath = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1]}";
                    var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];
                    filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}";

                    uploads = _appSettings.ApiDomain + "/api/Media/get?id=" + $@"{tempName}";

                    // size += file.Length;
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        files.CopyTo(fs);
                        fs.Flush();
                    }
                    filename = uploads;
                }
            }
            else if (!string.IsNullOrEmpty(imagePath))
            {
                filename = imagePath;
            }


            string[] updatedmessgae = Regex.Split(message, "<br>");
            foreach (var item in updatedmessgae)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    if (item.Contains("https://") || item.Contains("http://"))
                    {
                        try
                        {
                            link = "http" + getBetween(item, "http", " ");
                        }
                        catch
                        {
                            string temp_item = item + "###";
                            link = "http" + getBetween(temp_item, "http", "###");
                        }
                    }
                    if (item.Contains("hhh") || item.Contains("nnn"))
                    {
                        if (item.Contains("hhh"))
                        {
                            postmessage = postmessage + "\n\r" + item.Replace("hhh", "#");
                        }
                    }
                    else
                    {
                        postmessage = postmessage + "\n\r" + item;
                    }
                }
            }
            if (!string.IsNullOrEmpty(link))
            {
                message = postmessage.Replace(link, "");;
            }

            DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);

            string[] lstProfileIds = null;
            if (profileId != null)
            {
                lstProfileIds = profileId.Split(',');
                profileId     = lstProfileIds[0];
            }
            else
            {
                return(Ok("profileId required"));
            }

            string retunMsg = string.Empty;

            foreach (var item in lstProfileIds)
            {
                if (item.StartsWith("fb"))
                {
                    try
                    {
                        string prId = item.Substring(3, item.Length - 3);
                        Domain.Socioboard.Models.Facebookaccounts objFacebookaccounts = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr);
                        Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName, message, Domain.Socioboard.Enum.SocialProfileType.Facebook, userId, link, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, localscheduletime, _appSettings, _redisCache, dbr, _logger);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex.StackTrace);
                        //return Ok("Issue With Facebook schedulers");
                    }
                }
                if (item.StartsWith("page"))
                {
                    try
                    {
                        string prId = item.Substring(5, item.Length - 5);
                        Domain.Socioboard.Models.Facebookaccounts objFacebookaccounts = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(prId, _redisCache, dbr);
                        Helper.ScheduleMessageHelper.ScheduleMessage(prId, objFacebookaccounts.FbUserName, message, Domain.Socioboard.Enum.SocialProfileType.FacebookFanPage, userId, link, filename, "https://graph.facebook.com/" + prId + "/picture?type=small", scheduledatetime, localscheduletime, _appSettings, _redisCache, dbr, _logger);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex.StackTrace);
                        // return Ok("Issue With Facebook Page schedulers");
                    }
                }
                if (item.StartsWith("tw"))
                {
                    try
                    {
                        string prId = item.Substring(3, item.Length - 3);
                        Domain.Socioboard.Models.TwitterAccount objTwitterAccount = Api.Socioboard.Repositories.TwitterRepository.getTwitterAccount(prId, _redisCache, dbr);
                        Helper.ScheduleMessageHelper.ScheduleMessage(prId, objTwitterAccount.twitterScreenName, message, Domain.Socioboard.Enum.SocialProfileType.Twitter, userId, "", filename, objTwitterAccount.profileImageUrl, scheduledatetime, localscheduletime, _appSettings, _redisCache, dbr, _logger);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex.StackTrace);

                        // return Ok("Issue With Twitter schedulers");
                    }
                }
                if (item.StartsWith("lin"))
                {
                    try
                    {
                        string prId = item.Substring(4, item.Length - 4);
                        Domain.Socioboard.Models.LinkedInAccount objLinkedInAccount = Api.Socioboard.Repositories.LinkedInAccountRepository.getLinkedInAccount(prId, _redisCache, dbr);
                        Helper.ScheduleMessageHelper.ScheduleMessage(prId, objLinkedInAccount.LinkedinUserName, message, Domain.Socioboard.Enum.SocialProfileType.LinkedIn, userId, "", filename, objLinkedInAccount.ProfileImageUrl, scheduledatetime, localscheduletime, _appSettings, _redisCache, dbr, _logger);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex.StackTrace);

                        // return Ok("Issue With Linkedin schedulers");
                    }
                }
                if (item.StartsWith("Cmpylinpage"))
                {
                    try
                    {
                        string prId = item.Substring(12, item.Length - 12);
                        Domain.Socioboard.Models.LinkedinCompanyPage objLinkedinCompanyPage = Api.Socioboard.Repositories.LinkedInAccountRepository.getLinkedinCompanyPage(prId, _redisCache, dbr);
                        Helper.ScheduleMessageHelper.ScheduleMessage(prId, objLinkedinCompanyPage.LinkedinPageName, message, Domain.Socioboard.Enum.SocialProfileType.LinkedInComapanyPage, userId, "", filename, objLinkedinCompanyPage.LogoUrl, scheduledatetime, localscheduletime, _appSettings, _redisCache, dbr, _logger);
                    }
                    catch (System.Exception ex)
                    {
                        _logger.LogError(ex.StackTrace);

                        // return Ok("Issue With Linkedin Page schedulers");
                    }
                }
            }
            return(Ok("scheduled"));
        }
        public DatabaseVersionSetup GetVersionSetup()
        {
            var versionSetup = new DatabaseVersionSetup();
            mockSqlServerDatabaseProfile = new Mock<SqlServerDatabaseProfile>(MockBehavior.Strict, "Data Source=GMV-RW-LT;Initial Catalog=Intercontinental;Integrated Security=True"
                , "Intercontinental4"
                , "Intercontinental"
                , _mockITracker.Object);

            var profile = new DatabaseVersionSetup.Profile("Default",
                                                        mockSqlServerDatabaseProfile.Object);
            profile.AddProperties("test1", "test1Prof|withvar|${dp.DatabaseName}|");
            profile.AddProperties("test2", "test2");
            profile.AddProperties("test2", "test2|over");
            profile.AddProperties("insert", "insert.sql");
            profile.AddProperties("update", "update.sql");
            profile.AddProperties("delete", "delete.sql");
            versionSetup.Profiles.Add(profile);

            var runner = new SqlRunner("CREATE DATABASE ${dp.DatabaseName};", "USE Master; DROP DATABASE ${dp.DatabaseName};");
            var repository = new DatabaseRepository("Intercontinental", new UpdatesMetadata(1, "Todau", "Initialize", "rolf", runner));
            repository.AddProperties("test0", "test0");
            repository.AddProperties("test1", "test1");
            var versions = new UpdatesMetadata(2, "2010-04-16", "First update", "Rolf Wessels",
                new SqlRunner(
                    @"Create2 ${test0} ${test1} ${test2} ${test3}",
                    @"RoleBack2 ${test0} ${test1} ${test2} ${test3}",
                    @"TestData2 ${test0} ${test1} ${test2} ${test3}"
                    )
                );
            repository.Updates.Add(versions);

            versions = new UpdatesMetadata(3, "2010-04-16", "First update", "Rolf Wessels",
                new SqlRunner(
                    @"Create3 ${test0} ${test1} ${test2} ${test3}",
                    @"RoleBack3 ${test0} ${test1} ${test2} ${test3}",
                    @"TestData3 ${test0} ${test1} ${test2} ${test3}"
                    )
                );
            repository.Updates.Add(versions);
            File.WriteAllText(@"resources\insert.sql", @"Create4 ${test0} ${test1} ${test2} ${test3}");
            File.WriteAllText(@"resources\update.sql", @"RoleBack4 ${test0} ${test1} ${test2} ${test3}");
            File.WriteAllText(@"resources\delete.sql", @"TestData4 ${test0} ${test1} ${test2} ${test3}");
            repository.Updates.Add(new UpdatesMetadata(4, "2010-04-16", "First update", "Rolf Wessels",
                new SqlRunner(new SqlFilesExecuter(new[] { @"resources\${insert}" }),
                    new SqlFilesExecuter(new[] { @"resources\${update}" }),
                    new SqlFilesExecuter(new[] { @"resources\${delete}" }))));

            versionSetup.Repository.Add(repository);

            return versionSetup;
        }
 private void LoadRepositories(DatabaseVersionSetup versionSetup, IEnumerable<XElement> enumerable)
 {
     foreach (var element in enumerable){
         string value = element.Attribute("id").Value;
         var initializeRunners = ReadUpdates(element.Element("initialRunner"));
         XElement properties = element.Element("properties");
         KeyValuePair<string, string>[] props = LoadProperties(properties);
         var databaseRepository = new DatabaseRepository(value, initializeRunners[0]);
         databaseRepository.AddProperties(props);
         databaseRepository.Updates.AddRange(ReadUpdates(element.Element("updates")));
         versionSetup.Repository.Add(databaseRepository);
     }
     //check for duplicate repository ID
     if (versionSetup.Repository.Select(x => x.Id).Distinct().Count() != versionSetup.Repository.Count)
     {
         throw new Exception(string.Format("Duplicate repository ID names ({0})", string.Join(", ", versionSetup.Repository.Select(x => x.Id).ToArray())));
     }
 }
예제 #38
0
        public IActionResult PluginComposemessage(string profile, string twitterText, string tweetId, string tweetUrl, string facebookText, string url, string imgUrl, long userId)
        {
            string[] profiles = profile.Split(',');

            int i = 0;

            foreach (var item in profiles)
            {
                string[] ids = item.Split('~');
                if (ids[1] == "facebook")
                {
                    string             updatedtext = "";
                    string             postmessage = "";
                    DatabaseRepository dbr         = new DatabaseRepository(_logger, _appEnv);
                    Domain.Socioboard.Models.Facebookaccounts objFacebookAccount = Api.Socioboard.Repositories.FacebookRepository.getFacebookAccount(ids[0], _redisCache, dbr);
                    if (!string.IsNullOrEmpty(facebookText))
                    {
                        string[] updatedmessgae = Regex.Split(facebookText, "<br>");
                        foreach (var items in updatedmessgae)
                        {
                            if (!string.IsNullOrEmpty(items))
                            {
                                if (items.Contains("https://") || items.Contains("http://"))
                                {
                                    if (string.IsNullOrEmpty(url))
                                    {
                                        url = items;
                                        if (items.Contains("https://"))
                                        {
                                            string link = getBetween(url + "###", "https", "###");
                                            link = "https" + link;
                                            url  = link;
                                        }
                                        if (items.Contains("http://"))
                                        {
                                            string link = getBetween(url + "###", "http", "###");
                                            link = "http" + link;
                                            url  = link;
                                        }
                                    }
                                }
                                if (items.Contains("hhh") || items.Contains("nnn"))
                                {
                                    if (items.Contains("hhh"))
                                    {
                                        postmessage = postmessage + "\n\r" + items.Replace("hhh", "#");
                                    }
                                    else
                                    {
                                        postmessage = postmessage + "\n\r" + items;
                                    }
                                }
                                else
                                {
                                    postmessage = postmessage + "\n\r" + items;
                                }
                            }
                        }
                    }
                    updatedtext = postmessage.Replace(url, "");
                    int count = dbr.GetCount <ScheduledMessage>(t => t.shareMessage == updatedtext && t.profileId == objFacebookAccount.FbUserId && t.url == imgUrl && t.scheduleTime.Date == DateTime.UtcNow.Date);
                    if (count > 0)
                    {
                        i++;
                    }
                    else
                    {
                        string ret = Helper.FacebookHelper.ComposeMessage(objFacebookAccount.FbProfileType, objFacebookAccount.AccessToken, objFacebookAccount.FbUserId, updatedtext, ids[0], userId, imgUrl, url, dbr, _logger);
                    }
                }
                else
                {
                    DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv);
                    if (!string.IsNullOrEmpty(twitterText) || !string.IsNullOrEmpty(imgUrl))
                    {
                        twitterText = twitterText + " " + tweetUrl;
                        int count = dbr.GetCount <ScheduledMessage>(t => t.shareMessage == twitterText && t.profileId == ids[0] && t.url == imgUrl && t.scheduleTime.Date == DateTime.UtcNow.Date);
                        if (count > 0)
                        {
                            i++;
                        }
                        else
                        {
                            string ret = Helper.TwitterHelper.PostTwitterMessage(_appSettings, _redisCache, twitterText, ids[0], userId, imgUrl, true, dbr, _logger);
                        }
                    }
                    else
                    {
                        string data = TwitterRepository.TwitterRetweet_post(ids[0], tweetId, userId, 0, dbr, _logger, _redisCache, _appSettings);
                    }
                }
            }
            if (i > 0)
            {
                return(Ok("it seems you already posted this message to few profiles"));
            }
            return(Ok("successfully posted"));
        }