예제 #1
0
        private void SetupPageFriendMode()
        {
            atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_LIST;
            WebService.StreamService streamService = new WebService.StreamService();
            UserSettings             settings      = ProfileSettings != null ? ProfileSettings : UserSettings;

            if (settings is Group)
            {
                if (this.UserSettings.Id != settings.Id)
                {
                    atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_REQUEST;
                }
                tabFollowing.Visible = pageViewFollowing.Visible = false;
                tabFollowers.Visible = pageViewFollowers.Visible = false;
                string json = streamService.getMemberListData(settings.Id, 0, 25, this.UserSettings.Id);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FriendList", "$(function(){ Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); });", true);
            }
            else
            {
                if (this.UserSettings.Id != settings.Id)
                {
                    atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_REQUEST;
                }
                string json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, 0, 25, this.UserSettings.Id);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FriendList", "$(function(){ Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); });", true);
            }
        }
        protected void atiFollow_Click(object sender, EventArgs e)
        {
            try
            {
                Affine.WebService.StreamService ss = new WebService.StreamService();
                if (base.Following) // this is an unfollow then
                {
                    ss.UnFollowUser(this.UserId, this.PortalId, this.ProfileSettings.UserKey);
                    litStatus.Text = "You are <em>No longer following " + this.ProfileSettings.UserName + "</em>";
                    base.Following = false;
                }
                else  // we want to follow this user
                {
                    ss.FollowUser(this.UserId, this.PortalId, this.ProfileSettings.UserKey);
                    litStatus.Text = "You are now <em>following " + this.ProfileSettings.UserName + "</em>";
                    base.Following = true;
                }
                atiFollow.Text = base.Following ? "Unfollow " : "Follow " + ProfileSettings.UserName;

            }
            catch (Exception)
            {
                litStatus.Text = "There was an <em>Error</em> with the operation.  Please contact support.";
            }
        }
예제 #3
0
 protected void atiAddRemFav_Click(object sender, ImageClickEventArgs e)
 {
     if (this.UserId > 0)
     {   // Is this user Loged in ?
         aqufitEntities       entities = new aqufitEntities();
         User2StreamFavorites rFav     = entities.User2StreamFavorites.FirstOrDefault(f => f.UserKey == this.UserId && f.PortalKey == this.PortalId && f.UserStream.Id == this.RecipeId);
         if (rFav == null)
         {
             Affine.WebService.StreamService service = new WebService.StreamService();
             string ret = service.addStreamToFavorites(this.UserId, this.PortalId, this.RecipeId);
             if (!ret.Contains("success"))
             {
                 litStatus.Text = ret;
             }
             else
             {
                 litStatus.Text = "SUCCESS. Recipe has been added to your favorites.";
             }
         }
         else
         {
             entities.DeleteObject(rFav);
             entities.SaveChanges();
             litStatus.Text = "Boom. Recipe has been removed from your favorites.";
         }
         RadAjaxManager1.ResponseScripts.Add("$('#atiFavContainer').fadeOut('slow');");
     }
     else
     {  // otherwise jump to a login
         RadAjaxManager1.ResponseScripts.Add("self.location.href= Aqufit.Page.LoginUrl + \"?ReturnUrl=\" + self.location.href;");
     }
 }
예제 #4
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                base.Page_Load(sender, e);
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    int numEntries = 3;
                    if (Settings["NumEntries"] != null)
                    {
                        numEntries = Convert.ToInt32(Settings["NumEntries"]);
                    }
                    Affine.WebService.StreamService streamService = new WebService.StreamService();
                    string json = streamService.getRecentWorkouts(this.PortalId, 0, numEntries);
                    ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #5
0
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            string status = string.Empty;

            try
            {
                Affine.Data.Managers.IDataManager dataManager   = Affine.Data.Managers.LINQ.DataManager.Instance;
                Affine.WebService.StreamService   streamService = new WebService.StreamService();
                int    skip = 0;
                int    take = 0;
                string json = string.Empty;
                switch (hiddenAjaxAction.Value)
                {
                case "friendRequest":
                    long fid = Convert.ToInt64(hiddenAjaxValue.Value);
                    dataManager.sendFriendRequest(UserSettings.Id, fid);
                    status = "Friend request has been sent.";
                    break;

                case "friendListDataPage":
                    skip = Convert.ToInt32(hiddenAjaxValue.Value);
                    take = Convert.ToInt32(hiddenAjaxValue2.Value);
                    if (ProfileSettings is Group)
                    {
                        json = streamService.getMemberListData(ProfileSettings.Id, skip, take, this.UserSettings.Id);
                    }
                    else
                    {
                        json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, skip, take, this.UserSettings.Id);
                    }
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); ");
                    break;

                case "followingListDataPage":
                    skip = Convert.ToInt32(hiddenAjaxValue.Value);
                    take = Convert.ToInt32(hiddenAjaxValue2.Value);
                    json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWING, skip, take);
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFollowingList.generateStreamDom('" + json + "'); ");
                    break;

                case "followerListDataPage":
                    skip = Convert.ToInt32(hiddenAjaxValue.Value);
                    take = Convert.ToInt32(hiddenAjaxValue2.Value);
                    json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWERS, skip, take);
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFollowerList.generateStreamDom('" + json + "'); ");
                    break;
                }
            }
            catch (Exception ex)
            {
                status = "ERROR: There was a problem with the action (" + ex.Message + ")";
            }
            RadAjaxManager1.ResponseScripts.Add("UpdateStatus('" + status + "'); ");
        }
예제 #6
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?u=-1&p=0&bg=1";
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    aqufitEntities   entities = new aqufitEntities();
                    ServiceReference service  = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    if (GroupSettings != null || (UserSettings != null && UserSettings.MainGroupKey.HasValue))
                    {
                        tabMyGroupComps.Visible  = true;
                        pageMyGroupComps.Visible = true;
                        //  if (GroupSettings != null)
                        //   {
                        //         RadAjaxManager1.ResponseScripts.Add("Aqufit.addLoadEvent(function(){ Aqufit.Page.Tabs.SwitchTab(1); });");
                        //       }
                    }

                    Group taranis = entities.UserSettings.OfType <Group>().FirstOrDefault(g => g.Id == 511);;
                    atiFGProfileImg.Settings = taranis;
                    hrefGroupLink2.HRef      = baseUrl + "group/" + taranis.UserName;
                    imgSearch.Src            = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    if (GroupSettings == null)
                    {       // Let people search for a group in this case..
                        atiGroupListPanel.Visible = true;

                        if (this.UserSettings != null && (this.UserSettings.LatHome != null && this.UserSettings.LatHome.Value > 0.0))
                        {
                            atiGMap.Lat  = this.UserSettings.LatHome.Value;
                            atiGMap.Lng  = this.UserSettings.LngHome.Value;
                            atiGMap.Zoom = 13;
                        }
                        imgAd.Src = ResolveUrl("~/portals/0/images/adTastyPaleo.jpg");
                        WebService.StreamService streamService = new WebService.StreamService();
                        // string search = streamService.searchGroupListData(PortalId, null, 0, 15);

                        // we need to setup for a location based group search
                        // ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupSearch", "$(function(){ Aqufit.Page.atiGroupSearch.generateStreamDom('" + search + "'); });", true);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #7
0
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            try
            {
                Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                Affine.WebService.StreamService   ss      = new WebService.StreamService();
                long mid = 0;
                long gid = Convert.ToInt64(hiddenGroupKey.Value);;
                switch (hiddenAjaxAction.Value)
                {
                case "makeAdmin":
                    mid = Convert.ToInt64(hiddenAjaxValue.Value);
                    dataMan.makeMemberGroupAdmin(UserSettings.Id, gid, mid);
                    string json = ss.getMemberListDataOfRelationship(gid, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "'); ");
                    break;

                case "removeAdmin":
                    mid = Convert.ToInt64(hiddenAjaxValue.Value);
                    dataMan.removeMemberGroupAdmin(UserSettings.Id, gid, mid);
                    string json2 = ss.getMemberListDataOfRelationship(gid, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "'); ");
                    break;

                case "removeMember":
                    mid = Convert.ToInt64(hiddenAjaxValue.Value);
                    dataMan.removeMemberGroup(UserSettings.Id, gid, mid);
                    break;

                case "sendGroupInvite":
                    long usid = Convert.ToInt64(hiddenAjaxValue.Value);
                    dataMan.inviteUserToGroup(usid, gid);
                    break;

                case "friendData":
                    int skip = Convert.ToInt32(hiddenAjaxValue.Value);
                    int take = Convert.ToInt32(hiddenAjaxValue2.Value);
                    json = ss.getFriendListData(UserSettings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, skip, take, gid);
                    RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFriendList.generateStreamDom('" + json + "'); Aqufit.Page.atiLoading.remove(); ");
                    break;
                }
            }
            catch (Exception ex)
            {
                RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog('" + ex.Message.Replace("'", "") + "'); ");
            }
        }
 protected void bSend_Click(object sender, EventArgs e)
 {
     try
     {
         Affine.WebService.StreamService service = new WebService.StreamService();
         service.SendMessage(UserSettings.Id, atiSendMessage.To.ToArray(), atiSendMessage.Subject, atiSendMessage.Message);
         litStatus.Text = "Your message has been sent.";
         atiSendMessage.Visible = false;
         bSend.Visible = false;
         bClose.Visible = true;
     }
     catch (Exception ex)
     {
         RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiSendMessage.refresh();");
         litStatus.Text = "ERROR: There was a problem sending your message. " + ex.Message;
     }
 }
 protected void bSend_Click(object sender, EventArgs e)
 {
     try
     {
         Affine.WebService.StreamService service = new WebService.StreamService();
         service.SendMessage(UserSettings.Id, atiSendMessage.To.ToArray(), atiSendMessage.Subject, atiSendMessage.Message);
         litStatus.Text         = "Your message has been sent.";
         atiSendMessage.Visible = false;
         bSend.Visible          = false;
         bClose.Visible         = true;
     }
     catch (Exception ex)
     {
         RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiSendMessage.refresh();");
         litStatus.Text = "ERROR: There was a problem sending your message. " + ex.Message;
     }
 }
예제 #10
0
        private void SetupFeaturedGroups()
        {
            aqufitEntities entities = new aqufitEntities();
            // CA - We have encoded the number of members in a Groups::MainGroupKey ... this is an easy way to pick out featured groups..
            IQueryable<Group> featureQuery = entities.UserSettings.OfType<Group>().Include("Image").Include("Places").Where(g => g.MainGroupKey > 10 );
            int gcount = featureQuery.Count();
            int skip = new Random().Next(gcount-1);
            Group feature = featureQuery.OrderBy( g => g.Id ).Skip(skip).First();
            atiFGProfileImg.Settings = feature;
            hrefGroupName.HRef  = hrefGroupLink2.HRef = ResolveUrl("~/") + "Group/" + feature.UserName;
            hrefGroupName.InnerHtml = feature.UserFirstName;

            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
            Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(feature.Id);
            System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
            RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");

            // TODO: cache this grabbing of the friend ids from the stream service
            long[] friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == feature.Id || f.DestUserSettingKey == feature.Id) && (f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER)).Select(f => (f.SrcUserSettingKey == feature.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray();
            IQueryable<Affine.Data.User> friends = entities.UserSettings.OfType<User>().Where(Affine.Utils.Linq.LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).OrderBy(s => s.Id);
            int fcount = friends.Count();
            UserSettings[] firendSettings = null;
            if (fcount > 6)
            {
                Random rand = new Random((int)DateTime.Now.Millisecond);
                skip = rand.Next(fcount - 6);
                firendSettings = friends.Skip(skip).Take(6).ToArray();
            }
            else
            {
                firendSettings = friends.Take(6).ToArray();
            }            
            atiFriendsPhotos.FriendKeyList = firendSettings;
            atiFriendsPhotos.User = feature;
            atiFriendsPhotos.FriendCount = fcount;
            atiFriendsPhotos.FriendListLink = ResolveUrl("~/") + feature.UserName + "/Friends";

            if( feature.Places.Count > 0 ){
                Place place = feature.Places.FirstOrDefault();
                litGroupDescription.Text += "<span>" + place.Street + "<br />"+place.City+", "+place.Region+", "+place.Country+"</span>";
                litGroupDescription.Text += "<span>"+place.Description+"</span>";
            }            
            WebService.StreamService streamService = new WebService.StreamService();            
            string json = streamService.getActiveGroups(0, 10);
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "Groups", "$(function(){ Aqufit.Page.atiGroupList.generateStreamDom('" + json + "'); });", true);                        
        }
예제 #11
0
 protected void bSubmitComment_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         string status = string.Empty;
         try
         {
             Affine.WebService.StreamService service = new WebService.StreamService();
             RadAjaxManager1.ResponseScripts.Add(" (function(){ Aqufit.Page.atiStreamScript.prependJson('" + service.SaveStreamShout(this.GroupSettings.Id, this.UserId, this.PortalId, atiComment.Comment) + "'); })();");
             status = "Your comment has been saved.";
         }
         catch (Exception ex)
         {
             status = "ERROR: problem saving comment (" + ex.Message + ")";
         }
         RadAjaxManager1.ResponseScripts.Add("UpdateStatus('" + status + "'); ");
     }
 }
예제 #12
0
        private void SetupPageFollowMode()
        {
            WebService.StreamService streamService = new WebService.StreamService();
            if (Request["c"] != null)
            {
                streamService.FollowUser(this.UserSettings.Id, Convert.ToInt64(Request["c"]));
            }
            UserSettings settings = ProfileSettings != null ? ProfileSettings : UserSettings;

            if (!(settings is Group))
            {
                string json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWING, 0, 25);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FollowingList", "$(function(){ Aqufit.Page.atiFollowingList.generateStreamDom('" + json + "'); });", true);

                json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWERS, 0, 25);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FollowerList", "$(function(){ Aqufit.Page.atiFollowerList.generateStreamDom('" + json + "'); });", true);
            }
        }
예제 #13
0
        private void SetupPage()
        {
            // center USA if we dont have anything to go on
            // double Lat = 39.6395;
            // double Lng = -95.4492;
            // short Zoom = 4;
            double Lat  = 49.2844;
            double Lng  = -123.1258;
            short  Zoom = 10;

            if (UserSettings != null && UserSettings.LatHome.HasValue && UserSettings.LngHome.HasValue)
            {
                Lat  = UserSettings.LatHome.Value;
                Lng  = UserSettings.LngHome.Value;
                Zoom = 10;
            }
            atiGMap.Lat  = Lat;
            atiGMap.Lng  = Lng;
            atiGMap.Zoom = Zoom;

            /*
             * if (!string.IsNullOrEmpty(hiddenLat.Value))
             * {
             *  atiGMap.Lat = Convert.ToDouble(hiddenLat.Value);
             * }
             * if (!string.IsNullOrEmpty(hiddenLng.Value))
             * {
             *  atiGMap.Lng = Convert.ToDouble(hiddenLng.Value);
             * }
             * if (!string.IsNullOrEmpty(hiddenZoom.Value))
             * {
             *  atiGMap.Zoom = Convert.ToInt16(hiddenZoom.Value);
             * }
             */
            hiddenLat.Value  = "" + Lat;
            hiddenLng.Value  = "" + Lng;
            hiddenZoom.Value = "" + Zoom;
            WebService.StreamService streamService = new WebService.StreamService();
            string json = streamService.GetRoutes(Lat, Lng, 5.0, 0, 10, "date");

            ScriptManager.RegisterStartupScript(this, Page.GetType(), "RouteList", "$(function(){ Aqufit.Page.atiRouteListScript.generateStreamDom('" + json + "'); });", true);
        }
예제 #14
0
 protected void atiFollow_Click(object sender, EventArgs e)
 {
     try
     {
         Affine.WebService.StreamService ss = new WebService.StreamService();
         if (base.Following) // this is an unfollow then
         {
             ss.UnFollowUser(this.UserId, this.PortalId, this.ProfileSettings.UserKey);
             litStatus.Text = "You are <em>No longer following " + this.ProfileSettings.UserName + "</em>";
             base.Following = false;
         }
         else  // we want to follow this user
         {
             ss.FollowUser(this.UserId, this.PortalId, this.ProfileSettings.UserKey);
             litStatus.Text = "You are now <em>following " + this.ProfileSettings.UserName + "</em>";
             base.Following = true;
         }
         atiFollow.Text = base.Following ? "Unfollow " : "Follow " + ProfileSettings.UserName;
     }
     catch (Exception)
     {
         litStatus.Text = "There was an <em>Error</em> with the operation.  Please contact support.";
     }
 }
예제 #15
0
        private void SetupStreams()
        {
            // We need to get all the different types of requests that belong to the user.
            // - Once we have all the request.  Divide them up into categories by object type.
            // - Display each type using the Request List control.
            WebService.StreamService            streamService = new WebService.StreamService();
            Affine.Data.Managers.IStreamManager streamMan     = Affine.Data.Managers.LINQ.StreamManager.Instance;
            Affine.Data.json.UserSetting[]      freindRequest = streamMan.GetFriendRequests(this.UserSettings.Id);
            Affine.Data.json.UserSetting[]      groupInvite   = streamMan.GetGroupInviteRequests(this.UserSettings.Id);
            string json  = streamMan.ToJsonWithPager(freindRequest);
            string json2 = streamService.getNotifications(UserSettings.Id, 0, 50);
            string js    = string.Empty;

            if (Request["n"] != null)
            {
                aqufitEntities entities     = new aqufitEntities();
                long           nid          = Convert.ToInt64(Request["n"]);
                Notification   notification = entities.UserStreamSet.OfType <Notification>().FirstOrDefault(n => n.Id == nid);
                if (notification != null)
                {
                    notification.PublishSettings = (int)Affine.Utils.ConstsUtil.PublishSettings.NOTIFICATION_READ;  // this will take it out of the top menu since the user clicked to deal with it..
                    entities.SaveChanges();
                    js += "var $sel = $('#atiStreamItem" + Request["n"] + "');";
                    js += "var targetOffset = $sel.offset().top; ";
                    js += "$sel.css('background-color','#ffcc99').css('border', '2px solid #e47526'); ";
                    js += "$('html,body').animate({scrollTop: targetOffset}, 500);";
                }
            }
            if (groupInvite.Length > 0)
            {
                atiGroupJoinRequest.Visible = true;
                string json3 = streamMan.ToJsonWithPager(groupInvite);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupInviteList", "$(function(){ Aqufit.Page.atiGroupJoinRequest.generateStreamDom('" + json3 + "'); });", true);
            }
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "NotificationList", "$(function(){ Aqufit.Page.atiFriendRequestScript.generateStreamDom('" + json + "'); Aqufit.Page.atiStreamScript.generateStreamDom('" + json2 + "'); " + js + " });", true);
        }
