Esempio n. 1
0
        public DataTable getCountryAnalyticsApi(string profileId,Guid user)
        {
            DataTable dtAnalytics = new DataTable();
            try
            {
               
                Analytics objAlyt = new Analytics();
                oAuthTokenGa obj = new oAuthTokenGa();
                GoogleAnalyticsAccountRepository objGaAccRepo=new GoogleAnalyticsAccountRepository();
                GoogleAnalyticsStats objGaStats = new GoogleAnalyticsStats();
                GoogleAnalyticsStatsRepository objGaStatsRepo=new GoogleAnalyticsStatsRepository();
                GoogleAnalyticsAccount objGaAcc = objGaAccRepo.getGoogelAnalyticsAccountHomeDetailsById(profileId, user);

                string strRefresh = obj.GetAccessToken(objGaAcc.RefreshToken);
                    if (!strRefresh.StartsWith("["))
                        strRefresh = "[" + strRefresh + "]";
                    JArray objArray = JArray.Parse(strRefresh);
                    foreach (var itemRefresh in objArray)
                    {
                        objGaAcc.AccessToken = itemRefresh["access_token"].ToString();
                    }
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.LoadXml(objAlyt.getAnalyticsData(objGaAcc.GaProfileId, "metrics=ga:visits&dimensions=ga:country", "2013-01-01", "2013-07-15", objGaAcc.AccessToken));
                    dtAnalytics= getdatafromXml(xDoc);
                    for (int i = 0; i < dtAnalytics.Rows.Count; i++)
                    {
                        objGaStats.EntryDate = DateTime.Now;
                        objGaStats.GaAccountId = objGaAcc.GaAccountId;
                        if (dtAnalytics.Rows[i]["title"].ToString().Contains("ga:country"))
                            objGaStats.gaCountry = dtAnalytics.Rows[i]["title"].ToString().Substring(11);
                        objGaStats.gaVisits = dtAnalytics.Rows[i]["ga:visitors"].ToString();
                        objGaStats.GaProfileId = objGaAcc.GaProfileId;
                        objGaStats.Id = Guid.NewGuid();
                        objGaStats.UserId = user;
                        if (!objGaStatsRepo.checkGoogleAnalyticsDateStatsExists(objGaAcc.GaProfileId, "country", dtAnalytics.Rows[i]["title"].ToString(), user))
                            objGaStatsRepo.addGoogleAnalyticsStats(objGaStats);
                        else
                            objGaStatsRepo.updateGoogleAnalyticsStats(objGaStats);
                    }
            }
            catch (Exception Err)
            {
                Console.Write(Err.StackTrace);
            }
            return dtAnalytics;
        }
        public string UpdateGoogleAnalyticsAccount(string ProfileId, string AccessToken, string HostName)
        {
            try
            {
                HostName = HostName.Replace("www.", "");
                Analytics _Analytics = new Analytics();
                string visits = string.Empty;
                string pageviews = string.Empty;
                string finalToken = string.Empty;
                oAuthTokenGa objToken = new oAuthTokenGa();
                string finaltoken = objToken.GetAccessToken(AccessToken);
                JObject objArray = JObject.Parse(finaltoken);

                try
                {
                    finalToken = objArray["access_token"].ToString();
                    // break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
                try
                {
                    string analytics = _Analytics.getAnalyticsData(ProfileId, "ga:visits,ga:pageviews", DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"), DateTime.UtcNow.ToString("yyyy-MM-dd"), finalToken);
                    JObject JData = JObject.Parse(analytics);
                    visits = JData["totalsForAllResults"]["ga:visits"].ToString();
                    pageviews = JData["totalsForAllResults"]["ga:pageviews"].ToString();

                    double startUnixTime = DateTime.UtcNow.AddDays(-7).Date.ToUnixTimestamp();
                    double endUnixTime = DateTime.UtcNow.Date.ToUnixTimestamp();
                    var ret = TwtsearchRepo.Find<Domain.Socioboard.MongoDomain.TwitterUrlMentions>(t => t.HostName.Equals(HostName));
                    var task = Task.Run(async () =>
                    {
                        return await ret;
                    });
                    int twtCount = task.Result.Where(t => t.Feeddate > startUnixTime && t.Feeddate < endUnixTime).ToList().Count;

                    var ret1 = ArticlesAndBlogsRepo.Find<Domain.Socioboard.MongoDomain.ArticlesAndBlogs>(t => t.HostName.Equals(HostName));
                    var task1 = Task.Run(async () =>
                    {
                        return await ret1;
                    });
                    int articleCount = task1.Result.Where(t => t.Created_Time > startUnixTime && t.Created_Time < endUnixTime).ToList().Count;

                    _GoogleAnalyticsAccountRepository.updateGoogelAnalyticsUser(ProfileId, Double.Parse(visits), Double.Parse(pageviews), Double.Parse(twtCount.ToString()), Double.Parse(articleCount.ToString()));

                }
                catch (Exception ex)
                {
                    logger.Error("UpdateGoogleAnalyticsAccount1 => " + ex.Message);
                }
            }
            catch (Exception ex)
            {
                logger.Error("UpdateGoogleAnalyticsAccount2 => " + ex.Message);
            }

            return "Successfuly Updated";
        }
        public string GetGoogleAnalyticsData(string ProfileId, string AccessToken, string HostName)
        {
            try
            {
                HostName = HostName.Replace("www.", "");
                string arrVisit = string.Empty;
                string arrViews = string.Empty;
                string arrTwtMentions = string.Empty;
                string arrActicleandBlogs = string.Empty;
                string finalToken = string.Empty;
                oAuthTokenGa objToken = new oAuthTokenGa();
                string finaltoken = objToken.GetAccessToken(AccessToken);
                try
                {
                    JObject objArray = JObject.Parse(finaltoken);
                    finalToken = objArray["access_token"].ToString();
                }
                catch (Exception ex)
                {
                    finalToken = AccessToken;
                    Console.WriteLine(ex.StackTrace);
                }
                Analytics _Analytics = new Analytics();
                DateTime startDate = DateTime.UtcNow.AddDays(-90);
                while (startDate.Date < DateTime.UtcNow.Date)
                {
                    try
                    {
                        string visits = string.Empty;
                        string pageviews = string.Empty;
                        try
                        {
                            string analytics = _Analytics.getAnalyticsData(ProfileId, "ga:visits,ga:pageviews", startDate.ToString("yyyy-MM-dd"), startDate.AddDays(2).ToString("yyyy-MM-dd"), finalToken);
                            JObject JData = JObject.Parse(analytics);
                            visits = JData["totalsForAllResults"]["ga:visits"].ToString();
                            pageviews = JData["totalsForAllResults"]["ga:pageviews"].ToString();
                            arrVisit += visits + ",";
                            arrViews += pageviews + ",";
                        }
                        catch (Exception ex)
                        {
                            arrVisit += "0" + ",";
                            arrViews += "0" + ",";
                        }

                        long startUnixTime = startDate.Date.ToUnixTimestamp();
                        long endUnixTime = startDate.AddDays(3).Date.AddSeconds(-1).ToUnixTimestamp();
                        var ret = TwtsearchRepo.Find<Domain.Socioboard.MongoDomain.TwitterUrlMentions>(t => t.HostName.Equals(HostName));
                        var task = Task.Run(async () =>
                        {
                            return await ret;
                        });
                        IList<Domain.Socioboard.MongoDomain.TwitterUrlMentions> lstTwitterUrlMentions = task.Result.ToList();
                        int twtCount = lstTwitterUrlMentions.Count(t => t.Feeddate > startUnixTime && t.Feeddate <= endUnixTime);

                        arrTwtMentions += twtCount.ToString() + ",";

                        var ret1 = ArticlesAndBlogsRepo.Find<Domain.Socioboard.MongoDomain.ArticlesAndBlogs>(t => t.HostName.Equals(HostName));
                        var task1 = Task.Run(async () =>
                        {
                            return await ret1;
                        });
                        IList<Domain.Socioboard.MongoDomain.ArticlesAndBlogs> lstArticlesAndBlogs=task1.Result.ToList();
                        int artucleCount = lstArticlesAndBlogs.Count(t => t.Created_Time > startUnixTime && t.Created_Time <= endUnixTime);

                        arrActicleandBlogs += artucleCount.ToString() + ",";

                        startDate = startDate.AddDays(3);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("GetGoogleAnalyticsData1 => " + ex.Message);
                    }
                }
                arrVisit = arrVisit.TrimEnd(',');
                arrViews = arrViews.TrimEnd(',');
                arrTwtMentions = arrTwtMentions.TrimEnd(',');
                arrActicleandBlogs = arrActicleandBlogs.TrimEnd(',');
                Domain.Socioboard.Domain.GoogleAnalyticsReport _GoogleAnalyticsReport = new Domain.Socioboard.Domain.GoogleAnalyticsReport();
                _GoogleAnalyticsReport.GaProfileId = ProfileId;
                _GoogleAnalyticsReport.Views = arrViews;
                _GoogleAnalyticsReport.Visits = arrVisit;
                _GoogleAnalyticsReport.TwitterMention = arrTwtMentions;
                _GoogleAnalyticsReport.Article_Blogs = arrActicleandBlogs;
                _GoogleAnalyticsAccountRepository.AddGoogleAnalyticsReport(_GoogleAnalyticsReport);
            }
            catch (Exception ex)
            {
                logger.Error("GetGoogleAnalyticsData2 => " + ex.Message);
            }
            return "Updated Successfuly";
        }
        public string AddAnalyticsProfiles(string GAProfiles, string UserId, string GroupId)
        {
            try
            {
                Analytics _Analytics = new Analytics();
                List<Domain.Socioboard.Helper.GoogleAnalyticsProfiles> lstGoogleAnalyticsProfiles = (List<Domain.Socioboard.Helper.GoogleAnalyticsProfiles>)new JavaScriptSerializer().Deserialize(GAProfiles, typeof(List<Domain.Socioboard.Helper.GoogleAnalyticsProfiles>));
                Domain.Socioboard.Domain.GoogleAnalyticsAccount _GoogleAnalyticsAccount;
                foreach (var item in lstGoogleAnalyticsProfiles)
                {
                    try
                    {
                        _GoogleAnalyticsAccount = new Domain.Socioboard.Domain.GoogleAnalyticsAccount();
                        _GoogleAnalyticsAccount.UserId = Guid.Parse(UserId);
                        _GoogleAnalyticsAccount.EmailId = item.EmailId;
                        _GoogleAnalyticsAccount.GaAccountId = item.AccountId;
                        _GoogleAnalyticsAccount.GaAccountName = item.AccountName;
                        _GoogleAnalyticsAccount.GaWebPropertyId = item.WebPropertyId;
                        _GoogleAnalyticsAccount.GaProfileId = item.ProfileId;
                        _GoogleAnalyticsAccount.GaProfileName = item.ProfileName;
                        _GoogleAnalyticsAccount.AccessToken = item.AccessToken;
                        _GoogleAnalyticsAccount.RefreshToken = item.RefreshToken;
                        _GoogleAnalyticsAccount.WebsiteUrl = item.WebsiteUrl;
                        string visits = string.Empty;
                        string pageviews = string.Empty;
                        try
                        {
                            string analytics = _Analytics.getAnalyticsData(item.ProfileId, "ga:visits,ga:pageviews", DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"), DateTime.UtcNow.ToString("yyyy-MM-dd"), item.AccessToken);
                            JObject JData = JObject.Parse(analytics);
                            visits = JData["totalsForAllResults"]["ga:visits"].ToString();
                            pageviews = JData["totalsForAllResults"]["ga:pageviews"].ToString();
                        }
                        catch (Exception ex)
                        {
                            visits = "0";
                            pageviews = "0";
                        }
                        _GoogleAnalyticsAccount.Views = Double.Parse(pageviews);
                        _GoogleAnalyticsAccount.Visits = Double.Parse(visits);
                        _GoogleAnalyticsAccount.ProfilePicUrl = ConfigurationManager.AppSettings["DomainName"] + "/Themes/" + ConfigurationManager.AppSettings["DefaultGroupName"] + "/Contents/img/analytics_img.png";
                        _GoogleAnalyticsAccount.IsActive = true;
                        _GoogleAnalyticsAccount.EntryDate = DateTime.UtcNow;
                        if (!_GoogleAnalyticsAccountRepository.checkGoogelAnalyticsUserExists(item.ProfileId, item.AccountId, Guid.Parse(UserId)))
                        {
                            _GoogleAnalyticsAccountRepository.Add(_GoogleAnalyticsAccount);
                        }
                        #region  TeamMemberProfile
                        Domain.Socioboard.Domain.Team objTeam = objTeamRepository.GetTeamByGroupId(Guid.Parse(GroupId));
                        if (!grpProfileRepo.checkProfileExistsingroup(Guid.Parse(GroupId), item.ProfileId))
                        {
                            //Domain.Socioboard.Domain.TeamMemberProfile objTeamMemberProfile = new Domain.Socioboard.Domain.TeamMemberProfile();
                            //objTeamMemberProfile.ProfileId = item.ProfileId;
                            //objTeamMemberProfile.ProfileName = item.ProfileName;
                            //objTeamMemberProfile.ProfilePicUrl = ConfigurationManager.AppSettings["DomainName"] + "/Themes/Socioboard/Contents/img/analytics_img.png";
                            //objTeamMemberProfile.ProfileType = "googleanalytics";
                            //objTeamMemberProfile.Status = 1;
                            //objTeamMemberProfile.StatusUpdateDate = DateTime.Now;
                            //objTeamMemberProfile.TeamId = objTeam.Id;
                            //objTeamMemberProfileRepository.addNewTeamMember(objTeamMemberProfile);


                            Domain.Socioboard.Domain.GroupProfile grpProfile = new Domain.Socioboard.Domain.GroupProfile();
                            grpProfile.Id = Guid.NewGuid();
                            grpProfile.EntryDate = DateTime.UtcNow;
                            grpProfile.GroupId = Guid.Parse(GroupId);
                            grpProfile.GroupOwnerId = Guid.Parse(UserId);
                            grpProfile.ProfileId = item.ProfileId;
                            grpProfile.ProfileType = "googleanalytics";
                            grpProfile.ProfileName = item.ProfileName;
                            grpProfile.ProfilePic = ConfigurationManager.AppSettings["DomainName"] + "/Themes/" + ConfigurationManager.AppSettings["DefaultGroupName"] + "/Contents/img/analytics_img.png";
                            grpProfileRepo.AddGroupProfile(grpProfile);
                        }
                        #endregion
                        #region SocialProfile
                        Domain.Socioboard.Domain.SocialProfile objSocialProfile = new Domain.Socioboard.Domain.SocialProfile();
                        objSocialProfile.ProfileType = "googleanalytics";
                        objSocialProfile.ProfileId = item.ProfileId;
                        objSocialProfile.UserId = Guid.Parse(UserId);
                        objSocialProfile.ProfileDate = DateTime.Now;
                        objSocialProfile.ProfileStatus = 1;
                        if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile))
                        {
                            objSocialProfilesRepository.addNewProfileForUser(objSocialProfile);
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logger.Error("AddAnalyticsProfiles = > " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("AddAnalyticsProfiles = > " + ex.Message);
            }
            return "added successfully";
        }