Ejemplo 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;
        }
Ejemplo n.º 2
0
 public void AuthenticateGoogleAnalytics(object sender, EventArgs e)
 {
     try
     {
         int profilecount = (int)Session["ProfileCount"];
         int totalaccount = (int)Session["TotalAccount"];
         if (profilecount < totalaccount)
         {
             oAuthTokenGa obj = new oAuthTokenGa();
             Response.Redirect(obj.GetAutherizationLinkGa("https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/analytics.readonly"));
         }
         else
         {
             Response.Write("<script>SimpleMessageAlert('Change the Plan to Add More Accounts');</script>");
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
     }
 }
        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 GetAnalyticsProfile(string code)
        {
            Domain.Socioboard.Helper.GoogleAnalyticsProfiles _GoogleAnalyticsProfiles;
            List<Domain.Socioboard.Helper.GoogleAnalyticsProfiles> lstGoogleAnalyticsProfiles = new List<Domain.Socioboard.Helper.GoogleAnalyticsProfiles>();
            string access_token = string.Empty;
            string refresh_token = string.Empty;
            Accounts _Accounts = new Accounts();

            try
            {
                oAuthTokenGa objToken = new oAuthTokenGa();
                objToken.ConsumerKey = ConfigurationManager.AppSettings["YtconsumerKey"];
                objToken.ConsumerSecret = ConfigurationManager.AppSettings["YtconsumerSecret"];
                objToken.RedirectUri = ConfigurationManager.AppSettings["Ytredirect_uri"];

                string accessToken = objToken.GetRefreshToken(code);
                JObject JData = JObject.Parse(accessToken);

                try
                {
                    refresh_token = JData["refresh_token"].ToString();
                }
                catch (Exception ex)
                {
                    access_token = JData["access_token"].ToString();
                    objToken.RevokeToken(access_token);
                    logger.Error("Refresh Token Not Found = > " + ex.Message);
                    return "Refresh Token Not Found";
                }

                access_token = JData["access_token"].ToString();

                string accountsdata = _Accounts.getGaAccounts(access_token);

                JObject JAccountdata = JObject.Parse(accountsdata);

                string EmailId = JAccountdata["username"].ToString();

                foreach (var item in JAccountdata["items"])
                {
                    try
                    {
                        string accountId = item["id"].ToString();
                        string accountName = item["name"].ToString();
                        string profileData = _Accounts.getGaProfiles(access_token, accountId);
                        JObject JProfileData = JObject.Parse(profileData);
                        foreach (var item_profile in JProfileData["items"])
                        {
                            try
                            {
                                _GoogleAnalyticsProfiles = new Domain.Socioboard.Helper.GoogleAnalyticsProfiles();
                                _GoogleAnalyticsProfiles.AccessToken = access_token;
                                _GoogleAnalyticsProfiles.RefreshToken = refresh_token;
                                _GoogleAnalyticsProfiles.AccountId = accountId;
                                _GoogleAnalyticsProfiles.AccountName = accountName;
                                _GoogleAnalyticsProfiles.EmailId = EmailId;
                                _GoogleAnalyticsProfiles.ProfileId = item_profile["id"].ToString();
                                _GoogleAnalyticsProfiles.ProfileName = item_profile["name"].ToString();
                                _GoogleAnalyticsProfiles.WebPropertyId = item_profile["webPropertyId"].ToString();
                                _GoogleAnalyticsProfiles.WebsiteUrl = item_profile["websiteUrl"].ToString();
                                lstGoogleAnalyticsProfiles.Add(_GoogleAnalyticsProfiles);
                            }
                            catch (Exception ex)
                            {

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

            return new JavaScriptSerializer().Serialize(lstGoogleAnalyticsProfiles);

        }
        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 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";
        }