예제 #16
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src         = ResolveUrl("~/images/iphoneAd.png");
                imgCheck.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png");

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgSearch.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    imgCenter.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCenter.png");
                    aqufitEntities entities = new aqufitEntities();
                    long           rId      = 0;
                    if (HttpContext.Current.Items["r"] != null)
                    {
                        rId = Convert.ToInt64(HttpContext.Current.Items["r"]);
                    }
                    else if (Request["r"] != null)
                    {
                        rId = Convert.ToInt64(Request["r"]);
                    }
                    else if (HttpContext.Current.Items["w"] != null)
                    {
                        long workoutId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        rId = entities.UserStreamSet.OfType <Workout>().Where(w => w.Id == workoutId).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    }
                    else if (Request["w"] != null)
                    {
                        long workoutId = Convert.ToInt64(Request["w"]);
                        rId = entities.UserStreamSet.OfType <Workout>().Where(w => w.Id == workoutId).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    }
                    // Are we viewing a specific route ?
                    if (rId > 0)
                    {
                        hiddenRouteKey.Value = "" + rId;

                        MapRoute route = entities.MapRoutes.Include("UserSetting").Include("MapRoutePoints").FirstOrDefault(m => m.Id == rId);
                        if (base.UserSettings != null)
                        {
                            bAddRoute.Visible = entities.User2MapRouteFav.FirstOrDefault(mr => mr.MapRoute.Id == route.Id && mr.UserSettingsKey == UserSettings.Id) == null;
                        }
                        Affine.Utils.UnitsUtil.MeasureUnit unit = this.UserSettings != null && this.UserSettings.DistanceUnits != null?Affine.Utils.UnitsUtil.ToUnit(this.UserSettings.DistanceUnits.Value) : Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES;

                        string dist = Math.Round(Affine.Utils.UnitsUtil.systemDefaultToUnits(route.RouteDistance, unit), 2) + " " + Affine.Utils.UnitsUtil.unitToStringName(unit);
                        lRouteTitle.Text = route.Name + " (" + dist + ")";
                        lRouteInfo.Text  = "<span>A " + dist + " route posted by <a class=\"username\" href=\"/" + route.UserSetting.UserName + "\">" + route.UserSetting.UserName + "</a> on " + route.CreationDate.ToShortDateString() + "</span>";
                        double centerLat = (route.LatMax + route.LatMin) / 2;
                        double centerLng = (route.LngMax + route.LngMin) / 2;
                        atiGMapView.Lat = centerLat;
                        atiGMapView.Lng = centerLng;
                        if (route.ThumbZoom.HasValue)
                        {
                            atiGMapView.Zoom = (short)(route.ThumbZoom.Value + 2);
                        }
                        atiGMapView.Route      = route;
                        atiProfileImg.Settings = route.UserSetting;
                        atiRoutePanel.Visible  = false;
                        atiRouteViewer.Visible = true;

                        string js = string.Empty;

                        //js += "Affine.WebService.StreamService.GetRoutes(" + centerLat + ", " + centerLng + ", 10, 0, 5, 'distance', function (json) { ";
                        js += "Aqufit.Page.atiSimilarRouteListScript.dataBinder = function(skip, take){ \n";
                        js += "     Affine.WebService.StreamService.GetSimilarRoutes(" + rId + ", 10, skip, take, 'distance', function (json) { \n";
                        js += "         Aqufit.Page.atiSimilarRouteListScript.generateStreamDom(json); \n";
                        js += "     }); \n";
                        js += "};";
                        js += " Aqufit.Page.atiSimilarRouteListScript.dataBinder(0,5); ";
                        atiShareLink.ShareLink  = "http://" + Request.Url.Host + "/route/" + route.Id;
                        atiShareLink.ShareTitle = "FlexFWD.com Mapped Route: \"" + route.Name + "\"";

                        routeTabTitle.Text = "&nbsp;" + (string.IsNullOrWhiteSpace(route.Name) ? "Untitled" : route.Name);

                        Affine.WebService.StreamService ss = new WebService.StreamService();
                        string json = ss.getStreamDataForRoute(route.Id, 0, 5);
                        //generateStreamDom

                        ScriptManager.RegisterStartupScript(this, Page.GetType(), "SimilarRouteList", "$(function(){ " + js + " Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);
                    }
                    else
                    {
                        if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureMyRoutes"))
                        {
                            atiMyRoutePanel.Visible = true;
                            mapContainer.Visible    = false;
                            atiRoutePanel.Visible   = true;
                            routeTabTitle.Text      = "My Routes";
                            liMyRoutes.Visible      = false;
                            liFindRoute.Visible     = true;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetMyRoutes(base.UserSettings.Id, 0, 10, "date");
                            string js   = string.Empty;
                            //js += "Affine.WebService.StreamService.GetRoutes(" + centerLat + ", " + centerLng + ", 10, 0, 5, 'distance', function (json) { ";
                            js += "$(function(){ Aqufit.Page.atiRouteListScript.isMyRoutes = true; Aqufit.Page.atiRouteListScript.generateStreamDom('" + json + "'); \n";
                            js += "     Aqufit.Page.atiRouteListScript.dataBinder = function(skip, take){ \n";
                            js += "         Affine.WebService.StreamService.GetMyRoutes(" + base.UserSettings.Id + ", skip, take, 'date', function (json) { \n";
                            js += "             Aqufit.Page.atiRouteListScript.generateStreamDom(json); \n";
                            js += "         }); \n";
                            js += "     } \n";
                            js += " }); \n";

                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "RouteList", js, true);
                        }
                        else
                        {
                            routeTabTitle.Text     = "Routes";
                            atiRoutePanel.Visible  = true;
                            atiRouteViewer.Visible = false;
                            SetupPage();        // do normal page setup
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #17
0
 protected void bSubmitComment_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         string status = string.Empty;
         try
         {
             Affine.WebService.StreamService service = new WebService.StreamService();
             RadAjaxManager1.ResponseScripts.Add(" (function(){ Aqufit.Page.atiStreamScript.prependJson('" + service.SaveStreamShout(this.GroupSettings.Id, this.UserId, this.PortalId, atiComment.Comment) + "'); })();");
             status = "Your comment has been saved.";
         }
         catch (Exception ex)
         {
             status = "ERROR: problem saving comment (" + ex.Message + ")";
         }
         RadAjaxManager1.ResponseScripts.Add("UpdateStatus('" + status + "'); ");
     }
 }
예제 #18
0
        private void UpdateGroup()
        {
            if (Page.IsValid)
            {
                try
                {
                    // check required fields
                    aqufitEntities entities = new aqufitEntities();
                    Group          group    = entities.UserSettings.OfType <Group>().Include("GroupType").Include("UserSettingsExtendeds").Include("Places").FirstOrDefault(g => g.Id == GroupSettings.Id);

                    group.UserEmail     = atiTxtGroupEmail.Text;
                    group.UserFirstName = txtGroupName.Text;
                    Place place = group.Places.FirstOrDefault();
                    if (place != null)
                    {
                        place.Description = atTxtGroupDescription.Text;
                    }
                    int gtype = Convert.ToInt32(ddlGroupType.SelectedValue);

                    group.GroupType = entities.GroupTypes.FirstOrDefault(gt => gt.Id == gtype);

                    long followId = 0;
                    if (!string.IsNullOrWhiteSpace(atiRadComboBoxSearchGroups.SelectedValue))
                    {
                        followId = Convert.ToInt64(atiRadComboBoxSearchGroups.SelectedValue);
                    }
                    // first check if the group is following any other group;
                    UserFriends follow = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == group.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW);
                    if (follow != null)
                    {
                        // make sure it is a valid group ..
                        Group test = entities.UserSettings.OfType <Group>().FirstOrDefault(g => g.Id == followId);
                        // just update the follow refrence ...
                        if (test != null)
                        {
                            follow.DestUserSettingKey = followId;
                        }
                    }
                    else
                    {
                        // make sure it is a valid group ..
                        Group test = entities.UserSettings.OfType <Group>().FirstOrDefault(g => g.Id == followId);
                        // just update the follow refrence ...
                        if (test != null)
                        {
                            UserFriends followGroup = new UserFriends()
                            {
                                SrcUserSettingKey  = group.Id,
                                DestUserSettingKey = test.Id,
                                Relationship       = (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW
                            };
                            entities.AddToUserFriends(followGroup);
                        }
                    }


                    #region WebLinks settings
                    UserSettingsExtended[] webLinks = group.UserSettingsExtendeds.Where(s => s.Class == 1).ToArray();
                    if (atiWebLinks.Visible)
                    {
                        // Facebook
                        UserSettingsExtended facebook = webLinks.FirstOrDefault(s => s.Name == "Facebook");
                        if (!string.IsNullOrEmpty(atiWebLinks.Facebook))
                        {
                            if (facebook == null)
                            {
                                facebook = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "Facebook",
                                    Value = atiWebLinks.Facebook
                                };
                                group.UserSettingsExtendeds.Add(facebook);
                            }
                            else
                            {
                                facebook.Value = atiWebLinks.Facebook;
                            }
                        }
                        else if (facebook != null)
                        {
                            entities.DeleteObject(facebook);
                        }

                        // Twitter
                        UserSettingsExtended twitter = webLinks.FirstOrDefault(s => s.Name == "Twitter");
                        if (!string.IsNullOrEmpty(atiWebLinks.Twitter))
                        {
                            if (twitter == null)
                            {
                                twitter = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "Twitter",
                                    Value = atiWebLinks.Twitter
                                };
                                group.UserSettingsExtendeds.Add(twitter);
                            }
                            else
                            {
                                twitter.Value = atiWebLinks.Twitter;
                            }
                        }
                        else if (twitter != null)
                        {
                            entities.DeleteObject(twitter);
                        }

                        // YouTube
                        UserSettingsExtended youtube = webLinks.FirstOrDefault(s => s.Name == "YouTube");
                        if (!string.IsNullOrEmpty(atiWebLinks.YouTube))
                        {
                            if (youtube == null)
                            {
                                youtube = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "YouTube",
                                    Value = atiWebLinks.YouTube
                                };
                                group.UserSettingsExtendeds.Add(youtube);
                            }
                            else
                            {
                                youtube.Value = atiWebLinks.YouTube;
                            }
                        }
                        else if (youtube != null)
                        {
                            entities.DeleteObject(youtube);
                        }

                        // LinkedIn
                        UserSettingsExtended linkedin = webLinks.FirstOrDefault(s => s.Name == "LinkedIn");
                        if (!string.IsNullOrEmpty(atiWebLinks.LinkedIn))
                        {
                            if (linkedin == null)
                            {
                                linkedin = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "LinkedIn",
                                    Value = atiWebLinks.LinkedIn
                                };
                                group.UserSettingsExtendeds.Add(linkedin);
                            }
                            else
                            {
                                linkedin.Value = atiWebLinks.LinkedIn;
                            }
                        }
                        else if (linkedin != null)
                        {
                            entities.DeleteObject(linkedin);
                        }

                        // Flickr
                        UserSettingsExtended flickr = webLinks.FirstOrDefault(s => s.Name == "Flickr");
                        if (!string.IsNullOrEmpty(atiWebLinks.Flickr))
                        {
                            if (flickr == null)
                            {
                                flickr = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "Flickr",
                                    Value = atiWebLinks.Flickr
                                };
                                group.UserSettingsExtendeds.Add(flickr);
                            }
                            else
                            {
                                flickr.Value = atiWebLinks.Flickr;
                            }
                        }
                        else if (flickr != null)
                        {
                            entities.DeleteObject(flickr);
                        }

                        // Personal
                        UserSettingsExtended personal = webLinks.FirstOrDefault(s => s.Name == "Personal");
                        if (!string.IsNullOrEmpty(atiWebLinks.Peronsal))
                        {
                            if (personal == null)
                            {
                                personal = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name  = "Personal",
                                    Value = atiWebLinks.Peronsal
                                };
                                group.UserSettingsExtendeds.Add(personal);
                            }
                            else
                            {
                                personal.Value = atiWebLinks.Peronsal;
                            }
                        }
                        else if (personal != null)
                        {
                            entities.DeleteObject(personal);
                        }
                    }
                    #endregion

                    UploadThemeBackground();
                    group.CssStyle = string.Empty;

                    if (!atiThemeEditor.BackgroundColor.IsEmpty)
                    {
                        group.CssStyle += "background-color: #" + atiThemeEditor.BackgroundColor.Name.Substring(2) + ";";
                    }
                    if (atiThemeEditor.IsTiled)
                    {
                        group.CssStyle += "background-repeat: repeat;";
                    }
                    else
                    {
                        group.CssStyle += "background-repeat:no-repeat; background-attachment:fixed;";
                    }
                    this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?u=" + group.UserKey + "&p=" + group.PortalKey + "&bg=1";
                    this.ProfileCSS         = group.CssStyle;

                    entities.SaveChanges();


                    // Next the member list
                    Affine.WebService.StreamService ss = new WebService.StreamService();
                    string json  = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);
                    string json2 = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);
                    RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "');  Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "');  }); ");
                }
                catch (Exception ex)
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"" + ex.Message.Replace("'", "") + "\"}');");
                }
            }
            else
            {
                RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"\"}');");
            }
        }
예제 #19
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                base.Page_Load(sender, e);
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    int numEntries = 3;
                    if (Settings["NumEntries"] != null)
                    {
                        numEntries = Convert.ToInt32(Settings["NumEntries"]);
                    }
                    Affine.WebService.StreamService streamService = new WebService.StreamService();
                    string json = streamService.getRecentWorkouts(this.PortalId, 0, numEntries);
                    ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // CA - this will need to be cleaned up a lot.. but here is the iteration one version
        // ** People can view workouts in 4 modes (everyone, watchlist, friends, just them)
        //     -In the case of running, cycling, swimming, and STANDARD crossfit Wods... we are going to
        //      be storing peoples best times for (distance rnages) and standard wods... so in these cases
        //      we can shorted the query time when we do an "everyone" query
        //     -Watch list and friends we do the work of getting every time that person did the workout.. not just
        //      there best times.
        //     -Same for the (you only) view
        //        
        private void LoadFlexDataForWorkout(Workout workout, Affine.Utils.ConstsUtil.GraphContext context)
        {
            Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            // onload we send friend, watch, and group member data that is needed to the app
            aqufitEntities entities = new aqufitEntities();
            IList<long> friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id)).Select(f => (f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList();
            friendIds.Add(ProfileSettings.Id);

            // send the persons profile through
            var profile = new { UserName = ProfileSettings.UserName, Id = ProfileSettings.Id, FirstName = ProfileSettings.UserFirstName, LastName= ProfileSettings.UserLastName };
            hiddenProfileJson.Value = serializer.Serialize(profile);

            var friends = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).Select(u => new { Id = u.Id, Un = u.UserName, Fn = u.UserFirstName, Ln = u.UserLastName }).ToArray();
            hiddenFriendJson.Value = serializer.Serialize(friends);
            // get groups
            long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id) && f.Relationship > 0).Select(f => f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            UserSettings[] groupList = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<UserSettings, long>(us => us.Id, groupIds)).OrderBy(f => f.UserName).ToArray();
            var groups = entities.UserSettings.OfType<Group>().Where(LinqUtils.BuildContainsExpression<Group, long>(s => s.Id, groupIds)).Select(u => new { Id = u.Id, Un = u.UserName }).ToArray();
            hiddenGroupJson.Value = serializer.Serialize(groups);
            // next we load the workout compare to all (friends)

            Affine.WebService.StreamService ss = new WebService.StreamService();

            //hiddenWorkout.Value = ss.getWorkout(workout.Id);
            Affine.Data.json.Workout jsonWorkout = dataManager.workoutToJsonWorkout(workout);
            Affine.Data.json.WOD wod = null;
            Affine.Data.json.WorkoutData[] jsonWorkoutData = null;
            //var workoutJson = new { Id = workout.Id, WorkoutTypeKey = workout.WorkoutTypeKey, Title = workout.Title, Date = workout.Date.ToLocalTime().ToShortDateString(), DataSrc = workout.DataSrc };

            Affine.Utils.UnitsUtil.MeasureUnit weight = base.WeightUnits;
            if (workout.WorkoutTypeKey == (int)Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT)
            {
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {   // default context for crossfit is the watchlist
                    context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                }
                // if this is a crossfit workout
                // we want to get ALL the same WoDs for you and your friends
                IQueryable<Workout> workoutDataQuery = context == Utils.ConstsUtil.GraphContext.EVERYONE ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).AsQueryable()
                                    :
                                    context == Utils.ConstsUtil.GraphContext.WATCHLIST ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                    context == Utils.ConstsUtil.GraphContext.FRIENDS ?
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression<Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                    entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WOD.Id == workout.WOD.Id && w.UserSetting.Id == ProfileSettings.Id ).AsQueryable();
                var workoutData = workoutDataQuery.Select(w => new { Id = w.Id, UsKey = w.UserSetting.Id, Un = w.UserSetting.UserName, T = w.Duration, S = w.Score, M = w.Max, Rx = w.RxD, D = w.Date }).ToArray();
                wod = new Affine.Data.json.WOD (){ Id = workout.WOD.Id, Standard = workout.WOD.Standard, Type = workout.WOD.WODType.Id, Name = workout.WOD.Name, Description = workout.WOD.Description };
                if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.TIMED)
                {   // time in sec
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.T).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = (double)w.T, Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
                else if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT)
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.M).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id, Id = w.Id, S = Math.Round(Affine.Utils.UnitsUtil.systemDefaultToUnits(Convert.ToDouble(w.M), weight), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
                else
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.S).Select(w => new Affine.Data.json.WorkoutData() { UId = w.Un + "_" + w.Id , Id = w.Id, S = Math.Round(Convert.ToDouble(w.S), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false) }).ToArray();
                }
            }
            else
            {   // for now this will handle "running, swimming, walking, cycling"
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {
                    if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP || workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.EVERYONE;
                    }
                    else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.NIKE_NO_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                    }
                    // TODO: not sure about this one....
                    /*
                else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                {   // TODO: ?? this is a special case that we want to compare all the times of people that have logged a run for the route.
                    long mapRouteKey = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    IQueryable<Workout> workoutQuery = entities.WorkoutExtendeds.Include("UserStream").Where(we => we.MapRoute != null && we.MapRoute.Id == mapRouteKey).Select(we => we.UserStream).OfType<Workout>().OrderBy(w => w.Duration).Take(5000);
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    var wd = data.OrderByDescending(w => w.Duration).Select(w => new
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                    var ret = new { WOD = new { }, WorkoutData = wd, Workout = workoutJson, Context = (int)context };
                    hiddenWorkoutData.Value = serializer.Serialize(ret);
                }*/
                    else
                    {
                        context = Utils.ConstsUtil.GraphContext.ME;
                    }
                }

                if (context == Utils.ConstsUtil.GraphContext.EVERYONE)
                {   // we want to compare achievments...
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration.Value,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.WATCHLIST || context == Utils.ConstsUtil.GraphContext.FRIENDS)
                {
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).
                                                                                                    Where(LinqUtils.BuildContainsExpression<Achievement, long>(a => a.UserSetting.Id, friendIds)).Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id = w.Id,
                        S = w.Duration.Value,
                        Un = w.UserSetting.UserName,
                        D = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.ME)   // this is just you for the ranges.. since no map data
                {
                    IQueryable<Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.UserSetting.Id == ProfileSettings.Id &&
                                                                                                    a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                    workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                    workout.Distance < a.AchievementType.DistanceRangeB).
                                                                                                    Take(5000).Select(a => a.UserStream).OfType<Workout>().AsQueryable();
                   workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id));
                   workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                   Workout[] data = workoutQuery.ToArray();
                   jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                   {
                       UId = w.UserSetting.UserName + "_" + w.Id,
                       Id = w.Id,
                       S = w.Duration.Value,
                       Un = w.UserSetting.UserName,
                       D = w.Date.ToLocalTime().ToShortDateString()
                   }).ToArray();
                }
            }
            var retWorkout = new { WOD = wod, WorkoutData = jsonWorkoutData, Workout = jsonWorkout, Context = (int)context };
            hiddenWorkoutData.Value = serializer.Serialize(retWorkout);
        }
