Beispiel #1
0
    //$response[] = array($i, $name, null, '<img src="images/'. $filename . (file_exists('images/' . $filename . '.jpg') ? '.jpg' : '.png') .'" /> ' . $name);

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Items["UserId"] = 8;
            if (Items["UserId"] != null && Request["search"] != null)
            {
                string search = Request["search"];

                aqufitEntities entities       = new aqufitEntities();
                long           uid            = Convert.ToInt64(Items["UserId"]);
                IList <long>   friendIds      = entities.UserFriends.Where(f => (f.PortalKey == 0) && (f.SrcUserKey == uid || f.DestUserKey == uid)).Select(f => (f.SrcUserKey == uid ? f.DestUserKey : f.SrcUserKey)).ToList();
                UserSettings[] firendSettings = entities.UserSettings.Where(LinqUtils.BuildContainsExpression <UserSettings, long>(s => s.UserKey, friendIds)).Where(f => f.UserName.ToLower().Contains(search) || f.UserFirstName.ToLower().Contains(search) || f.UserLastName.ToLower().Contains(search)).ToArray();
                //
                object[] response = firendSettings.Select(f => new object[] { "" + f.UserKey, f.UserName + " (" + f.UserFirstName + "," + f.UserLastName + ")", null, "<img src=\"" + ResolveUrl("~/services/images/profile.aspx?u=" + f.UserKey) + "\" align=\"middle\"/>&nbsp;&nbsp;" + f.UserName + " (" + f.UserFirstName + "," + f.UserLastName + ")" }).ToArray();
                //object[] response = {new object[]{ "5", "fdsafda dfsa fdsa", null, null } };
                Response.Write(serializer.Serialize(response));
                Response.End();
            }
        }
        catch (Exception)
        {
            //Affine.Data.json.MapRoute route = new Affine.Data.json.MapRoute() { Id = -1 };
            //Response.Write(serializer.Serialize(route));
        }
    }
