public void addGoogleAnalyticsUser(GoogleAnalyticsAccount gaaccount)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             session.Save(gaaccount);
             transaction.Commit();
         }
     }
 }
 /// <addGoogleAnalyticsUser>
 /// Add New Google Analytics User
 /// </summary>
 /// <param name="gaaccount">Set Values in a GoogleAnalyticsAccount Class Property and Pass the same Object of GoogleAnalyticsAccount Class.(Domain.GoogleAnalyticsAccount)</param>
 public void addGoogleAnalyticsUser(GoogleAnalyticsAccount gaaccount)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             //Proceed action, to save data.
             session.Save(gaaccount);
             transaction.Commit();
         }//End Transaction
     }//End Session
 }
        /// <updateGoogelAnalyticsUser>
        /// update Googel Analytics User Details
        /// </summary>
        /// <param name="gaaccount">Set Values in a GoogleAnalyticsAccount Class Property and Pass the same Object of GoogleAnalyticsAccount Class.(Domain.GoogleAnalyticsAccount)</param>
        public void updateGoogelAnalyticsUser(GoogleAnalyticsAccount gaaccount)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //Proceed action, to update google account deatils.
                        session.CreateQuery("Update GoogleAnalyticsAccount set GaAccountName =:gausername,GaProfileId=:gaprofileid,GaProfileName=:gaprofilename,AccessToken =:access,RefreshToken=:refreshtoken,EmailId=:emailid,IsActive=:status where GaAccountId = :gauserid and UserId = :userid")
                            .SetParameter("gausername", gaaccount.GaAccountName)
                            .SetParameter("gaprofilename",gaaccount.GaProfileName)
                            .SetParameter("gaprofileid",gaaccount.GaProfileId)
                            .SetParameter("access", gaaccount.AccessToken)
                            .SetParameter("refreshtoken",gaaccount.RefreshToken)
                            //.SetParameter("visits", gaaccount.Visits)
                            //.SetParameter("newvisits", gaaccount.NewVisits)
                            //.SetParameter("avgvisits", gaaccount.AvgVisits)
                            .SetParameter("emailid", gaaccount.EmailId)
                            .SetParameter("gauserid", gaaccount.GaAccountId)
                            .SetParameter("userid", gaaccount.UserId)
                            .SetParameter("status", gaaccount.IsActive)
                            .ExecuteUpdate();
                        transaction.Commit();


                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.StackTrace);
                        // return 0;
                    }
                }//End Transaction
            }//End Session
        }
        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);
                        
                    }
                }
            }
        }
 /// <getGoogelAnalyticsAccountHomeDetailsById>
 /// Get the Googel Analytics Account Home Details By Id and google account id.
 /// </summary>
 /// <param name="gauserid">Google account id (String)</param>
 /// <param name="userId">Id of user(Guid)</param>
 /// <returns>Return object of Google analytic class.(Domein.GoogleAnalyticsAccount)</returns>
 public GoogleAnalyticsAccount getGoogelAnalyticsAccountHomeDetailsById(Guid userId, string gauserid)
 {
     //Creates a database connection and opens up a session
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         //After Session creation, start Transaction.
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             try
             {
                 NHibernate.IQuery query = session.CreateQuery("from GoogleAnalyticsAccount where GaAccountId = :GaAccountId and UserId=:userId");
                 query.SetParameter("GaAccountId", gauserid);
                 query.SetParameter("userId", userId);
                 GoogleAnalyticsAccount result = new GoogleAnalyticsAccount();
                 foreach (GoogleAnalyticsAccount item in query.Enumerable<GoogleAnalyticsAccount>())
                 {
                     result = item;
                     break;
                 }
                 return result;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.StackTrace);
                 return null;
             }
         }//End Transaction
     }//End session
 }