예제 #21
0
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            string status = string.Empty;
            try
            {
                Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance;
                Affine.WebService.StreamService streamService = new WebService.StreamService();
                int skip = 0;
                int take = 0;
                string json = string.Empty;
                switch (hiddenAjaxAction.Value)
                {
                    case "friendRequest":
                        long fid = Convert.ToInt64(hiddenAjaxValue.Value);
                        dataManager.sendFriendRequest(UserSettings.Id, fid);
                        status = "Friend request has been sent.";
                        break;
                    case "friendListDataPage":
                        skip = Convert.ToInt32(hiddenAjaxValue.Value);
                        take = Convert.ToInt32(hiddenAjaxValue2.Value);
                        if (ProfileSettings is Group)
                        {
                            json = streamService.getMemberListData(ProfileSettings.Id, skip, take, this.UserSettings.Id);
                        }
                        else
                        {
                            json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, skip, take, this.UserSettings.Id);
                        }
                        RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); ");
                        break;
                    case "followingListDataPage":
                        skip = Convert.ToInt32(hiddenAjaxValue.Value);
                        take = Convert.ToInt32(hiddenAjaxValue2.Value);
                        json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWING, skip, take);
                        RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFollowingList.generateStreamDom('" + json + "'); ");
                        break;
                    case "followerListDataPage":
                        skip = Convert.ToInt32(hiddenAjaxValue.Value);
                        take = Convert.ToInt32(hiddenAjaxValue2.Value);
                        json = streamService.getFriendListData(ProfileSettings.UserKey, ProfileSettings.PortalKey, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWERS, skip, take);
                        RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFollowerList.generateStreamDom('" + json + "'); ");
                        break;

                }
            }
            catch (Exception ex)
            {
                status = "ERROR: There was a problem with the action (" + ex.Message + ")";
            }
            RadAjaxManager1.ResponseScripts.Add("UpdateStatus('" + status + "'); ");
        }
예제 #22
0
 private void SetupStreams()
 {
     // We need to get all the different types of requests that belong to the user.
     // - Once we have all the request.  Divide them up into categories by object type.
     // - Display each type using the Request List control.
     WebService.StreamService streamService = new WebService.StreamService();
     Affine.Data.Managers.IStreamManager streamMan = Affine.Data.Managers.LINQ.StreamManager.Instance;
     Affine.Data.json.UserSetting[] freindRequest = streamMan.GetFriendRequests(this.UserSettings.Id);
     Affine.Data.json.UserSetting[] groupInvite = streamMan.GetGroupInviteRequests(this.UserSettings.Id);
     string json = streamMan.ToJsonWithPager(freindRequest);
     string json2 = streamService.getNotifications(UserSettings.Id, 0, 50);
     string js = string.Empty;
     if (Request["n"] != null)
     {
         aqufitEntities entities = new aqufitEntities();
         long nid = Convert.ToInt64(Request["n"]);
         Notification notification = entities.UserStreamSet.OfType<Notification>().FirstOrDefault(n => n.Id == nid);
         if (notification != null)
         {
             notification.PublishSettings = (int)Affine.Utils.ConstsUtil.PublishSettings.NOTIFICATION_READ;  // this will take it out of the top menu since the user clicked to deal with it..
             entities.SaveChanges();
             js += "var $sel = $('#atiStreamItem" + Request["n"] + "');";
             js += "var targetOffset = $sel.offset().top; ";
             js += "$sel.css('background-color','#ffcc99').css('border', '2px solid #e47526'); ";
             js += "$('html,body').animate({scrollTop: targetOffset}, 500);";
         }
     }
     if (groupInvite.Length > 0)
     {
         atiGroupJoinRequest.Visible = true;
         string json3 = streamMan.ToJsonWithPager(groupInvite);
         ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupInviteList", "$(function(){ Aqufit.Page.atiGroupJoinRequest.generateStreamDom('" + json3 + "'); });", true);
     }
     ScriptManager.RegisterStartupScript(this, Page.GetType(), "NotificationList", "$(function(){ Aqufit.Page.atiFriendRequestScript.generateStreamDom('" + json + "'); Aqufit.Page.atiStreamScript.generateStreamDom('" + json2 + "'); " + js + " });", true);
 }
예제 #23
0
        private void SetupFeaturedGroups()
        {
            aqufitEntities entities = new aqufitEntities();
            // CA - We have encoded the number of members in a Groups::MainGroupKey ... this is an easy way to pick out featured groups..
            IQueryable<Group> featureQuery = entities.UserSettings.OfType<Group>().Include("Image").Include("Places").Where(g => g.MainGroupKey > 10 );
            int gcount = featureQuery.Count();
            int skip = new Random().Next(gcount-1);
            Group feature = featureQuery.OrderBy( g => g.Id ).Skip(skip).First();
            atiFGProfileImg.Settings = feature;
            hrefGroupName.HRef  = hrefGroupLink2.HRef = ResolveUrl("~/") + "Group/" + feature.UserName;
            hrefGroupName.InnerHtml = feature.UserFirstName;

            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
            Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(feature.Id);
            System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
            RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");

            // TODO: cache this grabbing of the friend ids from the stream service
            long[] friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == feature.Id || f.DestUserSettingKey == feature.Id) && (f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER)).Select(f => (f.SrcUserSettingKey == feature.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray();
            IQueryable<Affine.Data.User> friends = entities.UserSettings.OfType<User>().Where(Affine.Utils.Linq.LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).OrderBy(s => s.Id);
            int fcount = friends.Count();
            UserSettings[] firendSettings = null;
            if (fcount > 6)
            {
                Random rand = new Random((int)DateTime.Now.Millisecond);
                skip = rand.Next(fcount - 6);
                firendSettings = friends.Skip(skip).Take(6).ToArray();
            }
            else
            {
                firendSettings = friends.Take(6).ToArray();
            }
            atiFriendsPhotos.FriendKeyList = firendSettings;
            atiFriendsPhotos.User = feature;
            atiFriendsPhotos.FriendCount = fcount;
            atiFriendsPhotos.FriendListLink = ResolveUrl("~/") + feature.UserName + "/Friends";

            if( feature.Places.Count > 0 ){
                Place place = feature.Places.FirstOrDefault();
                litGroupDescription.Text += "<span>" + place.Street + "<br />"+place.City+", "+place.Region+", "+place.Country+"</span>";
                litGroupDescription.Text += "<span>"+place.Description+"</span>";
            }
            WebService.StreamService streamService = new WebService.StreamService();
            string json = streamService.getActiveGroups(0, 10);
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "Groups", "$(function(){ Aqufit.Page.atiGroupList.generateStreamDom('" + json + "'); });", true);
        }
예제 #24
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {               
                this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx")+"?u=-1&p=0&bg=1";
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    aqufitEntities entities = new aqufitEntities();
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    imgSearch.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    if (GroupSettings == null)
                    {       // Let people search for a group in this case..
                        atiGroupListPanel.Visible = true;
                        atiGroupProfile.Visible = false;

                        if (this.UserSettings == null)
                        {
                            pageMyGroups.Visible = false;
                            tabMyGroups.Visible = false;
                        }

                        if (this.UserSettings != null && (this.UserSettings.LatHome != null && this.UserSettings.LatHome.Value > 0.0))
                        {
                            atiGMap.Lat = this.UserSettings.LatHome.Value;
                            atiGMap.Lng = this.UserSettings.LngHome.Value;
                            atiGMap.Zoom = 13;
                        }
                        imgAd.Src = ResolveUrl("~/portals/0/images/adTastyPaleo.jpg");
                        WebService.StreamService streamService = new WebService.StreamService();
                        if (this.UserSettings != null)
                        {   // TODO: need to hide the "My Group" section
                            string json = streamService.getGroupListData(this.UserSettings.Id, 0, 25);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "MyGroups", "$(function(){ Aqufit.Page.atiMyGroupList.generateStreamDom('" + json + "'); });", true);
                        }
                       // string search = streamService.searchGroupListData(PortalId, null, 0, 15);

                        atiMyGroupList.IsOwner = true;

                        SetupFeaturedGroups();

                        // we need to setup for a location based group search                    
                       // ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupSearch", "$(function(){ Aqufit.Page.atiGroupSearch.generateStreamDom('" + search + "'); });", true);
                    }
                    else
                    {
                        atiWebLinksList.ProfileSettings = GroupSettings;
                        aHistory.HRef = baseUrl + GroupSettings.UserName + "/workout-history";
                        aLeaders.HRef = baseUrl + GroupSettings.UserName + "/achievements";
                        aMembers.HRef = baseUrl + GroupSettings.UserName + "/friends";
                        atiProfile.ProfileSettings = GroupSettings;
                        this.ProfileCSS = GroupSettings.CssStyle;
                        atiWorkoutScheduler.ProfileSettings = GroupSettings;
                       
                        litGroupName.Text = "<h2>" + GroupSettings.UserFirstName + "</h2>";
                        imgAdRight.Src = ResolveUrl("/portals/0/images/adTastyPaleo.jpg");
                        LoadChartData();

                        if (Request["w"] != null)
                        {
                            RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page.Tabs.SwitchTab(1); });");
                            long wId = Convert.ToInt64(Request["w"]);
                            WOD wod = entities.WODs.Include("WODType").FirstOrDefault(w => w.Id == wId);
                            if (wod != null)
                            {
                                atiWorkoutScheduler.SetControlToWOD = wod;
                            }
                        }

                        long[] friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.GroupSettings.Id || f.DestUserSettingKey == this.GroupSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER).Select(f => (f.SrcUserSettingKey == this.GroupSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray();
                        IQueryable<Affine.Data.User> friends = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).OrderBy(s => s.Id);
                        int fcount = friends.Count();
                        UserSettings[] firendSettings = null;
                        if (fcount > 6)
                        {
                            Random rand = new Random((int)DateTime.Now.Millisecond);
                            int skip = rand.Next(fcount - 6);
                            firendSettings = friends.Skip(skip).Take(6).ToArray();
                        }
                        else
                        {
                            firendSettings = friends.Take(6).ToArray();
                        }
                        // PERMISSIONS: The action panel is only visible to OWNERS                     
                        if (GroupPermissions == ConstsUtil.Relationships.GROUP_OWNER || GroupPermissions == ConstsUtil.Relationships.GROUP_ADMIN)  // Need to find if user is an admin
                        {
                            atiProfile.IsOwner = true;
                            tabWorkout.Visible = true;
                            pageScheduleWOD.Visible = true;
                            bJoinGroup.Visible = false;     // for now owners can never leave the group ... mu ha ha ha
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(atiCommentPanel, atiCommentPanel, RadAjaxLoadingPanel1);
                        }
                        else if (GroupPermissions == ConstsUtil.Relationships.GROUP_MEMBER)
                        {
                            bJoinGroup.Text = "Leave Group";
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(atiCommentPanel, atiCommentPanel, RadAjaxLoadingPanel1);
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(bJoinGroup, bJoinGroup, RadAjaxLoadingPanel1);
                        }
                        else
                        {
                            tabComment.Visible = false;
                            pageViewComment.Visible = false;
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(bJoinGroup, bJoinGroup, RadAjaxLoadingPanel1);
                        }                      
                        // settup the users web links                    
                        this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?us=" + GroupSettings.Id + "&bg=1";
                        this.ProfileCSS = GroupSettings.CssStyle;                         
                        
                    }
                }
                
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }         
        }
예제 #25
0
        private void SetupAccountEdit(Group group)
        {
            aqufitEntities entities = new aqufitEntities();
            group = entities.UserSettings.OfType<Group>().Include("GroupType").Include("UserSettingsExtendeds").Include("Places").FirstOrDefault(g => g.Id == GroupSettings.Id);

            hiddenGroupKey.Value = "" + GroupSettings.Id;
            UserFriends ownerId = entities.UserFriends.FirstOrDefault(f => (f.SrcUserSettingKey == group.Id || f.DestUserSettingKey == group.Id) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER);
            if (ownerId != null)
            {
                atiOwnerProfile.Settings = entities.UserSettings.FirstOrDefault(u => u.Id == (ownerId.SrcUserSettingKey == group.Id ? ownerId.DestUserSettingKey : ownerId.SrcUserSettingKey));
            }
            else
            {
                atiOwnerProfile.Visible = false;
            }

            // setup the Basic Info section
            txtGroupName.Text = group.UserFirstName;
            atiGroupName.Text = group.UserName;
            Place place = group.Places.FirstOrDefault();
            if (place != null)
            {
                atTxtGroupDescription.Text = place.Description;
            }
            atiGroupName.Enabled = false;
            atiTxtGroupEmail.Text = group.UserEmail;
            ddlGroupType.SelectedValue = "" + group.GroupType.Id;

            atiAddress.Visible = false;
            // TODO: for now we don't allow a place edit.
            /*
            Place place = entities.Places.FirstOrDefault( p => p.UserSetting.Id == group.Id );
            if( place != null ){
                atiAddress.City = place.City;
                atiAddress.Region = place.Region;
                atiAddress.
            }
             **/
            UserSettingsExtended[] webLinks = group.UserSettingsExtendeds.Where(s => s.Class == 1).ToArray();
            UserSettingsExtended facebook = webLinks.FirstOrDefault(w => w.Name == "Facebook");
            atiWebLinks.Facebook = facebook != null ? facebook.Value : null;
            UserSettingsExtended twitter = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Twitter");
            atiWebLinks.Twitter = twitter != null ? twitter.Value : null;
            UserSettingsExtended linkedin = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "LinkedIn");
            atiWebLinks.LinkedIn = linkedin != null ? linkedin.Value : null;
            UserSettingsExtended youtube = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "YouTube");
            atiWebLinks.YouTube = youtube != null ? youtube.Value : null;
            UserSettingsExtended flickr = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Flickr");
            atiWebLinks.Flickr = flickr != null ? flickr.Value : null;
            UserSettingsExtended personal = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Personal");
            atiWebLinks.Peronsal = personal != null ? personal.Value : null;

            // setup the advanced settings
            UserFriends follow = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == group.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW);
            if (follow != null)
            {
                Group followedGroup = entities.UserSettings.OfType<Group>().FirstOrDefault(g => g.Id == follow.DestUserSettingKey);
                RadComboBoxItem item = new RadComboBoxItem();
                item.Text = followedGroup.UserFirstName;
                item.Value = "" + followedGroup.Id;
                atiRadComboBoxSearchGroups.Items.Add(item);
                atiRadComboBoxSearchGroups.SelectedIndex = atiRadComboBoxSearchGroups.Items.Count - 1;
            }

            // Next we do the appearance settings...
            if (! string.IsNullOrWhiteSpace( group.CssStyle ))
            {
                const string findMe = "background-color:";
                int bgInd = group.CssStyle.IndexOf(findMe);
                if (bgInd >= 0)
                {
                    string color = group.CssStyle.Substring(bgInd + findMe.Length, group.CssStyle.IndexOf(";", bgInd + findMe.Length) - (bgInd + findMe.Length)).Replace("#", "");
                    atiThemeEditor.BackgroundColor = System.Drawing.Color.FromName("#"+color.Trim());
                }
                if (group.CssStyle.Contains("background-repeat: repeat;"))
                {
                    atiThemeEditor.IsTiled = true;
                }
            }

            // Next the member list
            Affine.WebService.StreamService ss = new WebService.StreamService();
            string json = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);

            string json2 = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);
            RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "');  Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "');  }); ");
        }
예제 #26
0
        private void SetupPage()
        {
            // center USA if we dont have anything to go on
               // double Lat = 39.6395;
               // double Lng = -95.4492;
               // short Zoom = 4;
            double Lat = 49.2844;
            double Lng = -123.1258;
            short Zoom = 10;

            if (UserSettings != null && UserSettings.LatHome.HasValue && UserSettings.LngHome.HasValue)
            {
                Lat = UserSettings.LatHome.Value;
                Lng = UserSettings.LngHome.Value;
                Zoom = 10;
            }
            atiGMap.Lat = Lat;
            atiGMap.Lng = Lng;
            atiGMap.Zoom = Zoom;
            /*
            if (!string.IsNullOrEmpty(hiddenLat.Value))
            {
                atiGMap.Lat = Convert.ToDouble(hiddenLat.Value);
            }
            if (!string.IsNullOrEmpty(hiddenLng.Value))
            {
                atiGMap.Lng = Convert.ToDouble(hiddenLng.Value);
            }
            if (!string.IsNullOrEmpty(hiddenZoom.Value))
            {
                atiGMap.Zoom = Convert.ToInt16(hiddenZoom.Value);
            }
             */
            hiddenLat.Value = "" + Lat;
            hiddenLng.Value = "" + Lng;
            hiddenZoom.Value = "" + Zoom;
            WebService.StreamService streamService = new WebService.StreamService();
            string json = streamService.GetRoutes(Lat, Lng, 5.0, 0, 10, "date");
            ScriptManager.RegisterStartupScript(this, Page.GetType(), "RouteList", "$(function(){ Aqufit.Page.atiRouteListScript.generateStreamDom('" + json + "'); });", true);
        }