Beispiel #2
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)
                {
                    if (ProfileSettings == null)
                    {
                        Response.Redirect(ResolveUrl("~/"), true);
                    }
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);
                    atiProfileImage.Settings        = base.ProfileSettings;
                    atiProfileImage.IsOwner         = base.Permissions == AqufitPermission.OWNER;
                    atiStreamScript.IsFollowMode    = true;
                    atiStreamScript.DefaultTake     = 10;
                    bEditProfile.HRef               = ResolveUrl("~/Register.aspx");
                    litFriendsTitle.Text            = "Chefs " + ProfileSettings.UserName + " follows";
                    atiWebLinksList.ProfileSettings = base.ProfileSettings;
                    if (Permissions == AqufitPermission.OWNER)
                    {
                        atiFollow.Visible       = false;
                        atiWebLinksList.IsOwner = true;
                    }
                    else if (Permissions == AqufitPermission.PUBLIC)
                    {
                        string url = DotNetNuke.Common.Globals.NavigateURL(PortalSettings.LoginTabId, "Login", new string[] { "returnUrl=/" + this.ProfileSettings.UserName });
                        atiFollow.OnClientClick = "self.location.href='" + url + "'; return false;";
                        atiFollow.Click        -= atiFollow_Click;
                    }
                    else
                    {
                        atiFollow.Text = base.Following ? "Unfollow " : "Follow " + ProfileSettings.UserName;
                    }
                    aqufitEntities entities       = new aqufitEntities();
                    IList <long>   friendIds      = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.ProfileSettings.Id)).Select(f => f.DestUserSettingKey).ToList();
                    UserSettings[] firendSettings = entities.UserSettings.Where(LinqUtils.BuildContainsExpression <UserSettings, long>(s => s.Id, friendIds)).Where(f => f.PortalKey == this.PortalId).ToArray();
                    atiFriendsPhotos.RelationshipType = Affine.Relationship.FOLLOWING;
                    atiFriendsPhotos.FriendKeyList    = firendSettings;
                    atiFriendsPhotos.User             = base.ProfileSettings;
                    atiFriendsPhotos.FriendCount      = friendIds.Count;

                    Metric numRecipes = ProfileSettings.Metrics.FirstOrDefault(m => m.MetricType == (int)Utils.MetricUtil.MetricType.NUM_RECIPES);
                    lNumCreations.Text = lNumCreations2.Text = ProfileSettings.UserName + "'s Creations (" + (numRecipes != null ? numRecipes.MetricValue : "0") + ")";
                    lNumFavorites.Text = lNumFavorites2.Text = "" + entities.User2StreamFavorites.Where(f => f.UserKey == ProfileSettings.UserKey && f.PortalKey == ProfileSettings.PortalKey).Count();
                    lUserName.Text     = ProfileSettings.UserKey == this.UserId ? "you" : ProfileSettings.UserName;



                    atiStreamScript.EditUrl = ResolveUrl("~/AddRecipe.aspx");
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Beispiel #3
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
            {
                atiRecipeCategoriesPanel.Controls.Add(new CheckBox()
                {
                    ID      = "breakfast",
                    Text    = "Breakfast",
                    Checked = false
                });
                atiRecipeCategoriesPanel.Controls.Add(new CheckBox()
                {
                    ID      = "lunch",
                    Text    = "Lunch",
                    Checked = false
                });
                atiRecipeCategoriesPanel.Controls.Add(new CheckBox()
                {
                    ID      = "dinner",
                    Text    = "Dinner",
                    Checked = false
                });
                atiRecipeCategoriesPanel.Controls.Add(new CheckBox()
                {
                    ID      = "snack",
                    Text    = "Snack",
                    Checked = false
                });
                atiRecipeCategoriesPanel.Controls.Add(new CheckBox()
                {
                    ID      = "dessert",
                    Text    = "Dessert",
                    Checked = false
                });

                this.RecipeEditId = 0;
                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);
                    atiProfileImage.Settings = base.ProfileSettings;
                    atiProfileImage.IsOwner  = base.Permissions == AqufitPermission.OWNER;
                    atiUploadifyImg1.Action  = "recipe";
                    atiUploadifyImg2.Action  = "recipe";
                    atiUploadifyImg3.Action  = "recipe";
                    atiUploadifyImg4.Action  = "recipe";
                    aqufitEntities entities = new aqufitEntities();
                    if (Request["s"] != null)
                    {
                        long rid = Convert.ToInt64(Request["s"]);
                        Affine.Data.Recipe rec = entities.UserStreamSet.OfType <Recipe>().FirstOrDefault(r => r.Id == rid && r.UserSetting.UserKey == this.UserId && r.PortalKey == this.ProfileSettings.PortalKey);
                        this.RecipeEditId      = rec != null ? rec.Id : 0;
                        atHiddenRecipeId.Value = "" + this.RecipeEditId;
                    }
                    litFriendsTitle.Text = "Chefs " + ProfileSettings.UserName + " follows";
                    IList <long>   friendIds      = entities.UserFriends.Where(f => (f.SrcUserSettingKey == this.ProfileSettings.Id)).Select(f => f.DestUserSettingKey).ToList();
                    UserSettings[] firendSettings = entities.UserSettings.Where(LinqUtils.BuildContainsExpression <UserSettings, long>(s => s.Id, friendIds)).Where(f => f.PortalKey == this.PortalId).ToArray();
                    atiFriendsPhotos.RelationshipType = Affine.Relationship.FOLLOWING;
                    atiFriendsPhotos.FriendKeyList    = firendSettings;
                    atiFriendsPhotos.User             = base.ProfileSettings;
                    atiFriendsPhotos.FriendCount      = friendIds.Count;
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        /// -----------------------------------------------------------------------------
        /// <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);
            }         
        }
        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);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // 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);
        }