Exemplo 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;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            oAuthTokenGa obj = new oAuthTokenGa();
            Accounts objAcc = new Accounts();
            Analytics objAlyt = new Analytics();
            User user = (User)Session["LoggedUser"];
            if (!IsPostBack)
            {
                if (Session["login"] == null)
                {
                    if (user == null)
                    { Response.Redirect("Default.aspx"); }
                }

                try
                {
                    string strRefresh = obj.GetRefreshToken(Request.QueryString["code"].ToString());
                    if (!strRefresh.StartsWith("["))
                        strRefresh = "[" + strRefresh + "]";
                    JArray objArray = JArray.Parse(strRefresh);
                    GoogleAnalyticsAccount objGaAcc = new GoogleAnalyticsAccount();
                    GoogleAnalyticsAccountRepository objGaAccRepo = new GoogleAnalyticsAccountRepository();
                    GanalyticsHelper objGaHelper=new GanalyticsHelper();
                    SocialProfilesRepository socioprofilerepo = new SocialProfilesRepository();
                    SocialProfile socioprofile = new SocialProfile();
                    foreach (var item in objArray)
                    {
                        DataSet dsAccount = objAcc.getGaAccounts(item["access_token"].ToString());
                        objGaAcc.RefreshToken = item["refresh_token"].ToString();
                        objGaAcc.AccessToken = item["access_token"].ToString();
                        objGaAcc.EmailId = dsAccount.Tables["title"].Rows[0]["title_Text"].ToString();
                        objGaAcc.EntryDate = DateTime.Now;
                        objGaAcc.GaAccountId = dsAccount.Tables["property"].Rows[0]["value"].ToString();
                        objGaAcc.GaAccountName = dsAccount.Tables["property"].Rows[1]["value"].ToString();
                        objGaAcc.Id = Guid.NewGuid();
                        objGaAcc.IsActive = true;
                        objGaAcc.UserId = user.Id;
                        DataSet dsProfile = objAcc.getGaProfiles(item["access_token"].ToString(), objGaAcc.GaAccountId);
                        int profileCount = dsProfile.Tables["property"].Select("name='ga:profileId'").Length;
                        string[,] names =new string[profileCount,2];
                       

                        int tempCount = 0;
                        foreach (DataRow dRow in dsProfile.Tables["property"].Rows)
                        {
                            //if (dRow["name"].Equals("ga:profileId") || dRow["name"].Equals("ga:profileName"))
                            {
                                if (dRow["name"].Equals("ga:profileId"))
                                {
                                    objGaAcc.GaProfileId = dRow["value"].ToString();
                                    names[tempCount, 0] = dRow["value"].ToString();
                                }
                                if (dRow["name"].Equals("ga:profileName"))
                                {
                                    names[tempCount, 1] = dRow["value"].ToString();
                                    objGaAcc.GaProfileName = dRow["value"].ToString();
                                }
                                if (tempCount>=profileCount)
                                {
                                    break;
                                }
                                if (names[tempCount, 0] != null && names[tempCount, 1] != null)
                                {
                                    tempCount++;
                                }
                                
                            }
                        }

                            socioprofile.Id = Guid.NewGuid();
                            socioprofile.ProfileDate = DateTime.Now;
                            socioprofile.ProfileId = objGaAcc.GaAccountId;
                            socioprofile.ProfileType = "googleanalytics";
                            socioprofile.UserId = user.Id;

                            if (!objGaAccRepo.checkGoogelAnalyticsUserExists(objGaAcc.GaAccountId, user.Id))
                            {
                                for (int i = 0; i < profileCount; i++)
                                {
                                    objGaAcc.GaProfileId = names[i,0];
                                    objGaAcc.GaProfileName = names[i,1];
                                    if(!objGaAccRepo.checkGoogelAnalyticsProfileExists(objGaAcc.GaAccountId,objGaAcc.GaProfileId,user.Id))
                                        objGaAccRepo.addGoogleAnalyticsUser(objGaAcc);
                                    else
                                        objGaAccRepo.updateGoogelAnalyticsUser(objGaAcc);


                                    objGaHelper.getCountryAnalyticsApi(objGaAcc.GaProfileId,user.Id);
                                    objGaHelper.getYearWiseAnalyticsApi(objGaAcc.GaProfileId, user.Id);
                                    objGaHelper.getMonthWiseAnalyticsApi(objGaAcc.GaProfileId, user.Id);
                                    objGaHelper.getDayWiseAnalyticsApi(objGaAcc.GaProfileId, user.Id);

                                }
                                
                                if (!socioprofilerepo.checkUserProfileExist(socioprofile))
                                {
                                    socioprofilerepo.addNewProfileForUser(socioprofile);
                                }
                                else
                                {
                                    socioprofilerepo.updateSocialProfile(socioprofile);
                                }
                            }
                            else
                            {
                                //objGaAccRepo.updateGoogelAnalyticsUser(objGaAcc);
                                 for (int i = 0; i < names.Length; i++)
                                {
                                    objGaAcc.GaProfileId = names[i,0];
                                    objGaAcc.GaProfileName = names[i,1];
                                    if(!objGaAccRepo.checkGoogelAnalyticsProfileExists(objGaAcc.GaAccountId,objGaAcc.GaProfileId,user.Id))
                                        objGaAccRepo.addGoogleAnalyticsUser(objGaAcc);
                                    else
                                        objGaAccRepo.updateGoogelAnalyticsUser(objGaAcc);
                                }
                                if (!socioprofilerepo.checkUserProfileExist(socioprofile))
                                {
                                    socioprofilerepo.addNewProfileForUser(socioprofile);
                                }
                                else
                                {
                                    socioprofilerepo.updateSocialProfile(socioprofile);
                                }
                            }
                        Response.Redirect("Home.aspx");
                    }
                }
                catch (Exception Err)
                {

                    logger.Error(Err.StackTrace);
                    try
                    {
                        Response.Redirect("/Home.aspx");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        
                    }
                }
            }
        }
        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";
        }