예제 #27
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);

            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src         = ResolveUrl("/portals/0/images/adTastyPaleo.jpg");
                imgCheck.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png");

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    long wId = 0;
                    if (HttpContext.Current.Items["w"] != null)
                    {
                        wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                    }
                    else if (Request["w"] != null)
                    {
                        wId = Convert.ToInt64(Request["w"]);
                    }

                    // Are we viewing a specific workout ?
                    if (wId > 0)
                    {
                        divMainLinks.Visible = true;

                        atiProfile.Visible     = false;
                        hiddenWorkoutKey.Value = "" + wId;
                        aqufitEntities entities = new aqufitEntities();
                        WOD            wod      = entities.WODs.Include("WODType").Include("WODSets").Include("WODSets.WODExercises").Include("WODSets.WODExercises.Exercise").FirstOrDefault(w => w.Id == wId);
                        if (base.UserSettings != null && wod.Standard == 0)
                        {
                            User2WODFav fav = entities.User2WODFav.FirstOrDefault(mr => mr.WOD.Id == wod.Id && mr.UserSetting.Id == UserSettings.Id);
                            bAddWorkout.Visible    = fav == null;
                            bRemoveWorkout.Visible = fav != null;
                        }
                        lWorkoutTitle.Text = wod.Name;

                        //  lWorkoutDescription.Text = wod.Description;

                        // constructWorkoutInfo(wod);
                        lWorkoutInfo.Text = wod.Description;
                        if (wod.Standard > 0)
                        {
                            imgCrossFit.Visible   = true;
                            imgCrossFit.Src       = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/xfit.png");
                            atiProfileImg.Visible = false;
                        }
                        else
                        {
                            atiProfileImg.Settings = entities.UserSettings.FirstOrDefault(us => us.Id == wod.UserSettingsKey);
                        }
                        atiWorkoutPanel.Visible  = false;
                        atiWorkoutViewer.Visible = true;

                        // Get the leader board
                        IQueryable <Workout> stream = entities.UserStreamSet.OfType <Workout>().Where(w => w.WOD.Id == wId);
                        long typeId = entities.WODs.Where(w => w.Id == wId).Select(w => w.WODType.Id).FirstOrDefault();
                        switch (typeId)
                        {
                        case (long)Affine.Utils.WorkoutUtil.WodType.AMRAP:
                        case (long)Affine.Utils.WorkoutUtil.WodType.SCORE:
                            atiScoreRangePanel.Visible = true;
                            stream = stream.OrderByDescending(w => w.Score);
                            break;

                        case (long)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT:
                            atiMaxRangePanel.Visible = true;
                            atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                            atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                            atiMaxWeightUnitsFirst.Selected = WeightUnits;
                            atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                            atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                            atiMaxWeightUnitsLast.Selected = WeightUnits;
                            stream = stream.OrderByDescending(w => w.Max);
                            break;

                        case (long)Affine.Utils.WorkoutUtil.WodType.TIMED:
                            atiTimeSpanePanel.Visible = true;
                            stream = stream.OrderBy(w => w.Duration);
                            break;

                        default:
                            stream = stream.OrderByDescending(w => w.TimeStamp);
                            break;
                        }
                        string js = string.Empty;
                        atiShareLink.ShareLink  = "http://" + Request.Url.Host + "/workout/" + wod.Id;
                        atiShareLink.ShareTitle = "FlexFWD.com crossfit WOD " + wod.Name;

                        workoutTabTitle.Text = "&nbsp;" + (string.IsNullOrWhiteSpace(wod.Name) ? "Untitled" : wod.Name) + "&nbsp;";
                        Affine.WebService.StreamService ss = new WebService.StreamService();
                        string jsonEveryone = ss.getStreamDataForWOD(wod.Id, -1, 0, 15, true, true, -1, -1, -1);

                        string jsonYou = string.Empty;

                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromStreamData('" + jsonEveryone + "'); ";
                        if (base.UserSettings != null)
                        {
                            hlLogWorkout.HRef = baseUrl + UserSettings.UserName + "?w=" + wId;
                            hlWorkouts.HRef   = baseUrl + UserSettings.UserName + "/workout-history";
                            jsonYou           = ss.getStreamDataForWOD(wod.Id, base.UserSettings.Id, 0, 10, true, true, -1, -1, -1);
                            js += "Aqufit.Page.atiYouStreamScript.generateStreamDom('" + jsonYou + "');";
                            js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromYourStreamData('" + jsonYou + "'); ";
                            // TODO: this could be improved on...
                            Workout thisWod = entities.UserStreamSet.OfType <Workout>().FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id && w.WOD.Id == wId);
                            if (thisWod != null)
                            {   // graphs of this wod
                                hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + thisWod.Id;
                            }
                            else
                            {   // just grab any workout then..
                                Workout any = entities.UserStreamSet.OfType <Workout>().OrderByDescending(w => w.Id).FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id);
                                if (any != null)
                                {
                                    hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + any.Id;
                                }
                                else
                                {   // no workouts ??? say what.. slack man :) hide graph
                                    hlGraph.Visible = false;
                                }
                            }
                        }
                        else
                        {
                            hlGraph.HRef                 = ResolveUrl("~/Login");
                            hlLogWorkout.HRef            = hlGraph.HRef;
                            hlWorkouts.HRef              = hlGraph.HRef;
                            atiPanelYourProgress.Visible = false;
                        }
                        hlCreateWOD.HRef  = baseUrl + "Profile/WorkoutBuilder";
                        hlMyWorkouts.HRef = baseUrl + "Profile/MyWorkouts";
                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".drawChart(); ";



                        ScriptManager.RegisterStartupScript(this, Page.GetType(), "SimilarRouteList", "$(function(){ " + js + " Aqufit.Page.atiEveryoneStreamScript.generateStreamDom('" + jsonEveryone + "'); });", true);



                        YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                        //order results by the number of views (most viewed first)
                        query.OrderBy          = "viewCount";
                        query.NumberToRetrieve = 3;
                        query.SafeSearch       = YouTubeQuery.SafeSearchValues.Moderate;

                        YouTubeRequestSettings settings = new YouTubeRequestSettings(ConfigurationManager.AppSettings["youtubeApp"], ConfigurationManager.AppSettings["youtubeKey"]);
                        YouTubeRequest         request  = new YouTubeRequest(settings);
                        const int     NUM_ENTRIES       = 50;
                        IList <Video> videos            = new List <Video>();
                        IList <Video> groupVideo        = new List <Video>();
                        // first try to find videos with regard to users group
                        Feed <Video> videoFeed = null;

                        if (this.UserSettings != null)
                        {
                            long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == UserSettings.Id || f.DestUserSettingKey == UserSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER).Select(f => f.SrcUserSettingKey == UserSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
                            Group  business = entities.UserSettings.OfType <Group>().Where(Utils.Linq.LinqUtils.BuildContainsExpression <Group, long>(us => us.Id, groupIds)).FirstOrDefault(g => g.GroupType.Id == 1);
                            if (business != null)
                            {   // TODO: need the business name...
                                query.Query = business.UserName;
                            }
                            else
                            {
                                UserSettings creator = entities.UserSettings.FirstOrDefault(u => u.Id == wod.UserSettingsKey);
                                if (creator is Group)
                                {   // TODO: need the business name...
                                    query.Query = creator.UserFirstName + " " + creator.UserLastName;
                                }
                                else
                                {
                                    query.Query = UserSettings.UserFirstName + " " + UserSettings.UserLastName;
                                }
                            }
                            videoFeed = request.Get <Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                groupVideo.Add(v);
                            }
                        }
                        if (videos.Count < NUM_ENTRIES)
                        {   // now try the crossfit WOD name
                            query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                            query.Query            = "crossfit wod " + wod.Name;
                            videoFeed = request.Get <Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                videos.Add(v);
                            }
                            if (videos.Count < NUM_ENTRIES)
                            {   // this is last resort .. just get videos about crossfit...
                                query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                                query.Query            = "crossfit wod";
                                videoFeed = request.Get <Video>(query);
                                foreach (Video v in videoFeed.Entries)
                                {
                                    videos.Add(v);
                                }
                            }
                        }

                        const int TAKE = 3;
                        if (videos.Count > TAKE)
                        {
                            Random random = new Random((int)DateTime.Now.Ticks);
                            int    rand   = random.Next(videos.Count - TAKE);
                            videos = videos.Skip(rand).Take(TAKE).ToList();
                            if (groupVideo.Count > 0)
                            {
                                // always replace one of the main videos with a gorup one.. (if possible)
                                rand      = random.Next(groupVideo.Count - 1);
                                videos[0] = groupVideo[rand];
                            }
                            atiYoutubeThumbList.VideoFeed = videos;
                        }
                        else
                        {
                            atiVideoPanel.Visible = false;
                        }
                    }
                    else
                    {
                        atiVideoPanel.Visible     = false;
                        atiPanelQuickView.Visible = false;
                        hlGraph.Visible           = false;
                        aqufitEntities entities      = new aqufitEntities();
                        var            exerciseArray = entities.Exercises.OrderBy(x => x.Name).Select(x => new{ Text = x.Name, Value = x.Id }).ToArray();
                        RadListBoxExcerciseSource.DataSource = exerciseArray;
                        RadListBoxExcerciseSource.DataBind();

                        string order = orderDate.Checked ? "date" : "popular";
                        if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureMyWorkouts"))
                        {
                            this.IsMyWorkouts          = true;
                            atiProfile.ProfileSettings = base.UserSettings;
                            atiProfile.IsOwner         = true;
                            atiProfile.IsSmall         = true;
                            atiWorkoutPanel.Visible    = true;
                            workoutTabTitle.Text       = "My Workouts";
                            liMyWorkouts.Visible       = false;
                            liFindWorkout.Visible      = true;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(base.UserSettings.Id, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiWorkoutListScript.isMyRoutes = true; Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                        else
                        {
                            this.IsMyWorkouts        = false;
                            atiProfile.Visible       = false;
                            workoutTabTitle.Text     = "Workouts";
                            atiWorkoutPanel.Visible  = true;
                            atiWorkoutViewer.Visible = false;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(-1, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList2", "$(function(){ Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #28
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);

            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src = ResolveUrl("/portals/0/images/adTastyPaleo.jpg");
                imgCheck.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png");

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    long wId = 0;
                    if (HttpContext.Current.Items["w"] != null)
                    {
                        wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                    }
                    else if (Request["w"] != null)
                    {
                        wId = Convert.ToInt64(Request["w"]);
                    }

                    // Are we viewing a specific workout ?
                    if (wId > 0)
                    {
                        divMainLinks.Visible = true;

                        atiProfile.Visible = false;
                        hiddenWorkoutKey.Value = "" + wId;
                        aqufitEntities entities = new aqufitEntities();
                        WOD wod = entities.WODs.Include("WODType").Include("WODSets").Include("WODSets.WODExercises").Include("WODSets.WODExercises.Exercise").FirstOrDefault(w => w.Id == wId);
                        if( base.UserSettings != null && wod.Standard == 0){
                            User2WODFav fav = entities.User2WODFav.FirstOrDefault(mr => mr.WOD.Id == wod.Id && mr.UserSetting.Id == UserSettings.Id);
                            bAddWorkout.Visible = fav == null;
                            bRemoveWorkout.Visible = fav != null;
                        }
                        lWorkoutTitle.Text = wod.Name;

                      //  lWorkoutDescription.Text = wod.Description;

                       // constructWorkoutInfo(wod);
                        lWorkoutInfo.Text = wod.Description;
                        if (wod.Standard > 0)
                        {
                            imgCrossFit.Visible = true;
                            imgCrossFit.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/xfit.png");
                            atiProfileImg.Visible = false;
                        }
                        else
                        {
                            atiProfileImg.Settings = entities.UserSettings.FirstOrDefault(us => us.Id == wod.UserSettingsKey);
                        }
                        atiWorkoutPanel.Visible = false;
                        atiWorkoutViewer.Visible = true;

                        // Get the leader board
                        IQueryable<Workout> stream = entities.UserStreamSet.OfType<Workout>().Where(w => w.WOD.Id == wId);
                        long typeId = entities.WODs.Where(w => w.Id == wId).Select(w => w.WODType.Id).FirstOrDefault();
                        switch (typeId)
                        {
                            case (long)Affine.Utils.WorkoutUtil.WodType.AMRAP:
                            case (long)Affine.Utils.WorkoutUtil.WodType.SCORE:
                                atiScoreRangePanel.Visible = true;
                                stream = stream.OrderByDescending(w => w.Score);
                                break;
                            case (long)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT:
                                atiMaxRangePanel.Visible = true;
                                atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                                atiMaxWeightUnitsFirst.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                                atiMaxWeightUnitsFirst.Selected = WeightUnits;
                                atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                                atiMaxWeightUnitsLast.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
                                atiMaxWeightUnitsLast.Selected = WeightUnits;
                                stream = stream.OrderByDescending(w => w.Max);
                                break;
                            case (long)Affine.Utils.WorkoutUtil.WodType.TIMED:
                                atiTimeSpanePanel.Visible = true;
                                stream = stream.OrderBy(w => w.Duration);
                                break;
                            default:
                                stream = stream.OrderByDescending(w => w.TimeStamp);
                                break;
                        }
                        string js = string.Empty;
                        atiShareLink.ShareLink = "http://" + Request.Url.Host + "/workout/" + wod.Id;
                        atiShareLink.ShareTitle = "FlexFWD.com crossfit WOD " + wod.Name;

                        workoutTabTitle.Text = "&nbsp;" + (string.IsNullOrWhiteSpace(wod.Name) ? "Untitled" : wod.Name) + "&nbsp;";
                        Affine.WebService.StreamService ss = new WebService.StreamService();
                        string jsonEveryone = ss.getStreamDataForWOD(wod.Id, -1, 0, 15, true, true, -1, -1, -1);

                        string jsonYou = string.Empty;

                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromStreamData('" + jsonEveryone + "'); ";
                        if (base.UserSettings != null)
                        {
                            hlLogWorkout.HRef = baseUrl + UserSettings.UserName + "?w=" + wId;
                            hlWorkouts.HRef = baseUrl + UserSettings.UserName + "/workout-history";
                            jsonYou = ss.getStreamDataForWOD(wod.Id, base.UserSettings.Id, 0, 10, true, true, -1, -1, -1);
                            js += "Aqufit.Page.atiYouStreamScript.generateStreamDom('" + jsonYou + "');";
                            js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromYourStreamData('" + jsonYou + "'); ";
                            // TODO: this could be improved on...
                            Workout thisWod = entities.UserStreamSet.OfType<Workout>().FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id && w.WOD.Id == wId);
                            if (thisWod != null)
                            {   // graphs of this wod
                                hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + thisWod.Id;
                            }
                            else
                            {   // just grab any workout then..
                                Workout any = entities.UserStreamSet.OfType<Workout>().OrderByDescending( w => w.Id ).FirstOrDefault(w => w.UserSetting.Id == UserSettings.Id);
                                if (any != null)
                                {
                                    hlGraph.HRef = ResolveUrl("~/") + UserSettings.UserName + "/workout/" + any.Id;
                                }
                                else
                                {   // no workouts ??? say what.. slack man :) hide graph
                                    hlGraph.Visible = false;
                                }
                            }
                        }
                        else
                        {
                            hlGraph.HRef = ResolveUrl("~/Login");
                            hlLogWorkout.HRef = hlGraph.HRef;
                            hlWorkouts.HRef = hlGraph.HRef;
                            atiPanelYourProgress.Visible = false;
                        }
                        hlCreateWOD.HRef = baseUrl + "Profile/WorkoutBuilder";
                        hlMyWorkouts.HRef = baseUrl + "Profile/MyWorkouts";
                        js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".drawChart(); ";

                        ScriptManager.RegisterStartupScript(this, Page.GetType(), "SimilarRouteList", "$(function(){ " + js + " Aqufit.Page.atiEveryoneStreamScript.generateStreamDom('" + jsonEveryone + "'); });", true);

                        YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
                        //order results by the number of views (most viewed first)
                        query.OrderBy = "viewCount";
                        query.NumberToRetrieve = 3;
                        query.SafeSearch = YouTubeQuery.SafeSearchValues.Moderate;

                        YouTubeRequestSettings settings = new YouTubeRequestSettings(ConfigurationManager.AppSettings["youtubeApp"], ConfigurationManager.AppSettings["youtubeKey"]);
                        YouTubeRequest request = new YouTubeRequest(settings);
                        const int NUM_ENTRIES = 50;
                        IList<Video> videos = new List<Video>();
                        IList<Video> groupVideo = new List<Video>();
                        // first try to find videos with regard to users group
                        Feed<Video> videoFeed = null;

                        if (this.UserSettings != null)
                        {
                            long[] groupIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == UserSettings.Id || f.DestUserSettingKey == UserSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER).Select(f => f.SrcUserSettingKey == UserSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
                            Group business = entities.UserSettings.OfType<Group>().Where(Utils.Linq.LinqUtils.BuildContainsExpression<Group, long>(us => us.Id, groupIds)).FirstOrDefault(g => g.GroupType.Id == 1);
                            if (business != null)
                            {   // TODO: need the business name...
                                query.Query = business.UserName;
                            }
                            else
                            {
                                UserSettings creator = entities.UserSettings.FirstOrDefault(u => u.Id == wod.UserSettingsKey);
                                if (creator is Group )
                                {   // TODO: need the business name...
                                    query.Query = creator.UserFirstName + " " + creator.UserLastName;
                                }
                                else
                                {
                                    query.Query = UserSettings.UserFirstName + " " + UserSettings.UserLastName;
                                }
                            }
                            videoFeed = request.Get<Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                groupVideo.Add(v);
                            }
                        }
                        if (videos.Count < NUM_ENTRIES)
                        {   // now try the crossfit WOD name
                            query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                            query.Query = "crossfit wod " + wod.Name;
                            videoFeed = request.Get<Video>(query);
                            foreach (Video v in videoFeed.Entries)
                            {
                                videos.Add(v);
                            }
                            if (videos.Count < NUM_ENTRIES)
                            {   // this is last resort .. just get videos about crossfit...
                                query.NumberToRetrieve = NUM_ENTRIES - videos.Count;
                                query.Query = "crossfit wod";
                                videoFeed = request.Get<Video>(query);
                                foreach (Video v in videoFeed.Entries)
                                {
                                    videos.Add(v);
                                }
                            }
                        }

                        const int TAKE = 3;
                        if (videos.Count > TAKE)
                        {
                            Random random = new Random((int)DateTime.Now.Ticks);
                            int rand = random.Next(videos.Count - TAKE);
                            videos = videos.Skip(rand).Take(TAKE).ToList();
                            if( groupVideo.Count > 0 ){
                                // always replace one of the main videos with a gorup one.. (if possible)
                                rand = random.Next(groupVideo.Count - 1);
                                videos[0] = groupVideo[rand];
                            }
                            atiYoutubeThumbList.VideoFeed = videos;
                        }
                        else
                        {
                            atiVideoPanel.Visible = false;
                        }
                    }
                    else
                    {
                        atiVideoPanel.Visible = false;
                        atiPanelQuickView.Visible = false;
                        hlGraph.Visible = false;
                        aqufitEntities entities = new aqufitEntities();
                        var exerciseArray = entities.Exercises.OrderBy( x => x.Name ).Select( x => new{ Text = x.Name, Value = x.Id } ).ToArray();
                        RadListBoxExcerciseSource.DataSource = exerciseArray;
                        RadListBoxExcerciseSource.DataBind();

                        string order = orderDate.Checked ? "date" : "popular";
                        if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureMyWorkouts"))
                        {
                            this.IsMyWorkouts = true;
                            atiProfile.ProfileSettings = base.UserSettings;
                            atiProfile.IsOwner = true;
                            atiProfile.IsSmall = true;
                            atiWorkoutPanel.Visible = true;
                            workoutTabTitle.Text = "My Workouts";
                            liMyWorkouts.Visible = false;
                            liFindWorkout.Visible = true;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(base.UserSettings.Id, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiWorkoutListScript.isMyRoutes = true; Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                        else
                        {
                            this.IsMyWorkouts = false;
                            atiProfile.Visible = false;
                            workoutTabTitle.Text = "Workouts";
                            atiWorkoutPanel.Visible = true;
                            atiWorkoutViewer.Visible = false;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetWorkouts(-1, 0, 30, order, null);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList2", "$(function(){ Aqufit.Page.atiWorkoutListScript.generateStreamDom('" + json + "'); });", true);
                        }
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #29
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx")+"?u=-1&p=0&bg=1";
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    aqufitEntities entities = new aqufitEntities();
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    imgSearch.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    if (GroupSettings == null)
                    {       // Let people search for a group in this case..
                        atiGroupListPanel.Visible = true;
                        atiGroupProfile.Visible = false;

                        if (this.UserSettings == null)
                        {
                            pageMyGroups.Visible = false;
                            tabMyGroups.Visible = false;
                        }

                        if (this.UserSettings != null && (this.UserSettings.LatHome != null && this.UserSettings.LatHome.Value > 0.0))
                        {
                            atiGMap.Lat = this.UserSettings.LatHome.Value;
                            atiGMap.Lng = this.UserSettings.LngHome.Value;
                            atiGMap.Zoom = 13;
                        }
                        imgAd.Src = ResolveUrl("~/portals/0/images/adTastyPaleo.jpg");
                        WebService.StreamService streamService = new WebService.StreamService();
                        if (this.UserSettings != null)
                        {   // TODO: need to hide the "My Group" section
                            string json = streamService.getGroupListData(this.UserSettings.Id, 0, 25);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "MyGroups", "$(function(){ Aqufit.Page.atiMyGroupList.generateStreamDom('" + json + "'); });", true);
                        }
                       // string search = streamService.searchGroupListData(PortalId, null, 0, 15);

                        atiMyGroupList.IsOwner = true;

                        SetupFeaturedGroups();

                        // we need to setup for a location based group search
                       // ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupSearch", "$(function(){ Aqufit.Page.atiGroupSearch.generateStreamDom('" + search + "'); });", true);
                    }
                    else
                    {
                        atiWebLinksList.ProfileSettings = GroupSettings;
                        aHistory.HRef = baseUrl + GroupSettings.UserName + "/workout-history";
                        aLeaders.HRef = baseUrl + GroupSettings.UserName + "/achievements";
                        aMembers.HRef = baseUrl + GroupSettings.UserName + "/friends";
                        atiProfile.ProfileSettings = GroupSettings;
                        this.ProfileCSS = GroupSettings.CssStyle;
                        atiWorkoutScheduler.ProfileSettings = GroupSettings;

                        litGroupName.Text = "<h2>" + GroupSettings.UserFirstName + "</h2>";
                        imgAdRight.Src = ResolveUrl("/portals/0/images/adTastyPaleo.jpg");
                        LoadChartData();

                        if (Request["w"] != null)
                        {
                            RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page.Tabs.SwitchTab(1); });");
                            long wId = Convert.ToInt64(Request["w"]);
                            WOD wod = entities.WODs.Include("WODType").FirstOrDefault(w => w.Id == wId);
                            if (wod != null)
                            {
                                atiWorkoutScheduler.SetControlToWOD = wod;
                            }
                        }

                        long[] friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.GroupSettings.Id || f.DestUserSettingKey == this.GroupSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER).Select(f => (f.SrcUserSettingKey == this.GroupSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray();
                        IQueryable<Affine.Data.User> friends = entities.UserSettings.OfType<User>().Where(LinqUtils.BuildContainsExpression<User, long>(s => s.Id, friendIds)).OrderBy(s => s.Id);
                        int fcount = friends.Count();
                        UserSettings[] firendSettings = null;
                        if (fcount > 6)
                        {
                            Random rand = new Random((int)DateTime.Now.Millisecond);
                            int skip = rand.Next(fcount - 6);
                            firendSettings = friends.Skip(skip).Take(6).ToArray();
                        }
                        else
                        {
                            firendSettings = friends.Take(6).ToArray();
                        }
                        // PERMISSIONS: The action panel is only visible to OWNERS
                        if (GroupPermissions == ConstsUtil.Relationships.GROUP_OWNER || GroupPermissions == ConstsUtil.Relationships.GROUP_ADMIN)  // Need to find if user is an admin
                        {
                            atiProfile.IsOwner = true;
                            tabWorkout.Visible = true;
                            pageScheduleWOD.Visible = true;
                            bJoinGroup.Visible = false;     // for now owners can never leave the group ... mu ha ha ha
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(atiCommentPanel, atiCommentPanel, RadAjaxLoadingPanel1);
                        }
                        else if (GroupPermissions == ConstsUtil.Relationships.GROUP_MEMBER)
                        {
                            bJoinGroup.Text = "Leave Group";
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(atiCommentPanel, atiCommentPanel, RadAjaxLoadingPanel1);
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(bJoinGroup, bJoinGroup, RadAjaxLoadingPanel1);
                        }
                        else
                        {
                            tabComment.Visible = false;
                            pageViewComment.Visible = false;
                            RadAjaxManager1.AjaxSettings.AddAjaxSetting(bJoinGroup, bJoinGroup, RadAjaxLoadingPanel1);
                        }
                        // settup the users web links
                        this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?us=" + GroupSettings.Id + "&bg=1";
                        this.ProfileCSS = GroupSettings.CssStyle;

                    }
                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #30
0
        protected void bSaveRecipe_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    // TODO: category tags..
                    long rid = Convert.ToInt64(atHiddenRecipeId.Value);
                    if (rid > 0)
                    {
                        aqufitEntities entities = new aqufitEntities();
                        Recipe r = entities.UserStreamSet.OfType<Recipe>().FirstOrDefault(s => s.Id == rid && s.UserSetting.UserKey == this.UserId && s.UserSetting.PortalKey == this.PortalId);
                        if (r == null)  // security exception
                        {
                            // TODO: send a notification email
                            throw new Exception("Security Exception:  User does not own data.  Action has been logged");
                        }
                    }
                    string[] ingredients = atiRecipeIngredients.Text.Split('\n');
                    Affine.Data.json.RecipeIngredient[] riArray = ingredients.Where( i => !string.IsNullOrEmpty(i) ).Select(i => new Affine.Data.json.RecipeIngredient() { Name = i }).ToArray();

                    Affine.Data.json.RecipeExtended re = new Data.json.RecipeExtended()
                    {
                        Directions = atiRecipeDirections.Text,
                        Ingredients = riArray
                    };
                    // TODO: Ingredients
                    string extraTags = string.Empty;
                    CheckBox cbBreakfast = (CheckBox)atiRecipeCategoriesPanel.FindControl("breakfast");
                    if( cbBreakfast.Checked ){
                        extraTags += ","+cbBreakfast.Text;
                    }
                    CheckBox cbLunch = (CheckBox)atiRecipeCategoriesPanel.FindControl("lunch");
                    if (cbLunch.Checked)
                    {
                        extraTags += "," + cbLunch.Text;
                    }
                    CheckBox cbDinner = (CheckBox)atiRecipeCategoriesPanel.FindControl("dinner");
                    if (cbDinner.Checked)
                    {
                        extraTags += "," + cbDinner.Text;
                    }
                    CheckBox cbSnack = (CheckBox)atiRecipeCategoriesPanel.FindControl("snack");
                    if (cbSnack.Checked)
                    {
                        extraTags += "," + cbSnack.Text;
                    }
                    CheckBox cbDessert = (CheckBox)atiRecipeCategoriesPanel.FindControl("dessert");
                    if (cbDessert.Checked)
                    {
                        extraTags += "," + cbDessert.Text;
                    }
                    Affine.Data.json.StreamData recipe = new Data.json.StreamData()
                    {
                        Id = rid,
                        Title = atiRecipeName.Text,
                        Description = atiRecipeDescription.Text,
                        AvrRating = Convert.ToDouble(atiHiddenRecipeRate.Value),
                        AvrStrictness = Convert.ToDouble(atiHiddenRecipeStrict.Value),
                        Tags = atiRecipeTags.Text + extraTags,
                        NumServings = Convert.ToInt32(atiRecipeServings.Text),
                        TimePrep = Convert.ToInt32(atiRecipePrep.Text),
                        TimeCook = Convert.ToInt32(atiRecipeCook.Text),
                        RecipeExtended = re
                    };

                    Affine.WebService.StreamService service = new WebService.StreamService();
                    long id = service.SaveRecipe(this.UserId, this.PortalId, recipe);
                   // long id = 0;
                    litStatus.Text = "<em>SUCESS</em> Your recipe has been saved.  To Finish attach some image files then press 'done'.";
                    RadAjaxManager1.ResponseScripts.Add(" Paleo.AddMedia("+id+"); ");

                }
            }
            catch (Exception ex)
            {
                litStatus.Text = "<span style=\"color: red;\"><em>FAIL</em> "+ex.Message+"</span>";
                RadAjaxManager1.ResponseScripts.Add(" Paleo.OnFail(); ");
            }
        }
예제 #31
0
        private void LoadChartData()
        {
            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            // need a list of people in the group
            aqufitEntities entities = new aqufitEntities();
            long[] memberIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == GroupSettings.Id || f.DestUserSettingKey == GroupSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER ).Select(f => f.SrcUserSettingKey == GroupSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            // How many members are there in the group.. this will determin how far back in time we will look for workouts
            int numMembers = memberIds.Length;
            // For now we will always look over the last 7 days..
            DateTime today = DateTime.Today;
            DateTime past = today.AddDays(-7);

            IQueryable<UserStream> streamSet = entities.UserStreamSet
                                        .Include("UserSetting").Include("WOD")
                                        .Where(w => w.Date.CompareTo(past) > 0)
                                        .Where(LinqUtils.BuildContainsExpression<UserStream, long>(w => w.UserSetting.Id, memberIds));
            // TODO: we need to get a better idea of who is going to need hydrating before we do it.

            streamSet.Select(w => w.UserSetting).ToArray();     // THIS IS BAD.. Hydrating a lot of users profiles..
            IQueryable<IGrouping<long?, Workout>> groupWorkouts = streamSet.OfType<Workout>().GroupBy(w => w.WorkoutTypeKey);
            // Lets find out what this group is all about ... IE what type of workouts dominate
            long ukey = -1;
            long key = -1;
            int usize = 0;
            int size = 0;
            foreach (IGrouping<long?, Workout> g in groupWorkouts)
            {
                UserSettings us = g.Select(w => w.UserSetting).First();
                // first see if we can find anything that the current user is in
                if (UserSettings != null && g.FirstOrDefault(w => (long)w.UserSettingReference.EntityKey.EntityKeyValues[0].Value == UserSettings.Id) != null)
                {
                    int c = g.Count();
                    if ( c > size)
                    {
                        ukey = g.Key.Value;
                        usize = c;
                    }
                }else{
                    int c = g.Count();
                    if ( c > size)
                    {
                        key = g.Key.Value;
                        size = c;
                    }
                }
            }
            if( ukey > 0 ){ // we found something that this user is in
                key = ukey;
                size = usize;
            }
            IGrouping<long?, Workout> workouts = groupWorkouts.Where(g => g.Key == key).FirstOrDefault();
            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
            Affine.Data.json.LeaderBoardWOD[] leaderBoard = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
            atiLeaderBoard.Visible = true;

            WODSchedule scheduled = entities.WODSchedules.Include("WOD").Where(w => w.UserSetting.Id == GroupSettings.Id).OrderByDescending(w => w.Id).FirstOrDefault();
            litTodaysWOD.Text = "<h3>Last Scheduled Workout:";
            if (scheduled != null)
            {
                WOD wod = scheduled.WOD;
                litTodaysWOD.Text += " <a style=\"font-size: 16px; color: #0095cd; font-weight: bold;\" href=\"/workouts/" + wod.Id + "\">" + wod.Name + "</a></h3>";
                Affine.WebService.StreamService ss = new WebService.StreamService();
                string jsonEveryone = ss.getStreamDataForWOD(wod.Id, -1, 0, 25, true, true, -1, -1, -1);

                string jsonYou = string.Empty;
                string js = string.Empty;
                js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromStreamData('" + jsonEveryone + "'); ";
                if (base.UserSettings != null)
                {
                    jsonYou = ss.getStreamDataForWOD(wod.Id, base.UserSettings.Id, 0, 10, true, true, -1, -1, -1);
                    js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromYourStreamData('" + jsonYou + "'); ";
                }

                js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".drawChart(); ";

                RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page." + atiLeaderBoard.ID + ".loadLeaderBoardFromJson('" + jsSerializer.Serialize(leaderBoard) + "'); " + js + " });");
            }
            else
            {
                litTodaysWOD.Text += " <em>Unavailble</em></h3>";
                atiWorkoutHighChart.Visible = false;
            }
            // so now KEY is the most (type) of workout
            // There are now a couple special cases... (crossfit workouts)
             /*
            if (key == (int)Utils.WorkoutUtil.WorkoutType.CROSSFIT)
            {
                Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                Affine.Data.json.LeaderBoardWOD[] females = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id, "F");
                Affine.Data.json.LeaderBoardWOD[] males = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id, "M");
                atiLeaderBoardMale.Visible = true;
                atiLeaderBoardMale.LeaderWODList = males;
                atiLeaderBoardFemale.Visible = true;
                atiLeaderBoardFemale.LeaderWODList = females;
            }
            else
            {
                if (workouts != null)
                {
                    // TODO: now for some reason we can not hydrate the "UserSettings" so we need to get them now
                    long[] ids = workouts.Select(w => (long)w.UserSettingReference.EntityKey.EntityKeyValues[0].Value).ToArray();

                    // for now the other types of workout are just a quick grab...

                }
            }
              */
              //  ScriptManager.RegisterStartupScript(this, Page.GetType(), "wt", "alert('" +  jsSerializer.Serialize( title ) + "');", true);
        }
예제 #32
0
        private void SetupPageFollowMode()
        {
            WebService.StreamService streamService = new WebService.StreamService();
            if (Request["c"] != null)
            {
                streamService.FollowUser(this.UserSettings.Id, Convert.ToInt64(Request["c"]));
            }
            UserSettings settings = ProfileSettings != null ? ProfileSettings : UserSettings;
            if (!(settings is Group))
            {
                string json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWING, 0, 25);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FollowingList", "$(function(){ Aqufit.Page.atiFollowingList.generateStreamDom('" + json + "'); });", true);

                json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FOLLOWERS, 0, 25);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "FollowerList", "$(function(){ Aqufit.Page.atiFollowerList.generateStreamDom('" + json + "'); });", true);
            }
        }
예제 #33
0
        private void LoadChartData()
        {
            System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            // need a list of people in the group
            aqufitEntities entities = new aqufitEntities();
            long[] memberIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == GroupSettings.Id || f.DestUserSettingKey == GroupSettings.Id) && f.Relationship >= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER ).Select(f => f.SrcUserSettingKey == GroupSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            // How many members are there in the group.. this will determin how far back in time we will look for workouts
            int numMembers = memberIds.Length;
            // For now we will always look over the last 7 days..
            DateTime today = DateTime.Today;
            DateTime past = today.AddDays(-7);

            IQueryable<UserStream> streamSet = entities.UserStreamSet
                                        .Include("UserSetting").Include("WOD")
                                        .Where(w => w.Date.CompareTo(past) > 0)
                                        .Where(LinqUtils.BuildContainsExpression<UserStream, long>(w => w.UserSetting.Id, memberIds));          
            // TODO: we need to get a better idea of who is going to need hydrating before we do it.

            streamSet.Select(w => w.UserSetting).ToArray();     // THIS IS BAD.. Hydrating a lot of users profiles..
            IQueryable<IGrouping<long?, Workout>> groupWorkouts = streamSet.OfType<Workout>().GroupBy(w => w.WorkoutTypeKey);
            // Lets find out what this group is all about ... IE what type of workouts dominate
            long ukey = -1;
            long key = -1;
            int usize = 0;
            int size = 0;
            foreach (IGrouping<long?, Workout> g in groupWorkouts)
            {
                UserSettings us = g.Select(w => w.UserSetting).First();
                // first see if we can find anything that the current user is in
                if (UserSettings != null && g.FirstOrDefault(w => (long)w.UserSettingReference.EntityKey.EntityKeyValues[0].Value == UserSettings.Id) != null)
                {
                    int c = g.Count();
                    if ( c > size)
                    {
                        ukey = g.Key.Value;
                        usize = c;
                    }
                }else{
                    int c = g.Count();
                    if ( c > size)
                    {
                        key = g.Key.Value;
                        size = c;
                    }
                }
            }   
            if( ukey > 0 ){ // we found something that this user is in
                key = ukey;
                size = usize;
            }
            IGrouping<long?, Workout> workouts = groupWorkouts.Where(g => g.Key == key).FirstOrDefault();
            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
            Affine.Data.json.LeaderBoardWOD[] leaderBoard = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
            atiLeaderBoard.Visible = true;


            WODSchedule scheduled = entities.WODSchedules.Include("WOD").Where(w => w.UserSetting.Id == GroupSettings.Id).OrderByDescending(w => w.Id).FirstOrDefault();
            litTodaysWOD.Text = "<h3>Last Scheduled Workout:";
            if (scheduled != null)
            {
                WOD wod = scheduled.WOD;
                litTodaysWOD.Text += " <a style=\"font-size: 16px; color: #0095cd; font-weight: bold;\" href=\"/workouts/" + wod.Id + "\">" + wod.Name + "</a></h3>";
                Affine.WebService.StreamService ss = new WebService.StreamService();
                string jsonEveryone = ss.getStreamDataForWOD(wod.Id, -1, 0, 25, true, true, -1, -1, -1);

                string jsonYou = string.Empty;
                string js = string.Empty;
                js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromStreamData('" + jsonEveryone + "'); ";
                if (base.UserSettings != null)
                {
                    jsonYou = ss.getStreamDataForWOD(wod.Id, base.UserSettings.Id, 0, 10, true, true, -1, -1, -1);
                    js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".fromYourStreamData('" + jsonYou + "'); ";
                }


                js += " Aqufit.Page." + atiWorkoutHighChart.ID + ".drawChart(); ";

                RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page." + atiLeaderBoard.ID + ".loadLeaderBoardFromJson('" + jsSerializer.Serialize(leaderBoard) + "'); " + js + " });");
            }
            else
            {
                litTodaysWOD.Text += " <em>Unavailble</em></h3>";
                atiWorkoutHighChart.Visible = false;
            }
            // so now KEY is the most (type) of workout
            // There are now a couple special cases... (crossfit workouts)
         /*
            if (key == (int)Utils.WorkoutUtil.WorkoutType.CROSSFIT)
            {
                Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                Affine.Data.json.LeaderBoardWOD[] females = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id, "F");
                Affine.Data.json.LeaderBoardWOD[] males = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id, "M");
                atiLeaderBoardMale.Visible = true;
                atiLeaderBoardMale.LeaderWODList = males;
                atiLeaderBoardFemale.Visible = true;
                atiLeaderBoardFemale.LeaderWODList = females;
            }
            else
            {
                if (workouts != null)
                {
                    // TODO: now for some reason we can not hydrate the "UserSettings" so we need to get them now
                    long[] ids = workouts.Select(w => (long)w.UserSettingReference.EntityKey.EntityKeyValues[0].Value).ToArray();

                    // for now the other types of workout are just a quick grab...

                }
            }
          */
          //  ScriptManager.RegisterStartupScript(this, Page.GetType(), "wt", "alert('" +  jsSerializer.Serialize( title ) + "');", true);
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgLoading.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/proLoading.gif");
                    if (Settings["Configure"] != null && Convert.ToString( Settings["Configure"] ).Equals("ConfigureLists") )
                    {
                        imgAd.Src = ResolveUrl("~/images/iphoneAd.png");
                        aqufitEntities entities = new aqufitEntities();
                        if (HttpContext.Current.Items["w"] != null || Request["w"] != null)   // view a specific workouts history
                        {
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible = false;
                            atiWorkoutViewer.Visible = true;
                            atiWorkoutListPanel.Visible = false;
                            long wid = Request["w"] != null ? Convert.ToInt64(Request["w"]) : Convert.ToInt64(HttpContext.Current.Items["w"]);
                            txtRouteLink.Text = "http://flexfwd.com/"+ ProfileSettings.UserName + "/workout-history/" + wid;
                            Workout workout = entities.UserStreamSet.OfType<Workout>().FirstOrDefault(w => w.Id == wid);
                            // get all the workouts that have the same title
                            Workout[] workouts = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id && w.WorkoutTypeKey == workout.WorkoutTypeKey && w.Title == workout.Title).ToArray();
                            workoutTabTitle.Text = "&nbsp;" + workout.Title;

                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.getWokoutStreamData(base.ProfileSettings.Id, workout);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);

                            //atiStreamScript
                        }
                        else
                        {
                            atiProfileImg2.Settings = base.ProfileSettings;
                            if (ProfileSettings != null && ProfileSettings is Group)
                            {
                                RadGrid1.Visible = false;
                                RadGrid2.Visible = true;
                                atiWorkoutSelector.Visible = false;
                            }
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible = false;
                            workoutTabTitle.Text = "Workout History";
                            atiWorkoutTotals.Cols = 3;

                            // get number of workouts for each workout type
                            WorkoutType[] wtypes = entities.WorkoutType.ToArray();
                            IQueryable<Workout> workoutQuery = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name = wt.Name,
                                    Icon = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }

                        }
                    }
                    else
                    {
                        // for now if the user is not logged in they can not view stats...
                        if (UserSettings == null)
                        {
                            Response.Redirect(ResolveUrl("~/Login") + "?returnurl=" + Request.Url.ToString(), true);
                            return;
                        }

                        atiWorkoutList.Visible = false;
                        atiStatsPanel.Visible = true;

                        string requestsUrl = Convert.ToString(Settings["RequestsPage"]);
                        // cache workout types if not already done.
                        // TODO: store this in the application startup

                        // Get all the stream data for the user.
                        // TODO: cache the stream list.
                        long wId = 0;
                        if (HttpContext.Current.Items["w"] != null)
                        {
                            wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        }
                        else if (Request["w"] != null)
                        {
                            wId = Convert.ToInt64(Request["w"]);
                        }
                        if (wId == 0)
                        {
                            throw new Exception("No Workout specified");
                        }
                        aqufitEntities entities = new aqufitEntities();
                        Workout workout = entities.UserStreamSet.OfType<Workout>().Include("WOD").Include("WOD.WODType").FirstOrDefault(w => w.Id == wId);
                        atiWorkoutVisualizer.Text = GetFlexEmbed(workout);

                        // Get the 'LONG' list of past workouts (only one time)
                        const int workoutTake = 50;
                        IQueryable<IGrouping<long, Workout>> workoutHistory = entities.UserStreamSet.OfType<Workout>().Include("WOD").OrderByDescending(w => w.Id).Where(w => w.UserSetting.Id == UserSettings.Id && w.WorkoutTypeKey.HasValue).Take(workoutTake).GroupBy(w => w.WorkoutTypeKey.Value);
                        IEnumerable<Workout> workoutHistoryList = new List<Workout>();
                        foreach (IGrouping<long, Workout> wh in workoutHistory)
                        {
                            workoutHistoryList = workoutHistoryList.Concat(wh.AsEnumerable());
                        }
                        hiddenWorkoutHistory.Value = workoutHistoryList.Select(w => new {
                                                    Title = w.Title,
                                                    Id = w.Id,
                                                    Type = w.WorkoutTypeKey,
                                                    Wod = (w.WOD != null ? w.WOD.Id : -1),
                                                    Distance = w.Distance,
                                                    Score = w.Score,
                                                    Max = w.Max,
                                                    Duration = w.Duration }).OrderBy( w => w.Title).ToArray().ToJson();

                        LoadFlexDataForWorkout(workout, Utils.ConstsUtil.GraphContext.DEFAULT);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #35
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src = ResolveUrl("~/images/iphoneAd.png");

                Affine.Utils.WorkoutUtil.WorkoutType workoutType = Affine.Utils.WorkoutUtil.WorkoutType.RUNNING;
                if (Request["wt"] != null)
                {
                    workoutType = Affine.Utils.WorkoutUtil.IntToWorkoutType(Convert.ToInt32(Request["wt"]));
                }
                atiWorkoutTypes.SelectedType = workoutType;
                aqufitEntities entities     = new aqufitEntities();
                WorkoutType    selectedType = entities.WorkoutType.First(w => w.Id == (int)workoutType);
                userQuery             = entities.UserSettings.OfType <User>().Where(u => u.PortalKey == this.PortalId && !u.User2WorkoutType.Select(wt => wt.WorkoutType.Id).Contains(selectedType.Id)).OrderBy(u => u.Id).AsQueryable();
                userQueryRecentActive = userQuery.OrderByDescending(w => w.LastLoginDate);
                if (this.UserSettings != null)
                {
                    userQueryLiveNear = userQuery.Where(u => u.LngHome.HasValue && u.LngHome.HasValue).OrderBy(u => Math.Abs(u.LatHome.Value - UserSettings.LatHome.Value) + Math.Abs(u.LngHome.Value - UserSettings.LngHome.Value));
                }
                userQueryMostWatched = userQuery.Where(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS) != null).OrderByDescending(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS).MetricValue);
                IQueryable <Workout> fastWorkoutQuery = entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WorkoutTypeKey.HasValue && w.WorkoutTypeKey.Value == (int)workoutType && w.Duration.HasValue && w.Duration.Value > 0);
                if (workoutType == Utils.WorkoutUtil.WorkoutType.RUNNING)
                {
                    // metrics will be 1 mile, 5km and 10km
                    hFastTime1.InnerText = "Fastest 1 mile";
                    double mile = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.MILE_1);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= mile).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 5 km";
                    double km5 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_5);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km5).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.ROW)
                {
                    // row metrics will be fastest 500 M and 1 Km
                    hFastTime1.InnerText = "Fastest 500 M";
                    double m500 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.M_500);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= m500).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 1 km";
                    double km1 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_1);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km1).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.CROSSFIT)
                {
                    hFastTime1.InnerText = "Fran";
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Fran" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Helen";
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Helen" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);
                }

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    if (ProfileSettings != null)
                    {
                        liFindFriends.Visible       = false;
                        pageViewFindFriends.Visible = false;
                        atiProfileImg.Settings      = ProfileSettings;
                        atiProfileImg.IsOwner       = base.Permissions == AqufitPermission.OWNER;
                        atiPeoplePanel.Visible      = false;
                        atiPeopleViewer.Visible     = true;
                        peopleTabTitle.Text         = ProfileSettings.UserName + " Achievements";
                        litUserName.Text            = "<a class=\"midBlue\" href=\"" + ResolveUrl("~") + ProfileSettings.UserName + "\">" + ProfileSettings.UserName + "</a> <span> (" + ProfileSettings.UserFirstName + " " + ProfileSettings.UserLastName + ")</span>";
                        atiShareLink.ShareLink      = Request.Url.AbsoluteUri;
                        atiShareLink.ShareTitle     = ProfileSettings.UserName + " Achievements";

                        if (ProfileSettings is Group)
                        {
                            Affine.Utils.ConstsUtil.Relationships memberType = Utils.ConstsUtil.Relationships.NONE;
                            if (UserSettings != null)
                            {
                                UserFriends uf = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == UserSettings.Id && f.DestUserSettingKey == ProfileSettings.Id);
                                if (uf != null)
                                {
                                    memberType = Utils.ConstsUtil.IntToRelationship(uf.Relationship);
                                }
                            }
                            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                            atiWorkoutTotals.Visible = false;
                            nvgCrossfit.Visible      = false;
                            liConfig.Visible         = (memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER);
                            if ((memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER) && Request["c"] != null)
                            {
                                atiPeopleViewer.Visible      = false;
                                atiLeaderBoardConfig.Visible = true;
                                bool hasCustom = entities.LeaderBoard2WOD.FirstOrDefault(lb => lb.UserSetting.Id == GroupSettings.Id) != null;
                                if (hasCustom)
                                {
                                    Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                    System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                    RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2Config.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                                }
                            }
                            else
                            {
                                Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                            }
                        }
                        else
                        {
                            atiWorkoutTotals.Cols = 3;
                            // get number of workouts for each workout type
                            WorkoutType[]        wtypes       = entities.WorkoutType.ToArray();
                            IQueryable <Workout> workoutQuery = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name  = wt.Name,
                                    Icon  = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }
                            IQueryable <Workout> crossfitWorkouts = entities.UserStreamSet.OfType <Workout>().Include("WOD").Where(w => w.UserSetting.Id == ProfileSettings.Id && w.IsBest == true);
                            int numDistinct = crossfitWorkouts.Select(w => w.WOD).Distinct().Count();
                            IQueryable <Workout> wodsToDisplay = null;
                            wodsToDisplay = crossfitWorkouts.OrderByDescending(w => w.Id);
                            string baseUrl = ResolveUrl("~") + "workout/";
                            // We need to split up into WOD types now...
                            Workout[] timedWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.TIMED).OrderBy(w => w.Duration).ToArray();
                            IList <DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem> cfTotals = timedWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Affine.Utils.UnitsUtil.durationToTimeString(Convert.ToInt64(w.Duration)), Link = baseUrl + w.WOD.Id
                            }).ToList();
                            // Now all the scored ones...
                            Workout[] scoredWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.SCORE || w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.AMRAP).ToArray();
                            cfTotals = cfTotals.Concat(scoredWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Convert.ToString(w.Score), Link = baseUrl + w.WOD.Id
                            }).ToList()).ToList();
                            Workout[] maxWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT).ToArray();
                            cfTotals = cfTotals.Concat(maxWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                            {
                                Name = w.Title, Total = Affine.Utils.UnitsUtil.systemDefaultToUnits(w.Max.Value, WeightUnits) + " " + Affine.Utils.UnitsUtil.unitToStringName(WeightUnits), Link = baseUrl + w.WOD.Id
                            }).ToList()).ToList();
                            // TODO: we should have workout names link to that workout (a you vs. them kinda deal)
                            nvgCrossfit.Totals = cfTotals.OrderBy(t => t.Name).ToArray();

                            #region Achievments

                            Affine.WebService.StreamService ss = new WebService.StreamService();
                            string js = string.Empty;

                            Affine.Utils.WorkoutUtil.WorkoutType running = Utils.WorkoutUtil.WorkoutType.RUNNING;
                            Achievement[] runningAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)running && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in runningAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRunning.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType rowing = Utils.WorkoutUtil.WorkoutType.ROW;
                            Achievement[] rowingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)rowing && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in rowingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRowing.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType cycling = Utils.WorkoutUtil.WorkoutType.CYCLING;
                            Achievement[] cyclingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)cycling && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in cyclingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedCycling.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType swimming = Utils.WorkoutUtil.WorkoutType.SWIMMING;
                            Achievement[] swimmingAchievements            = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)swimming && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in swimmingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedSwimming.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }

                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "Achievements", "$(function(){" + js + " });", true);
                            #endregion
                        }
                    }
                    else
                    {
                        peopleTabTitle.Text     = "Athletes";
                        atiPeoplePanel.Visible  = true;
                        atiPeopleViewer.Visible = false;
                        SetupPage();        // do normal page setup
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #36
0
        private void SetupAccountEdit(Group group)
        {
            aqufitEntities entities = new aqufitEntities();

            group = entities.UserSettings.OfType <Group>().Include("GroupType").Include("UserSettingsExtendeds").Include("Places").FirstOrDefault(g => g.Id == GroupSettings.Id);

            hiddenGroupKey.Value = "" + GroupSettings.Id;
            UserFriends ownerId = entities.UserFriends.FirstOrDefault(f => (f.SrcUserSettingKey == group.Id || f.DestUserSettingKey == group.Id) && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.GROUP_OWNER);

            if (ownerId != null)
            {
                atiOwnerProfile.Settings = entities.UserSettings.FirstOrDefault(u => u.Id == (ownerId.SrcUserSettingKey == group.Id ? ownerId.DestUserSettingKey : ownerId.SrcUserSettingKey));
            }
            else
            {
                atiOwnerProfile.Visible = false;
            }


            // setup the Basic Info section
            txtGroupName.Text = group.UserFirstName;
            atiGroupName.Text = group.UserName;
            Place place = group.Places.FirstOrDefault();

            if (place != null)
            {
                atTxtGroupDescription.Text = place.Description;
            }
            atiGroupName.Enabled       = false;
            atiTxtGroupEmail.Text      = group.UserEmail;
            ddlGroupType.SelectedValue = "" + group.GroupType.Id;

            atiAddress.Visible = false;
            // TODO: for now we don't allow a place edit.

            /*
             * Place place = entities.Places.FirstOrDefault( p => p.UserSetting.Id == group.Id );
             * if( place != null ){
             *  atiAddress.City = place.City;
             *  atiAddress.Region = place.Region;
             *  atiAddress.
             * }
             **/
            UserSettingsExtended[] webLinks = group.UserSettingsExtendeds.Where(s => s.Class == 1).ToArray();
            UserSettingsExtended   facebook = webLinks.FirstOrDefault(w => w.Name == "Facebook");

            atiWebLinks.Facebook = facebook != null ? facebook.Value : null;
            UserSettingsExtended twitter = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Twitter");

            atiWebLinks.Twitter = twitter != null ? twitter.Value : null;
            UserSettingsExtended linkedin = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "LinkedIn");

            atiWebLinks.LinkedIn = linkedin != null ? linkedin.Value : null;
            UserSettingsExtended youtube = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "YouTube");

            atiWebLinks.YouTube = youtube != null ? youtube.Value : null;
            UserSettingsExtended flickr = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Flickr");

            atiWebLinks.Flickr = flickr != null ? flickr.Value : null;
            UserSettingsExtended personal = webLinks.FirstOrDefault(s => s.Class == 1 && s.Name == "Personal");

            atiWebLinks.Peronsal = personal != null ? personal.Value : null;


            // setup the advanced settings
            UserFriends follow = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == group.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW);

            if (follow != null)
            {
                Group           followedGroup = entities.UserSettings.OfType <Group>().FirstOrDefault(g => g.Id == follow.DestUserSettingKey);
                RadComboBoxItem item          = new RadComboBoxItem();
                item.Text  = followedGroup.UserFirstName;
                item.Value = "" + followedGroup.Id;
                atiRadComboBoxSearchGroups.Items.Add(item);
                atiRadComboBoxSearchGroups.SelectedIndex = atiRadComboBoxSearchGroups.Items.Count - 1;
            }

            // Next we do the appearance settings...
            if (!string.IsNullOrWhiteSpace(group.CssStyle))
            {
                const string findMe = "background-color:";
                int          bgInd  = group.CssStyle.IndexOf(findMe);
                if (bgInd >= 0)
                {
                    string color = group.CssStyle.Substring(bgInd + findMe.Length, group.CssStyle.IndexOf(";", bgInd + findMe.Length) - (bgInd + findMe.Length)).Replace("#", "");
                    atiThemeEditor.BackgroundColor = System.Drawing.Color.FromName("#" + color.Trim());
                }
                if (group.CssStyle.Contains("background-repeat: repeat;"))
                {
                    atiThemeEditor.IsTiled = true;
                }
            }

            // Next the member list
            Affine.WebService.StreamService ss = new WebService.StreamService();
            string json = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);

            string json2 = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);

            RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "');  Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "');  }); ");
        }
예제 #37
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src = ResolveUrl("~/images/iphoneAd.png");
                imgCheck.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png");

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgSearch.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    imgCenter.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCenter.png");
                    aqufitEntities entities = new aqufitEntities();
                    long rId = 0;
                    if (HttpContext.Current.Items["r"] != null)
                    {
                        rId = Convert.ToInt64(HttpContext.Current.Items["r"]);
                    }
                    else if (Request["r"] != null)
                    {
                        rId = Convert.ToInt64(Request["r"]);
                    }
                    else if (HttpContext.Current.Items["w"] != null)
                    {
                        long workoutId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        rId = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workoutId).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    }
                    else if (Request["w"] != null)
                    {
                        long workoutId = Convert.ToInt64(Request["w"]);
                        rId = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workoutId).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                    }
                    // Are we viewing a specific route ?
                    if (rId > 0)
                    {
                        hiddenRouteKey.Value = "" + rId;

                        MapRoute route = entities.MapRoutes.Include("UserSetting").Include("MapRoutePoints").FirstOrDefault(m => m.Id == rId);
                        if( base.UserSettings != null ){
                            bAddRoute.Visible = entities.User2MapRouteFav.FirstOrDefault(mr => mr.MapRoute.Id == route.Id && mr.UserSettingsKey == UserSettings.Id) == null;
                        }
                        Affine.Utils.UnitsUtil.MeasureUnit unit = this.UserSettings != null && this.UserSettings.DistanceUnits != null ? Affine.Utils.UnitsUtil.ToUnit( this.UserSettings.DistanceUnits.Value ) : Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES;
                        string dist = Math.Round( Affine.Utils.UnitsUtil.systemDefaultToUnits(route.RouteDistance, unit), 2 ) + " " + Affine.Utils.UnitsUtil.unitToStringName(unit);
                        lRouteTitle.Text = route.Name + " (" + dist + ")";
                        lRouteInfo.Text = "<span>A " + dist + " route posted by <a class=\"username\" href=\"/" + route.UserSetting.UserName + "\">" + route.UserSetting.UserName + "</a> on "+route.CreationDate.ToShortDateString()+"</span>";
                        double centerLat = (route.LatMax + route.LatMin) / 2;
                        double centerLng = (route.LngMax + route.LngMin) / 2;
                        atiGMapView.Lat = centerLat;
                        atiGMapView.Lng = centerLng;
                        if (route.ThumbZoom.HasValue)
                        {
                            atiGMapView.Zoom = (short)(route.ThumbZoom.Value + 2);
                        }
                        atiGMapView.Route = route;
                        atiProfileImg.Settings = route.UserSetting;
                        atiRoutePanel.Visible = false;
                        atiRouteViewer.Visible = true;

                        string js = string.Empty;

                        //js += "Affine.WebService.StreamService.GetRoutes(" + centerLat + ", " + centerLng + ", 10, 0, 5, 'distance', function (json) { ";
                        js += "Aqufit.Page.atiSimilarRouteListScript.dataBinder = function(skip, take){ \n";
                        js += "     Affine.WebService.StreamService.GetSimilarRoutes(" + rId + ", 10, skip, take, 'distance', function (json) { \n";
                        js += "         Aqufit.Page.atiSimilarRouteListScript.generateStreamDom(json); \n";
                        js += "     }); \n";
                        js += "};";
                        js += " Aqufit.Page.atiSimilarRouteListScript.dataBinder(0,5); ";
                        atiShareLink.ShareLink = "http://"+Request.Url.Host + "/route/" + route.Id;
                        atiShareLink.ShareTitle = "FlexFWD.com Mapped Route: \"" + route.Name +"\"";

                        routeTabTitle.Text = "&nbsp;" + (string.IsNullOrWhiteSpace(route.Name) ? "Untitled" : route.Name);

                        Affine.WebService.StreamService ss = new WebService.StreamService();
                        string json = ss.getStreamDataForRoute(route.Id, 0, 5);
                        //generateStreamDom

                        ScriptManager.RegisterStartupScript(this, Page.GetType(), "SimilarRouteList", "$(function(){ " + js + " Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);
                    }
                    else
                    {
                        if (Settings["Configure"] != null && Convert.ToString( Settings["Configure"] ).Equals("ConfigureMyRoutes") )
                        {
                            atiMyRoutePanel.Visible = true;
                            mapContainer.Visible = false;
                            atiRoutePanel.Visible = true;
                            routeTabTitle.Text = "My Routes";
                            liMyRoutes.Visible = false;
                            liFindRoute.Visible = true;
                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.GetMyRoutes(base.UserSettings.Id, 0, 10, "date");
                            string js = string.Empty;
                            //js += "Affine.WebService.StreamService.GetRoutes(" + centerLat + ", " + centerLng + ", 10, 0, 5, 'distance', function (json) { ";
                            js += "$(function(){ Aqufit.Page.atiRouteListScript.isMyRoutes = true; Aqufit.Page.atiRouteListScript.generateStreamDom('" + json + "'); \n";
                            js += "     Aqufit.Page.atiRouteListScript.dataBinder = function(skip, take){ \n";
                            js += "         Affine.WebService.StreamService.GetMyRoutes(" + base.UserSettings.Id + ", skip, take, 'date', function (json) { \n";
                            js += "             Aqufit.Page.atiRouteListScript.generateStreamDom(json); \n";
                            js += "         }); \n";
                            js += "     } \n";
                            js += " }); \n";

                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "RouteList", js, true);
                        }
                        else
                        {
                            routeTabTitle.Text = "Routes";
                            atiRoutePanel.Visible = true;
                            atiRouteViewer.Visible = false;
                            SetupPage();        // do normal page setup
                        }

                    }
                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #38
0
 private void SetupPageFriendMode()
 {
     atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_LIST;
     WebService.StreamService streamService = new WebService.StreamService();
     UserSettings settings = ProfileSettings != null ? ProfileSettings : UserSettings;
     if (settings is Group)
     {
         if (this.UserSettings.Id != settings.Id)
         {
             atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_REQUEST;
         }
         tabFollowing.Visible = pageViewFollowing.Visible = false;
         tabFollowers.Visible = pageViewFollowers.Visible = false;
         string json = streamService.getMemberListData(settings.Id, 0, 25, this.UserSettings.Id);
         ScriptManager.RegisterStartupScript(this, Page.GetType(), "FriendList", "$(function(){ Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); });", true);
     }
     else
     {
         if (this.UserSettings.Id != settings.Id)
         {
             atiFriendListScript.ControlMode = DesktopModules_ATI_Base_controls_ATI_FriendListScript.Mode.FRIEND_REQUEST;
         }
         string json = streamService.getFriendListData(settings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, 0, 25, this.UserSettings.Id);
         ScriptManager.RegisterStartupScript(this, Page.GetType(), "FriendList", "$(function(){ Aqufit.Page.atiFriendListScript.generateStreamDom('" + json + "'); });", true);
     }
 }
 protected void atiAddRemFav_Click(object sender, ImageClickEventArgs e)
 {
     if (this.UserId > 0)
     {   // Is this user Loged in ?
         aqufitEntities entities = new aqufitEntities();
         User2StreamFavorites rFav = entities.User2StreamFavorites.FirstOrDefault(f => f.UserKey == this.UserId && f.PortalKey == this.PortalId && f.UserStream.Id == this.RecipeId);
         if (rFav == null)
         {
             Affine.WebService.StreamService service = new WebService.StreamService();
             string ret = service.addStreamToFavorites(this.UserId, this.PortalId, this.RecipeId);
             if (!ret.Contains("success"))
             {
                 litStatus.Text = ret;
             }
             else
             {
                 litStatus.Text = "SUCCESS. Recipe has been added to your favorites.";
             }
         }
         else
         {
             entities.DeleteObject(rFav);
             entities.SaveChanges();
             litStatus.Text = "Boom. Recipe has been removed from your favorites.";
         }
         RadAjaxManager1.ResponseScripts.Add("$('#atiFavContainer').fadeOut('slow');");
     }
     else
     {  // otherwise jump to a login
         RadAjaxManager1.ResponseScripts.Add("self.location.href= Aqufit.Page.LoginUrl + \"?ReturnUrl=\" + self.location.href;");
     }
 }
예제 #40
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx")+"?u=-1&p=0&bg=1";
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    baseUrl = ResolveUrl("~/");
                    aqufitEntities entities = new aqufitEntities();
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                    if (GroupSettings != null || (UserSettings != null && UserSettings.MainGroupKey.HasValue))
                    {
                        tabMyGroupComps.Visible = true;
                        pageMyGroupComps.Visible = true;
                      //  if (GroupSettings != null)
                     //   {
                   //         RadAjaxManager1.ResponseScripts.Add("Aqufit.addLoadEvent(function(){ Aqufit.Page.Tabs.SwitchTab(1); });");
                 //       }
                    }

                    Group taranis = entities.UserSettings.OfType<Group>().FirstOrDefault(g => g.Id == 511); ;
                    atiFGProfileImg.Settings = taranis;
                    hrefGroupLink2.HRef = baseUrl + "group/" + taranis.UserName;
                    imgSearch.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iSearch.png");
                    if (GroupSettings == null)
                    {       // Let people search for a group in this case..
                        atiGroupListPanel.Visible = true;

                        if (this.UserSettings != null && (this.UserSettings.LatHome != null && this.UserSettings.LatHome.Value > 0.0))
                        {
                            atiGMap.Lat = this.UserSettings.LatHome.Value;
                            atiGMap.Lng = this.UserSettings.LngHome.Value;
                            atiGMap.Zoom = 13;
                        }
                        imgAd.Src = ResolveUrl("~/portals/0/images/adTastyPaleo.jpg");
                        WebService.StreamService streamService = new WebService.StreamService();
                       // string search = streamService.searchGroupListData(PortalId, null, 0, 15);

                        // we need to setup for a location based group search
                       // ScriptManager.RegisterStartupScript(this, Page.GetType(), "GroupSearch", "$(function(){ Aqufit.Page.atiGroupSearch.generateStreamDom('" + search + "'); });", true);
                    }
                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #41
0
 protected void bAjaxPostback_Click(object sender, EventArgs e)
 {
     try
     {
         Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
         Affine.WebService.StreamService ss = new WebService.StreamService();
         long mid = 0;
         long gid = Convert.ToInt64(hiddenGroupKey.Value);;
         switch (hiddenAjaxAction.Value)
         {
             case "makeAdmin":
                 mid = Convert.ToInt64(hiddenAjaxValue.Value);
                 dataMan.makeMemberGroupAdmin(UserSettings.Id, gid, mid);
                 string json = ss.getMemberListDataOfRelationship(gid, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);
                 RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "'); ");
                 break;
             case "removeAdmin":
                 mid = Convert.ToInt64(hiddenAjaxValue.Value);
                 dataMan.removeMemberGroupAdmin(UserSettings.Id, gid, mid);
                 string json2 = ss.getMemberListDataOfRelationship(gid, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);
                 RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "'); ");
                 break;
             case "removeMember":
                 mid = Convert.ToInt64(hiddenAjaxValue.Value);
                 dataMan.removeMemberGroup(UserSettings.Id, gid, mid);
                 break;
             case "sendGroupInvite":
                 long usid = Convert.ToInt64(hiddenAjaxValue.Value);
                 dataMan.inviteUserToGroup(usid, gid);
                 break;
             case "friendData":
                 int skip = Convert.ToInt32(hiddenAjaxValue.Value);
                 int take = Convert.ToInt32(hiddenAjaxValue2.Value);
                 json = ss.getFriendListData(UserSettings.UserKey, this.PortalId, Affine.Utils.ConstsUtil.FriendListModes.FRIEND, skip, take, gid);
                 RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.atiFriendList.generateStreamDom('" + json + "'); Aqufit.Page.atiLoading.remove(); ");
                 break;
         }
     }
     catch (Exception ex)
     {
         RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog('" + ex.Message.Replace("'","") + "'); ");
     }
 }
예제 #42
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);
                imgAd.Src = ResolveUrl("~/images/iphoneAd.png");

                Affine.Utils.WorkoutUtil.WorkoutType workoutType = Affine.Utils.WorkoutUtil.WorkoutType.RUNNING;
                if (Request["wt"] != null)
                {
                    workoutType = Affine.Utils.WorkoutUtil.IntToWorkoutType(Convert.ToInt32(Request["wt"]));
                }
                atiWorkoutTypes.SelectedType = workoutType;
                aqufitEntities entities = new aqufitEntities();
                WorkoutType selectedType = entities.WorkoutType.First(w => w.Id == (int)workoutType);
                userQuery = entities.UserSettings.OfType<User>().Where(u => u.PortalKey == this.PortalId && !u.User2WorkoutType.Select( wt => wt.WorkoutType.Id ).Contains(selectedType.Id)).OrderBy(u => u.Id).AsQueryable();
                userQueryRecentActive = userQuery.OrderByDescending(w => w.LastLoginDate);
                if (this.UserSettings != null)
                {
                    userQueryLiveNear = userQuery.Where( u => u.LngHome.HasValue && u.LngHome.HasValue ).OrderBy(u => Math.Abs(u.LatHome.Value - UserSettings.LatHome.Value) + Math.Abs(u.LngHome.Value - UserSettings.LngHome.Value));
                }
                userQueryMostWatched = userQuery.Where(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS) != null ).OrderByDescending(u => u.Metrics.FirstOrDefault(m => m.MetricType == (int)Affine.Utils.MetricUtil.MetricType.NUM_FOLLOWERS).MetricValue);
                IQueryable<Workout> fastWorkoutQuery = entities.UserStreamSet.Include("UserSettings").OfType<Workout>().Where(w => w.WorkoutTypeKey.HasValue && w.WorkoutTypeKey.Value == (int)workoutType && w.Duration.HasValue && w.Duration.Value > 0 );
                if (workoutType == Utils.WorkoutUtil.WorkoutType.RUNNING)
                {
                    // metrics will be 1 mile, 5km and 10km
                    hFastTime1.InnerText = "Fastest 1 mile";
                    double mile = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.MILE_1);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= mile).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 5 km";
                    double km5 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_5);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km5).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.ROW)
                {
                    // row metrics will be fastest 500 M and 1 Km
                    hFastTime1.InnerText = "Fastest 500 M";
                    double m500 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.M_500);
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.Distance >= m500).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Fastest 1 km";
                    double km1 = Affine.Utils.UnitsUtil.distanceMetricToDistance(Utils.UnitsUtil.DistanceMetric.KM_1);
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.Distance >= km1).OrderBy(w => w.Duration);
                }
                else if (workoutType == Utils.WorkoutUtil.WorkoutType.CROSSFIT)
                {
                    hFastTime1.InnerText = "Fran";
                    workoutQueryFastest1 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Fran" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);

                    hFastTime2.InnerText = "Helen";
                    workoutQueryFastest2 = fastWorkoutQuery.Where(w => w.WOD.Standard > 0 && w.WOD.Name == "Helen" && w.RxD.HasValue && w.RxD.Value).OrderBy(w => w.Duration);
                }

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    if (ProfileSettings != null)
                    {
                        liFindFriends.Visible = false;
                        pageViewFindFriends.Visible = false;
                        atiProfileImg.Settings = ProfileSettings;
                        atiProfileImg.IsOwner = base.Permissions == AqufitPermission.OWNER;
                        atiPeoplePanel.Visible = false;
                        atiPeopleViewer.Visible = true;
                        peopleTabTitle.Text = ProfileSettings.UserName + " Achievements";
                        litUserName.Text = "<a class=\"midBlue\" href=\"" + ResolveUrl("~") + ProfileSettings.UserName+ "\">" + ProfileSettings.UserName + "</a> <span> (" + ProfileSettings.UserFirstName + " " + ProfileSettings.UserLastName + ")</span>";
                        atiShareLink.ShareLink = Request.Url.AbsoluteUri;
                        atiShareLink.ShareTitle = ProfileSettings.UserName + " Achievements";

                        if (ProfileSettings is Group)
                        {
                            Affine.Utils.ConstsUtil.Relationships memberType = Utils.ConstsUtil.Relationships.NONE;
                            if (UserSettings != null)
                            {
                                UserFriends uf = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == UserSettings.Id && f.DestUserSettingKey == ProfileSettings.Id);
                                if (uf != null)
                                {
                                    memberType = Utils.ConstsUtil.IntToRelationship(uf.Relationship);
                                }
                            }
                            Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                            atiWorkoutTotals.Visible = false;
                            nvgCrossfit.Visible = false;
                            liConfig.Visible = (memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER);
                            if ((memberType == Utils.ConstsUtil.Relationships.GROUP_ADMIN || memberType == Utils.ConstsUtil.Relationships.GROUP_OWNER) && Request["c"] != null)
                            {
                                atiPeopleViewer.Visible = false;
                                atiLeaderBoardConfig.Visible = true;
                                bool hasCustom = entities.LeaderBoard2WOD.FirstOrDefault(lb => lb.UserSetting.Id == GroupSettings.Id) != null;
                                if (hasCustom)
                                {
                                    Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                    System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                    RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2Config.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                                }
                            }
                            else
                            {
                                Affine.Data.json.LeaderBoardWOD[] all = dataMan.CalculatCrossFitLeaderBoard(base.GroupSettings.Id);
                                System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
                                RadAjaxManager1.ResponseScripts.Add("$(function(){ Aqufit.Page." + atiLeaderBoard2.ID + ".loadLeaderBoardFromJson('" + jsSerial.Serialize(all) + "'); });");
                            }
                        }
                        else
                        {
                            atiWorkoutTotals.Cols = 3;
                            // get number of workouts for each workout type
                            WorkoutType[] wtypes = entities.WorkoutType.ToArray();
                            IQueryable<Workout> workoutQuery = entities.UserStreamSet.OfType<Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name = wt.Name,
                                    Icon = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }
                            IQueryable<Workout> crossfitWorkouts = entities.UserStreamSet.OfType<Workout>().Include("WOD").Where(w => w.UserSetting.Id == ProfileSettings.Id && w.IsBest == true);
                            int numDistinct = crossfitWorkouts.Select(w => w.WOD).Distinct().Count();
                            IQueryable<Workout> wodsToDisplay = null;
                            wodsToDisplay = crossfitWorkouts.OrderByDescending(w => w.Id);
                            string baseUrl = ResolveUrl("~") + "workout/";
                            // We need to split up into WOD types now...
                            Workout[] timedWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.TIMED).OrderBy(w => w.Duration).ToArray();
                            IList<DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem> cfTotals = timedWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem() { Name = w.Title, Total = Affine.Utils.UnitsUtil.durationToTimeString(Convert.ToInt64(w.Duration)), Link = baseUrl + w.WOD.Id }).ToList();
                            // Now all the scored ones...
                            Workout[] scoredWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.SCORE || w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.AMRAP ).ToArray();
                            cfTotals = cfTotals.Concat(scoredWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem() { Name = w.Title, Total = Convert.ToString(w.Score), Link = baseUrl + w.WOD.Id }).ToList()).ToList();
                            Workout[] maxWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT).ToArray();
                            cfTotals = cfTotals.Concat(maxWods.Select(w => new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem() { Name = w.Title, Total = Affine.Utils.UnitsUtil.systemDefaultToUnits(w.Max.Value, WeightUnits) + " " + Affine.Utils.UnitsUtil.unitToStringName(WeightUnits), Link = baseUrl + w.WOD.Id }).ToList()).ToList();
                            // TODO: we should have workout names link to that workout (a you vs. them kinda deal)
                            nvgCrossfit.Totals = cfTotals.OrderBy(t => t.Name).ToArray();

                            #region Achievments

                            Affine.WebService.StreamService ss = new WebService.StreamService();
                            string js = string.Empty;

                            Affine.Utils.WorkoutUtil.WorkoutType running = Utils.WorkoutUtil.WorkoutType.RUNNING;
                            Achievement[] runningAchievements = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)running && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in runningAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRunning.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType rowing = Utils.WorkoutUtil.WorkoutType.ROW;
                            Achievement[] rowingAchievements = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)rowing && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in rowingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedRowing.addItem('" + json + "','" + a.AchievementType.Name + "'); ";

                            }
                            Affine.Utils.WorkoutUtil.WorkoutType cycling = Utils.WorkoutUtil.WorkoutType.CYCLING;
                            Achievement[] cyclingAchievements = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)cycling && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in cyclingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedCycling.addItem('" + json + "','" + a.AchievementType.Name + "'); ";
                            }
                            Affine.Utils.WorkoutUtil.WorkoutType swimming = Utils.WorkoutUtil.WorkoutType.SWIMMING;
                            Achievement[] swimmingAchievements = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Include("AchievementType").Where(a => a.AchievementType.WorkoutType.Id == (int)swimming && a.UserSetting.Id == ProfileSettings.Id).OrderBy(a => a.AchievementType.DistanceRangeA).ToArray();
                            foreach (Achievement a in swimmingAchievements)
                            {
                                string json = ss.getStreamData((Workout)a.UserStream);
                                js += "Aqufit.Page.atiFeaturedSwimming.addItem('" + json + "','" + a.AchievementType.Name + "'); ";

                            }

                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "Achievements", "$(function(){" + js + " });", true);
                            #endregion
                        }
                    }
                    else
                    {
                        peopleTabTitle.Text = "Athletes";
                        atiPeoplePanel.Visible = true;
                        atiPeopleViewer.Visible = false;
                        SetupPage();        // do normal page setup
                    }
                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #43
0
        private void UpdateGroup()
        {
            if (Page.IsValid)
            {
                try
                {
                    // check required fields
                    aqufitEntities entities = new aqufitEntities();
                    Group group = entities.UserSettings.OfType<Group>().Include("GroupType").Include("UserSettingsExtendeds").Include("Places").FirstOrDefault(g => g.Id == GroupSettings.Id);

                    group.UserEmail = atiTxtGroupEmail.Text;
                    group.UserFirstName = txtGroupName.Text;
                    Place place = group.Places.FirstOrDefault();
                    if (place != null)
                    {
                        place.Description = atTxtGroupDescription.Text;
                    }
                    int gtype = Convert.ToInt32(ddlGroupType.SelectedValue);

                    group.GroupType = entities.GroupTypes.FirstOrDefault(gt => gt.Id == gtype);

                    long followId = 0;
                    if (!string.IsNullOrWhiteSpace(atiRadComboBoxSearchGroups.SelectedValue))
                    {
                        followId = Convert.ToInt64(atiRadComboBoxSearchGroups.SelectedValue);

                    }
                    // first check if the group is following any other group;
                    UserFriends follow = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == group.Id && f.Relationship == (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW);
                    if (follow != null)
                    {
                        // make sure it is a valid group ..
                        Group test = entities.UserSettings.OfType<Group>().FirstOrDefault(g => g.Id == followId);
                        // just update the follow refrence ...
                        if (test != null)
                        {
                            follow.DestUserSettingKey = followId;
                        }
                    }
                    else
                    {
                        // make sure it is a valid group ..
                        Group test = entities.UserSettings.OfType<Group>().FirstOrDefault(g => g.Id == followId);
                        // just update the follow refrence ...
                        if (test != null)
                        {
                            UserFriends followGroup = new UserFriends()
                            {
                                SrcUserSettingKey = group.Id,
                                DestUserSettingKey = test.Id,
                                Relationship = (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW
                            };
                            entities.AddToUserFriends(followGroup);
                        }
                    }

                    #region WebLinks settings
                    UserSettingsExtended[] webLinks = group.UserSettingsExtendeds.Where(s => s.Class == 1).ToArray();
                    if (atiWebLinks.Visible)
                    {
                        // Facebook
                        UserSettingsExtended facebook = webLinks.FirstOrDefault(s => s.Name == "Facebook");
                        if (!string.IsNullOrEmpty(atiWebLinks.Facebook))
                        {
                            if (facebook == null)
                            {
                                facebook = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "Facebook",
                                    Value = atiWebLinks.Facebook
                                };
                                group.UserSettingsExtendeds.Add(facebook);
                            }
                            else
                            {
                                facebook.Value = atiWebLinks.Facebook;
                            }
                        }
                        else if (facebook != null)
                        {
                            entities.DeleteObject(facebook);
                        }

                        // Twitter
                        UserSettingsExtended twitter = webLinks.FirstOrDefault(s => s.Name == "Twitter");
                        if (!string.IsNullOrEmpty(atiWebLinks.Twitter))
                        {
                            if (twitter == null)
                            {
                                twitter = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "Twitter",
                                    Value = atiWebLinks.Twitter
                                };
                                group.UserSettingsExtendeds.Add(twitter);
                            }
                            else
                            {
                                twitter.Value = atiWebLinks.Twitter;
                            }
                        }
                        else if (twitter != null)
                        {
                            entities.DeleteObject(twitter);
                        }

                        // YouTube
                        UserSettingsExtended youtube = webLinks.FirstOrDefault(s => s.Name == "YouTube");
                        if (!string.IsNullOrEmpty(atiWebLinks.YouTube))
                        {

                            if (youtube == null)
                            {
                                youtube = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "YouTube",
                                    Value = atiWebLinks.YouTube
                                };
                                group.UserSettingsExtendeds.Add(youtube);
                            }
                            else
                            {
                                youtube.Value = atiWebLinks.YouTube;
                            }
                        }
                        else if (youtube != null)
                        {
                            entities.DeleteObject(youtube);
                        }

                        // LinkedIn
                        UserSettingsExtended linkedin = webLinks.FirstOrDefault(s => s.Name == "LinkedIn");
                        if (!string.IsNullOrEmpty(atiWebLinks.LinkedIn))
                        {
                            if (linkedin == null)
                            {
                                linkedin = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "LinkedIn",
                                    Value = atiWebLinks.LinkedIn
                                };
                                group.UserSettingsExtendeds.Add(linkedin);
                            }
                            else
                            {
                                linkedin.Value = atiWebLinks.LinkedIn;
                            }
                        }
                        else if (linkedin != null)
                        {
                            entities.DeleteObject(linkedin);
                        }

                        // Flickr
                        UserSettingsExtended flickr = webLinks.FirstOrDefault(s => s.Name == "Flickr");
                        if (!string.IsNullOrEmpty(atiWebLinks.Flickr))
                        {
                            if (flickr == null)
                            {
                                flickr = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "Flickr",
                                    Value = atiWebLinks.Flickr
                                };
                                group.UserSettingsExtendeds.Add(flickr);
                            }
                            else
                            {
                                flickr.Value = atiWebLinks.Flickr;
                            }
                        }
                        else if (flickr != null)
                        {
                            entities.DeleteObject(flickr);
                        }

                        // Personal
                        UserSettingsExtended personal = webLinks.FirstOrDefault(s => s.Name == "Personal");
                        if (!string.IsNullOrEmpty(atiWebLinks.Peronsal))
                        {
                            if (personal == null)
                            {
                                personal = new UserSettingsExtended()
                                {
                                    Class = 1,
                                    Name = "Personal",
                                    Value = atiWebLinks.Peronsal
                                };
                                group.UserSettingsExtendeds.Add(personal);
                            }
                            else
                            {
                                personal.Value = atiWebLinks.Peronsal;
                            }
                        }
                        else if (personal != null)
                        {
                            entities.DeleteObject(personal);
                        }

                    }
                    #endregion

                    UploadThemeBackground();
                    group.CssStyle = string.Empty;

                    if( !atiThemeEditor.BackgroundColor.IsEmpty )
                    {
                        group.CssStyle += "background-color: #" + atiThemeEditor.BackgroundColor.Name.Substring(2)+";";
                    }
                    if (atiThemeEditor.IsTiled)
                    {
                        group.CssStyle += "background-repeat: repeat;";
                    }else{
                        group.CssStyle += "background-repeat:no-repeat; background-attachment:fixed;";
                    }
                    this.BackgroundImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?u=" + group.UserKey + "&p=" + group.PortalKey + "&bg=1";
                    this.ProfileCSS = group.CssStyle;

                    entities.SaveChanges();

                    // Next the member list
                    Affine.WebService.StreamService ss = new WebService.StreamService();
                    string json = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN, 0, 10);
                    string json2 = ss.getMemberListDataOfRelationship(GroupSettings.Id, (int)Affine.Utils.ConstsUtil.Relationships.GROUP_MEMBER, 0, 25);
                    RadAjaxManager1.ResponseScripts.Add(" $(function(){ Aqufit.Page.atiMemberListAdmin.generateStreamDom('" + json + "');  Aqufit.Page.atiMemberList.generateStreamDom('" + json2 + "');  }); ");
                }
                catch (Exception ex)
                {
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\""+ex.Message.Replace("'","")+"\"}');");
                }

            }
            else
            {
                RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog.open('{\"html\":\"\"}');");
            }
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            base.Page_Load(sender, e);
            try
            {
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    imgLoading.Src = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/proLoading.gif");
                    if (Settings["Configure"] != null && Convert.ToString(Settings["Configure"]).Equals("ConfigureLists"))
                    {
                        imgAd.Src = ResolveUrl("~/images/iphoneAd.png");
                        aqufitEntities entities = new aqufitEntities();
                        if (HttpContext.Current.Items["w"] != null || Request["w"] != null)   // view a specific workouts history
                        {
                            atiWorkoutList.Visible      = true;
                            atiStatsPanel.Visible       = false;
                            atiWorkoutViewer.Visible    = true;
                            atiWorkoutListPanel.Visible = false;
                            long wid = Request["w"] != null?Convert.ToInt64(Request["w"]) : Convert.ToInt64(HttpContext.Current.Items["w"]);

                            txtRouteLink.Text = "http://flexfwd.com/" + ProfileSettings.UserName + "/workout-history/" + wid;
                            Workout workout = entities.UserStreamSet.OfType <Workout>().FirstOrDefault(w => w.Id == wid);
                            // get all the workouts that have the same title
                            Workout[] workouts = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id && w.WorkoutTypeKey == workout.WorkoutTypeKey && w.Title == workout.Title).ToArray();
                            workoutTabTitle.Text = "&nbsp;" + workout.Title;

                            WebService.StreamService streamService = new WebService.StreamService();
                            string json = streamService.getWokoutStreamData(base.ProfileSettings.Id, workout);
                            ScriptManager.RegisterStartupScript(this, Page.GetType(), "WorkoutList", "$(function(){ Aqufit.Page.atiStreamScript.generateStreamDom('" + json + "'); });", true);

                            //atiStreamScript
                        }
                        else
                        {
                            atiProfileImg2.Settings = base.ProfileSettings;
                            if (ProfileSettings != null && ProfileSettings is Group)
                            {
                                RadGrid1.Visible           = false;
                                RadGrid2.Visible           = true;
                                atiWorkoutSelector.Visible = false;
                            }
                            atiWorkoutList.Visible = true;
                            atiStatsPanel.Visible  = false;
                            workoutTabTitle.Text   = "Workout History";
                            atiWorkoutTotals.Cols  = 3;

                            // get number of workouts for each workout type
                            WorkoutType[]        wtypes       = entities.WorkoutType.ToArray();
                            IQueryable <Workout> workoutQuery = entities.UserStreamSet.OfType <Workout>().Where(w => w.UserSetting.Id == ProfileSettings.Id);
                            foreach (WorkoutType wt in wtypes)
                            {
                                atiWorkoutTotals.Totals.Add(new DesktopModules_ATI_Base_controls_ATI_NameValueGrid.TotalItem()
                                {
                                    Name  = wt.Name,
                                    Icon  = wt.Icon,
                                    Total = "" + workoutQuery.Where(w => w.WorkoutTypeKey == wt.Id).Count()
                                });
                            }
                        }
                    }
                    else
                    {
                        // for now if the user is not logged in they can not view stats...
                        if (UserSettings == null)
                        {
                            Response.Redirect(ResolveUrl("~/Login") + "?returnurl=" + Request.Url.ToString(), true);
                            return;
                        }

                        atiWorkoutList.Visible = false;
                        atiStatsPanel.Visible  = true;

                        string requestsUrl = Convert.ToString(Settings["RequestsPage"]);
                        // cache workout types if not already done.
                        // TODO: store this in the application startup

                        // Get all the stream data for the user.
                        // TODO: cache the stream list.
                        long wId = 0;
                        if (HttpContext.Current.Items["w"] != null)
                        {
                            wId = Convert.ToInt64(HttpContext.Current.Items["w"]);
                        }
                        else if (Request["w"] != null)
                        {
                            wId = Convert.ToInt64(Request["w"]);
                        }
                        if (wId == 0)
                        {
                            throw new Exception("No Workout specified");
                        }
                        aqufitEntities entities = new aqufitEntities();
                        Workout        workout  = entities.UserStreamSet.OfType <Workout>().Include("WOD").Include("WOD.WODType").FirstOrDefault(w => w.Id == wId);
                        atiWorkoutVisualizer.Text = GetFlexEmbed(workout);

                        // Get the 'LONG' list of past workouts (only one time)
                        const int workoutTake = 50;
                        IQueryable <IGrouping <long, Workout> > workoutHistory = entities.UserStreamSet.OfType <Workout>().Include("WOD").OrderByDescending(w => w.Id).Where(w => w.UserSetting.Id == UserSettings.Id && w.WorkoutTypeKey.HasValue).Take(workoutTake).GroupBy(w => w.WorkoutTypeKey.Value);
                        IEnumerable <Workout> workoutHistoryList = new List <Workout>();
                        foreach (IGrouping <long, Workout> wh in workoutHistory)
                        {
                            workoutHistoryList = workoutHistoryList.Concat(wh.AsEnumerable());
                        }
                        hiddenWorkoutHistory.Value = workoutHistoryList.Select(w => new {
                            Title    = w.Title,
                            Id       = w.Id,
                            Type     = w.WorkoutTypeKey,
                            Wod      = (w.WOD != null ? w.WOD.Id : -1),
                            Distance = w.Distance,
                            Score    = w.Score,
                            Max      = w.Max,
                            Duration = w.Duration
                        }).OrderBy(w => w.Title).ToArray().ToJson();

                        LoadFlexDataForWorkout(workout, Utils.ConstsUtil.GraphContext.DEFAULT);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #45
0
        protected void bSaveRecipe_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    // TODO: category tags..
                    long rid = Convert.ToInt64(atHiddenRecipeId.Value);
                    if (rid > 0)
                    {
                        aqufitEntities entities = new aqufitEntities();
                        Recipe         r        = entities.UserStreamSet.OfType <Recipe>().FirstOrDefault(s => s.Id == rid && s.UserSetting.UserKey == this.UserId && s.UserSetting.PortalKey == this.PortalId);
                        if (r == null)  // security exception
                        {
                            // TODO: send a notification email
                            throw new Exception("Security Exception:  User does not own data.  Action has been logged");
                        }
                    }
                    string[] ingredients = atiRecipeIngredients.Text.Split('\n');
                    Affine.Data.json.RecipeIngredient[] riArray = ingredients.Where(i => !string.IsNullOrEmpty(i)).Select(i => new Affine.Data.json.RecipeIngredient()
                    {
                        Name = i
                    }).ToArray();

                    Affine.Data.json.RecipeExtended re = new Data.json.RecipeExtended()
                    {
                        Directions  = atiRecipeDirections.Text,
                        Ingredients = riArray
                    };
                    // TODO: Ingredients
                    string   extraTags   = string.Empty;
                    CheckBox cbBreakfast = (CheckBox)atiRecipeCategoriesPanel.FindControl("breakfast");
                    if (cbBreakfast.Checked)
                    {
                        extraTags += "," + cbBreakfast.Text;
                    }
                    CheckBox cbLunch = (CheckBox)atiRecipeCategoriesPanel.FindControl("lunch");
                    if (cbLunch.Checked)
                    {
                        extraTags += "," + cbLunch.Text;
                    }
                    CheckBox cbDinner = (CheckBox)atiRecipeCategoriesPanel.FindControl("dinner");
                    if (cbDinner.Checked)
                    {
                        extraTags += "," + cbDinner.Text;
                    }
                    CheckBox cbSnack = (CheckBox)atiRecipeCategoriesPanel.FindControl("snack");
                    if (cbSnack.Checked)
                    {
                        extraTags += "," + cbSnack.Text;
                    }
                    CheckBox cbDessert = (CheckBox)atiRecipeCategoriesPanel.FindControl("dessert");
                    if (cbDessert.Checked)
                    {
                        extraTags += "," + cbDessert.Text;
                    }
                    Affine.Data.json.StreamData recipe = new Data.json.StreamData()
                    {
                        Id             = rid,
                        Title          = atiRecipeName.Text,
                        Description    = atiRecipeDescription.Text,
                        AvrRating      = Convert.ToDouble(atiHiddenRecipeRate.Value),
                        AvrStrictness  = Convert.ToDouble(atiHiddenRecipeStrict.Value),
                        Tags           = atiRecipeTags.Text + extraTags,
                        NumServings    = Convert.ToInt32(atiRecipeServings.Text),
                        TimePrep       = Convert.ToInt32(atiRecipePrep.Text),
                        TimeCook       = Convert.ToInt32(atiRecipeCook.Text),
                        RecipeExtended = re
                    };

                    Affine.WebService.StreamService service = new WebService.StreamService();
                    long id = service.SaveRecipe(this.UserId, this.PortalId, recipe);
                    // long id = 0;
                    litStatus.Text = "<em>SUCESS</em> Your recipe has been saved.  To Finish attach some image files then press 'done'.";
                    RadAjaxManager1.ResponseScripts.Add(" Paleo.AddMedia(" + id + "); ");
                }
            }
            catch (Exception ex)
            {
                litStatus.Text = "<span style=\"color: red;\"><em>FAIL</em> " + ex.Message + "</span>";
                RadAjaxManager1.ResponseScripts.Add(" Paleo.OnFail(); ");
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // CA - this will need to be cleaned up a lot.. but here is the iteration one version
        // ** People can view workouts in 4 modes (everyone, watchlist, friends, just them)
        //     -In the case of running, cycling, swimming, and STANDARD crossfit Wods... we are going to
        //      be storing peoples best times for (distance rnages) and standard wods... so in these cases
        //      we can shorted the query time when we do an "everyone" query
        //     -Watch list and friends we do the work of getting every time that person did the workout.. not just
        //      there best times.
        //     -Same for the (you only) view
        //

        private void LoadFlexDataForWorkout(Workout workout, Affine.Utils.ConstsUtil.GraphContext context)
        {
            Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            // onload we send friend, watch, and group member data that is needed to the app
            aqufitEntities entities  = new aqufitEntities();
            IList <long>   friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id)).Select(f => (f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToList();

            friendIds.Add(ProfileSettings.Id);

            // send the persons profile through
            var profile = new { UserName = ProfileSettings.UserName, Id = ProfileSettings.Id, FirstName = ProfileSettings.UserFirstName, LastName = ProfileSettings.UserLastName };

            hiddenProfileJson.Value = serializer.Serialize(profile);

            var friends = entities.UserSettings.OfType <User>().Where(LinqUtils.BuildContainsExpression <User, long>(s => s.Id, friendIds)).Select(u => new { Id = u.Id, Un = u.UserName, Fn = u.UserFirstName, Ln = u.UserLastName }).ToArray();

            hiddenFriendJson.Value = serializer.Serialize(friends);
            // get groups
            long[]         groupIds  = entities.UserFriends.Where(f => (f.SrcUserSettingKey == ProfileSettings.Id || f.DestUserSettingKey == ProfileSettings.Id) && f.Relationship > 0).Select(f => f.SrcUserSettingKey == ProfileSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey).ToArray();
            UserSettings[] groupList = entities.UserSettings.OfType <Group>().Where(LinqUtils.BuildContainsExpression <UserSettings, long>(us => us.Id, groupIds)).OrderBy(f => f.UserName).ToArray();
            var            groups    = entities.UserSettings.OfType <Group>().Where(LinqUtils.BuildContainsExpression <Group, long>(s => s.Id, groupIds)).Select(u => new { Id = u.Id, Un = u.UserName }).ToArray();

            hiddenGroupJson.Value = serializer.Serialize(groups);
            // next we load the workout compare to all (friends)

            Affine.WebService.StreamService ss = new WebService.StreamService();

            //hiddenWorkout.Value = ss.getWorkout(workout.Id);
            Affine.Data.json.Workout       jsonWorkout     = dataManager.workoutToJsonWorkout(workout);
            Affine.Data.json.WOD           wod             = null;
            Affine.Data.json.WorkoutData[] jsonWorkoutData = null;
            //var workoutJson = new { Id = workout.Id, WorkoutTypeKey = workout.WorkoutTypeKey, Title = workout.Title, Date = workout.Date.ToLocalTime().ToShortDateString(), DataSrc = workout.DataSrc };

            Affine.Utils.UnitsUtil.MeasureUnit weight = base.WeightUnits;
            if (workout.WorkoutTypeKey == (int)Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT)
            {
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {   // default context for crossfit is the watchlist
                    context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                }
                // if this is a crossfit workout
                // we want to get ALL the same WoDs for you and your friends
                IQueryable <Workout> workoutDataQuery = context == Utils.ConstsUtil.GraphContext.EVERYONE ?
                                                        entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WOD.Id == workout.WOD.Id).AsQueryable()
                                    :
                                                        context == Utils.ConstsUtil.GraphContext.WATCHLIST ?
                                                        entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression <Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                                        context == Utils.ConstsUtil.GraphContext.FRIENDS ?
                                                        entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WOD.Id == workout.WOD.Id).Where(LinqUtils.BuildContainsExpression <Workout, long>(w => w.UserSetting.Id, friendIds)).AsQueryable()
                                    :
                                                        entities.UserStreamSet.Include("UserSettings").OfType <Workout>().Where(w => w.WOD.Id == workout.WOD.Id && w.UserSetting.Id == ProfileSettings.Id).AsQueryable();
                var workoutData = workoutDataQuery.Select(w => new { Id = w.Id, UsKey = w.UserSetting.Id, Un = w.UserSetting.UserName, T = w.Duration, S = w.Score, M = w.Max, Rx = w.RxD, D = w.Date }).ToArray();
                wod = new Affine.Data.json.WOD()
                {
                    Id = workout.WOD.Id, Standard = workout.WOD.Standard, Type = workout.WOD.WODType.Id, Name = workout.WOD.Name, Description = workout.WOD.Description
                };
                if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.TIMED)
                {   // time in sec
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.T).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.Un + "_" + w.Id, Id = w.Id, S = (double)w.T, Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false)
                    }).ToArray();
                }
                else if (wod.Type == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT)
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.M).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.Un + "_" + w.Id, Id = w.Id, S = Math.Round(Affine.Utils.UnitsUtil.systemDefaultToUnits(Convert.ToDouble(w.M), weight), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false)
                    }).ToArray();
                }
                else
                {
                    jsonWorkoutData = workoutData.OrderByDescending(w => w.S).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.Un + "_" + w.Id, Id = w.Id, S = Math.Round(Convert.ToDouble(w.S), 2), Un = w.Un, D = w.D.ToLocalTime().ToShortDateString(), Rx = (w.Rx.HasValue ? w.Rx.Value : false)
                    }).ToArray();
                }
            }
            else
            {   // for now this will handle "running, swimming, walking, cycling"
                if (context == Utils.ConstsUtil.GraphContext.DEFAULT)
                {
                    if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP || workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.EVERYONE;
                    }
                    else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.NIKE_NO_MAP)
                    {
                        context = Utils.ConstsUtil.GraphContext.WATCHLIST;
                    }
                    // TODO: not sure about this one....

                    /*
                     * else if (workout.DataSrc == (short)Utils.WorkoutUtil.DataSrc.MANUAL_WITH_MAP)
                     * {   // TODO: ?? this is a special case that we want to compare all the times of people that have logged a run for the route.
                     * long mapRouteKey = entities.UserStreamSet.OfType<Workout>().Where(w => w.Id == workout.Id).Select(w => w.WorkoutExtendeds.FirstOrDefault().MapRoute.Id).FirstOrDefault();
                     * IQueryable<Workout> workoutQuery = entities.WorkoutExtendeds.Include("UserStream").Where(we => we.MapRoute != null && we.MapRoute.Id == mapRouteKey).Select(we => we.UserStream).OfType<Workout>().OrderBy(w => w.Duration).Take(5000);
                     * workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                     * Workout[] data = workoutQuery.ToArray();
                     * var wd = data.OrderByDescending(w => w.Duration).Select(w => new
                     * {
                     *  UId = w.UserSetting.UserName + "_" + w.Id,
                     *  Id = w.Id,
                     *  S = w.Duration,
                     *  Un = w.UserSetting.UserName,
                     *  D = w.Date.ToLocalTime().ToShortDateString()
                     * }).ToArray();
                     * var ret = new { WOD = new { }, WorkoutData = wd, Workout = workoutJson, Context = (int)context };
                     * hiddenWorkoutData.Value = serializer.Serialize(ret);
                     * }*/
                    else
                    {
                        context = Utils.ConstsUtil.GraphContext.ME;
                    }
                }

                if (context == Utils.ConstsUtil.GraphContext.EVERYONE)
                {   // we want to compare achievments...
                    IQueryable <Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                                                            a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                                                            workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                                                            workout.Distance < a.AchievementType.DistanceRangeB).Take(5000).Select(a => a.UserStream).OfType <Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType <Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id  = w.Id,
                        S   = w.Duration.Value,
                        Un  = w.UserSetting.UserName,
                        D   = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.WATCHLIST || context == Utils.ConstsUtil.GraphContext.FRIENDS)
                {
                    IQueryable <Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a =>
                                                                                                                                            a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                                                            workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                                                            workout.Distance < a.AchievementType.DistanceRangeB).
                                                        Where(LinqUtils.BuildContainsExpression <Achievement, long>(a => a.UserSetting.Id, friendIds)).Take(5000).Select(a => a.UserStream).OfType <Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType <Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id  = w.Id,
                        S   = w.Duration.Value,
                        Un  = w.UserSetting.UserName,
                        D   = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
                else if (context == Utils.ConstsUtil.GraphContext.ME)   // this is just you for the ranges.. since no map data
                {
                    IQueryable <Workout> workoutQuery = entities.Achievements.Include("UserStream").Include("UserStream.UserSetting").Where(a => a.UserSetting.Id == ProfileSettings.Id &&
                                                                                                                                            a.AchievementType.WorkoutType.Id == workout.WorkoutTypeKey &&
                                                                                                                                            workout.Distance >= a.AchievementType.DistanceRangeA &&
                                                                                                                                            workout.Distance < a.AchievementType.DistanceRangeB).
                                                        Take(5000).Select(a => a.UserStream).OfType <Workout>().AsQueryable();
                    workoutQuery = workoutQuery.Union(entities.UserStreamSet.OfType <Workout>().Where(w => w.Id == workout.Id));
                    workoutQuery.Select(w => w.UserSetting).ToArray(); // hydrate.. not working above so do it here.
                    Workout[] data = workoutQuery.ToArray();
                    jsonWorkoutData = data.OrderByDescending(w => w.Duration).Select(w => new Affine.Data.json.WorkoutData()
                    {
                        UId = w.UserSetting.UserName + "_" + w.Id,
                        Id  = w.Id,
                        S   = w.Duration.Value,
                        Un  = w.UserSetting.UserName,
                        D   = w.Date.ToLocalTime().ToShortDateString()
                    }).ToArray();
                }
            }
            var retWorkout = new { WOD = wod, WorkoutData = jsonWorkoutData, Workout = jsonWorkout, Context = (int)context };

            hiddenWorkoutData.Value = serializer.Serialize(retWorkout);
        }