protected void atiRadComboBoxSearchMessageInbox_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            // TODO: we need to search "reply" text and add those messages to the results.
            RadComboBox atiRadComboBoxSearchMessageInbox = (RadComboBox)sender;
            atiRadComboBoxSearchMessageInbox.Items.Clear();
            const int TAKE = 5;
            aqufitEntities entities = new aqufitEntities();
            int itemOffset = e.NumberOfItems;
            IQueryable<Message> messagesQuery = entities.MessageRecipiants.Where( m => m.UserSettingsKey == this.UserSettings.Id ).Select( m => m.Message ).OrderBy(m => m.DateTime);
            int length = messagesQuery.Count();
            messagesQuery = string.IsNullOrEmpty(e.Text) ? messagesQuery.Where(m => m.UserSetting.Id != this.UserSettings.Id).Skip(itemOffset).Take(TAKE) : messagesQuery.Where(m => m.UserSetting.Id != this.UserSettings.Id && m.Subject.ToLower().Contains(e.Text) || m.Text.ToLower().Contains(e.Text)).Skip(itemOffset).Take(TAKE);

            Message[] messages = messagesQuery.ToArray();

            foreach (Message m in messages)
            {
                RadComboBoxItem item = new RadComboBoxItem(m.Subject);
                item.Value = "" + m.Id;
               // item.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?u=" + g.UserKey + "&p=" + g.PortalKey;
                atiRadComboBoxSearchMessageInbox.Items.Add(item);
            }
            int endOffset = Math.Min(itemOffset + TAKE + 1, length);
            e.EndOfItems = endOffset == length;
            e.Message = (length <= 0) ? "No matches" : String.Format("Items <b>1</b>-<b>{0}</b> of {1}", endOffset, length);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     aqufitEntities entities = new aqufitEntities();
     if (this.CompetitionAthleteId > 0)
     {
         CompetitionAthlete athlete = entities.CompetitionAthletes.FirstOrDefault(a => a.Id == CompetitionAthleteId);
         if (athlete != null)
         {
             litName.Text = athlete.AthleteName + " " + athlete.OverallRank + "(" + athlete.OverallScore + ")";
             imgAthlete.ImageUrl = athlete.ImgUrl;
             string html = "<ul>";
             if( athlete.Height.HasValue ){
                 double inch = Affine.Utils.UnitsUtil.systemDefaultToUnits(athlete.Height.Value, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_INCHES );
                 html += "<li>Height: <em>" + Math.Floor(inch/12.0) + "' " + Math.Ceiling(inch%12.0) + "\"</em></li>";
             }
             if( athlete.Weight.HasValue ){
                 double lbs = Affine.Utils.UnitsUtil.systemDefaultToUnits(athlete.Weight.Value, Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
                 html += "<li>Weight: <em>" + Math.Round(lbs, 2) + "</em></li>";
             }
             html += "<li>&nbsp;</li>";
             html += "<li>Affiliate: <em>" + athlete.AffiliateName + "</em></li>";
             html += "<li>Region: <em>" + athlete.RegionName + "</em></li>";
             html += "<li>Hometown: <em>" + athlete.Hometown + "</em></li>";
             html += "<li>Country: <em>" + athlete.Country + "</em></li>";
             html += "</ul>";
             litDetails.Text = html;
         }
     }
 }
Beispiel #3
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)
    {
        Response.ContentType = "application/json";
        if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
        {
            object json = new { Status = "FAIL", Msg = "" };
            try
            {
                aqufitEntities entities = new aqufitEntities();
                long uid = Convert.ToInt64(Request.Form["u"]);
                string token = Convert.ToString(Request.Form["t"]);     // our limited security model ;)
                long sk = Convert.ToInt64(Request.Form["sk"]);
                long profileKey = Convert.ToInt64(Request.Form["p"]);
                string comment = Convert.ToString(Request.Form["c"]);
                Guid guid = Guid.Parse(token);
                User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid && u.Guid == guid);

                Affine.Data.Managers.LINQ.DataManager.Instance.AddComment(user.UserKey, user.PortalKey, profileKey, sk, comment);
                json = new { Status = "SUCCESS", Msg = "" };
            }
            catch (Exception ex)
            {
                json = new { Status = "FAIL", Msg = ex.Message.Replace("'", "") };
            }
            Response.Write(serializer.Serialize(json));
            Response.Flush();
            Response.End();
        }
    }
Beispiel #4
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));
        }
    }
    /*
    <u>{userId}</u>
    <t>{token}</t>
    <ds>{dateSrc}</ds>
    <d>{description}</d>
    <n>{workoutName}</n>
    <wt>{WODType}</wt>
    <at>{amrapTime}</at>
     */
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "application/json";
        if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
        {
            object json = new{ Id = -1, Status = "FAIL", Msg = "" };
            try
            {
                aqufitEntities entities = new aqufitEntities();
                long uid = Convert.ToInt64(Request.Form["u"]);
                string token = Convert.ToString(Request.Form["t"]);     // our limited security model ;)
                int wodType = Convert.ToInt32(Request.Form["wt"]);
                string description = Convert.ToString(Request.Form["d"]);
                string name = Convert.ToString(Request.Form["n"]);
                long dataSrc = Convert.ToInt64(Request.Form["ds"]);
                long amrapTime = Convert.ToInt64(Request.Form["at"]);

                Guid gToken = Guid.Parse(token);
                User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid && u.Guid == gToken);

                Affine.Data.json.Exercise[] none = new Affine.Data.json.Exercise[0];
                long wodId = dataManager.CreateWOD(user.Id, name, description, wodType, amrapTime, none);
                json = new { Id = wodId, Status = "SUCCESS", Msg = "" };
            }
            catch (Exception ex)
            {
                json = new { Id = -1, Status = "FAIL", Msg = ex.Message.Replace("'", "") };
            }
            Response.Write(serializer.Serialize(json));
            Response.Flush();
            Response.End();
        }
    }
Beispiel #6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (Request["i"] != null )
         {
             long iid = Convert.ToInt64(Request["i"]);
             aqufitEntities entities = new aqufitEntities();
             Affine.Data.Image img = entities.Image.FirstOrDefault(i => i.Id == iid);
             if (Request["f"] != null)
             {
                 Affine.Data.Image image = entities.Image.FirstOrDefault(i => i.Id == img.ImageLargeKey);
                 Response.ContentType = image.ContentType;
                 Response.OutputStream.Write(image.Bytes, 0, image.Bytes.Length);
                 Response.Flush();
                 Response.End();
             }
             else
             {
                 Response.ContentType = img.ContentType;
                 Response.OutputStream.Write(img.Bytes, 0, img.Bytes.Length);
                 Response.Flush();
                 Response.End();
             }
         }
     }
     catch (Exception)
     {
         // fall through
     }
     Response.Flush();
     Response.End();
 }
 protected void bSend_Click(object sender, EventArgs e)
 {
     aqufitEntities entities = new aqufitEntities();
     UserSettings settings = null;
     if (this.UserId > 0)
     {
         settings = entities.UserSettings.FirstOrDefault(us => us.UserKey == this.UserId && us.PortalKey == this.PortalId);
     }
     string un = settings != null ? settings.UserName : "";
     string url = Request["u"] != null ? Request["u"] : Request.Url.AbsoluteUri;
     long tab = Request["t"] != null ? Convert.ToInt64(Request["t"]) : this.TabId;
     string email = string.Empty;
     if (this.UserId > 0)
     {
         email = entities.UserSettings.FirstOrDefault(u => u.Id == this.UserId && u.PortalKey == this.PortalId).UserEmail;
     }
     else
     {
         email = txtEmail.Text;
     }
     BugReport bug = new BugReport()
     {
         Description = txtDescription.Text,
         UserAgent = Request.UserAgent,
         UserId = this.UserId,
         UserName = un,
         PortalId = this.PortalId,
         PortalName = this.PortalAlias.HTTPAlias,
         AbsoluteUrl = Request.Url.AbsoluteUri,
         AbsoluteUrlReferrer = url,
         DateTime = DateTime.Now,
         Ip = Request.ServerVariables["REMOTE_ADDR"],
         RawUrl = Request.RawUrl,
         ScreenResolution = hiddenScreenRes.Value,
         Status = "Open",
         Email = email,
         ActiveTabId = this.TabId,
         IsContactRequest = panelContactHead.Visible
     };
     entities.AddToBugReports(bug);
     entities.SaveChanges();
     bSend.Visible = false;
     txtDescription.Visible = false;
     if (panelBugHead.Visible)   // This moduel is configured to report bugs
     {
         sendBugNotificationEmailAsync(bug);
         litStatus.Text = "<em>Thank You</em>.  Bear with us as we work out some of the kinks in our system.";
     }
     else
     {
         sendContactNotificationEmailAsync(bug);
         litStatus.Text = "<em>Thank You</em>.  Your request has been sent.  We will get back to you as soon as we possibly can.";
     }
 }
Beispiel #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(Request["u"]) && !string.IsNullOrEmpty(Request["json"]))
            {
                string jsonString = Request["json"];

                Affine.Data.json.MapRoute mapRoute = serializer.Deserialize<Affine.Data.json.MapRoute>(jsonString);

                long userKey = Convert.ToInt64(Request["u"]);
                Affine.Data.MapRoute route = new MapRoute()
                {
                    Name = mapRoute.Name,
                    City = mapRoute.City,
                    Region = mapRoute.Region,
                    Rating = mapRoute.Rating,
                    PortalKey = 0,                  // TODO: send this in
                    UserKey = userKey,
                    RouteDistance = mapRoute.RouteDistance,
                    LatMax = mapRoute.LatMax,
                    LatMin = mapRoute.LatMin,
                    LngMax = mapRoute.LngMax,
                    LngMin = mapRoute.LngMin,
                    CreationDate = DateTime.Now
                };
                Affine.Data.MapRoutePoint[] points = mapRoute.MapRoutePoints.Select(mp => new Affine.Data.MapRoutePoint() { Lat = mp.Lat, Lng = mp.Lng, Order = mp.Order, MapRoute = route }).ToArray<Affine.Data.MapRoutePoint>();
                route.MapRoutePoints.Concat(points);
                aqufitEntities entities = new aqufitEntities();
                entities.AddToMapRoutes(route);
                long id = entities.SaveChanges();
                MapRoute passback = entities.MapRoutes.Where(m => m.UserKey == userKey ).OrderByDescending( m => m.Id).FirstOrDefault();
                Affine.Data.json.MapRoute mr = new Affine.Data.json.MapRoute() { Id = passback.Id, Name = passback.Name, RouteDistance = passback.RouteDistance };
                string json = serializer.Serialize(mr);
                Response.Write(json);
            }
            else
            {
                Affine.Data.json.MapRoute route = new Affine.Data.json.MapRoute() { Id = -1 };
                Response.Write(serializer.Serialize(route));
            }
        }
        catch (Exception)
        {
            Affine.Data.json.MapRoute route = new Affine.Data.json.MapRoute() { Id = -1 };
            Response.Write(serializer.Serialize(route));
        }
    }
 protected void bSave_Click(object sender, EventArgs e)
 {
     try
     {
         _hId = Request["h"] != null ? Convert.ToInt64(Request["h"]) : 1;
         aqufitEntities entities = new aqufitEntities();
         HelpPage helpPage = entities.HelpPages.FirstOrDefault(h => h.Id == _hId);
         helpPage.Content = TextEditor.RichText.Text;
         entities.SaveChanges();
         RadAjaxManager1.ResponseScripts.Add("alert('Content Saved');");
     }
     catch (Exception ex)
     {
         RadAjaxManager1.ResponseScripts.Add("alert('Error: "+ex.Message+"');");
     }
 }
Beispiel #10
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)
 {
     Response.ContentType = "application/json";
     if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
     {
         aqufitEntities entities = new aqufitEntities();
         long uid = Convert.ToInt64( Request.Form["u"] );
         Guid token = Guid.Parse( Request.Form["t"] );
         User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid && u.Guid == token);
         string json = ss.getStreamData(0, user.UserKey, user.PortalKey, user.UserKey, 0, 0, 0, 30);
         json = json.Replace(";", "");   // this messes up the json parser .. frig..
         Response.Write(json);
         Response.Flush();
         Response.End();
     }
 }
Beispiel #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "application/json";
        if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
        {
            aqufitEntities entities = new aqufitEntities();
            long uid = Convert.ToInt64( Request.Form["u"] );
            Guid token = Guid.Parse( Request.Form["t"] );
            User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid && u.Guid == token);
            string search = Request["s"] != null ? Convert.ToString(Request["s"]) : "";

            if (!string.IsNullOrWhiteSpace(search))
            {
                IQueryable<Workout> wodsToDisplay = entities.UserStreamSet.OfType<Workout>().Include("WOD").Where(w => w.UserSetting.Id == user.Id && w.Title.StartsWith(search));
                wodsToDisplay.Take(25);
                Workout[] timedWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.TIMED).OrderBy(w => w.Duration).ToArray();
                IList<NameValue> cfTotals = timedWods.Select(w => new NameValue() { Name = w.Title, Value = Affine.Utils.UnitsUtil.durationToTimeString(Convert.ToInt64(w.Duration)), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).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 NameValue() { Name = w.Title, Value = Convert.ToString(w.Score), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).ToList()).ToList();
                Workout[] maxWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT).ToArray();
                Affine.Utils.UnitsUtil.MeasureUnit WeightUnits = Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS;
                cfTotals = cfTotals.Concat(maxWods.Select(w => new NameValue() { Name = w.Title, Value = Affine.Utils.UnitsUtil.systemDefaultToUnits(w.Max.Value, WeightUnits) + " " + Affine.Utils.UnitsUtil.unitToStringName(WeightUnits), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).ToList()).ToList();
                Response.Write(serializer.Serialize(cfTotals.OrderBy(t => t.Name).ToArray()));
            }
            else
            {
                IQueryable<Workout> crossfitWorkouts = entities.UserStreamSet.OfType<Workout>().Include("WOD").Where(w => w.UserSetting.Id == user.Id && w.IsBest == true);
                int numDistinct = crossfitWorkouts.Select(w => w.WOD).Distinct().Count();
                IQueryable<Workout> wodsToDisplay = null;
                wodsToDisplay = crossfitWorkouts.OrderByDescending(w => w.Id);
                // 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<NameValue> cfTotals = timedWods.Select(w => new NameValue() { Name = w.Title, Value = Affine.Utils.UnitsUtil.durationToTimeString(Convert.ToInt64(w.Duration)), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).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 NameValue() { Name = w.Title, Value = Convert.ToString(w.Score), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).ToList()).ToList();
                Workout[] maxWods = wodsToDisplay.Where(w => w.WOD.WODType.Id == (int)Affine.Utils.WorkoutUtil.WodType.MAX_WEIGHT).ToArray();
                Affine.Utils.UnitsUtil.MeasureUnit WeightUnits = Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS;
                cfTotals = cfTotals.Concat(maxWods.Select(w => new NameValue() { Name = w.Title, Value = Affine.Utils.UnitsUtil.systemDefaultToUnits(w.Max.Value, WeightUnits) + " " + Affine.Utils.UnitsUtil.unitToStringName(WeightUnits), Date = w.Date.ToShortDateString(), Notes = "" + w.Description }).ToList()).ToList();
                Response.Write(serializer.Serialize(cfTotals.OrderBy(t => t.Name).ToArray()));
            }
            Response.Flush();
            Response.End();
        }
    }
Beispiel #12
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)
    {
        Response.ContentType = "application/json";
        IList<object> json = new List<object>();
        json.Add( new { Id = 0, Name = "", Type =  1} );
        try
        {
            if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
            {
                aqufitEntities entities = new aqufitEntities();
                long uid = Convert.ToInt64(Request.Form["u"]);
                Guid token = Guid.Parse(Request.Form["t"]);
                User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid && u.Guid == token);
                DateTime date = Convert.ToDateTime(Request.Form["d"]);
                string search = Request.Form["s"];
                if (string.IsNullOrWhiteSpace(search) && user.MainGroupKey.HasValue)
                {
                    WODSchedule schedule = entities.WODSchedules.Include("WOD").Include("WOD.WODType").FirstOrDefault(s => s.UserSetting.Id == user.MainGroupKey.Value && s.Date == date);
                    if (schedule != null)
                    {
                        json.RemoveAt(0);
                        json.Add(new { Id = schedule.WOD.Id, Name = schedule.WOD.Name, Type = schedule.WOD.WODType.Id });
                    }
                }
                else
                {
                    search = search.ToLower();
                    IQueryable<WOD> wods = entities.User2WODFav.Where(w => w.UserSetting.Id == user.Id).Select(w => w.WOD);
                    wods = wods.Union<WOD>(entities.WODs.Where(w => w.Standard > 0));
                    wods.Select(w => w.WODType).ToArray();  // hydrate WODTypes
                    wods = wods.Where(w => w.Name.ToLower().Contains(search)).OrderBy(w => w.Name).Take(10);
                    json = wods.Select(w => new { Id = w.Id, Name = w.Name, Type = w.WODType.Id }).ToArray();
                }

            }
        }
        catch (Exception ex)
        {
            json.RemoveAt(0);
            json.Add( new { WorkoutId = 0, Name = ex.Message } );
        }
        Response.Write(serializer.Serialize( json ));
        Response.Flush();
        Response.End();
    }
 protected void bRemoveImg1_Click(object sender, EventArgs e)
 {
     long rid = Convert.ToInt64(Request["s"]);
     if (rid > 0)
     {
         aqufitEntities entities = new aqufitEntities();
         Recipe r = entities.UserStreamSet.OfType<Recipe>().Include("RecipeExtendeds").Include("RecipeExtendeds.Image").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");
         }
         Affine.Data.Image img = r.RecipeExtendeds.First().Image;
         entities.DeleteObject(img);
         entities.SaveChanges();
         litStatus.Text = "Image Removed.";
         RadAjaxManager1.ResponseScripts.Add(" $('#atiRecipeImg1Div').hide(); Aqufit.Page.atiUploadifyImg1.show();");
     }
 }
Beispiel #14
0
 protected void Page_Load(object sender, EventArgs e)
 {
     Response.ContentType = "application/json";
     object json = new { Status = "Login Failed" };
     if (!string.IsNullOrWhiteSpace(Request.Form["u"]))
     {
         aqufitEntities entities = new aqufitEntities();
         string uname = Request.Form["u"];
         string password = Request.Form["p"];
         if (uname.Contains("@"))
         {   // this is an email login
             User user = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.UserEmail == uname);
             if (user == null)
             {
                 json = new { Status = "Email ERROR" };
                 Response.Write(json);
                 Response.Flush();
                 Response.End();
                 return;
             }
             uname = user.UserName;
         }
         uname = uname.ToLower();
         DotNetNuke.Security.Membership.UserLoginStatus status = DotNetNuke.Security.Membership.UserLoginStatus.LOGIN_FAILURE;
         DotNetNuke.Entities.Portals.PortalController pc = new DotNetNuke.Entities.Portals.PortalController();
         DotNetNuke.Entities.Portals.PortalInfo pi = pc.GetPortal(0);
         UserInfo uinfo = UserController.UserLogin(0, uname, password, null, pi.PortalName, DotNetNuke.Services.Authentication.AuthenticationLoginBase.GetIPAddress(), ref status, true);
         if (status == DotNetNuke.Security.Membership.UserLoginStatus.LOGIN_SUCCESS || status == DotNetNuke.Security.Membership.UserLoginStatus.LOGIN_SUPERUSER)
         {
             UserSettings usersettings = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.UserKey == uinfo.UserID && u.PortalKey == 0);
             if (!usersettings.Guid.HasValue)
             {   // we only add a UUID if there was none before.. this is so the "remember me" on the desktop site will still work.
                 usersettings.Guid = Guid.NewGuid();
                 entities.SaveChanges();
             }
             json = new { Status = "SUCCESS", Token = usersettings.Guid.ToString(), UserId = usersettings.Id, Username = usersettings.UserName };
         }
     }
     Response.Write(serializer.Serialize( json ));
     Response.Flush();
     Response.End();
 }
Beispiel #15
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try{
        // Response.ContentType = "application/json";
         if (!string.IsNullOrEmpty(Request["g"]))
         {
             aqufitEntities entities = new aqufitEntities();
             string gname = Request["g"];
             Group group = entities.UserSettings.OfType<Group>().FirstOrDefault(g => string.Compare(g.UserName, gname, true) == 0);
             Affine.Data.json.LeaderBoardWOD[] leaderBoard = dataMan.CalculatCrossFitLeaderBoard(group.Id);
             JavaScriptSerializer jserializer = new JavaScriptSerializer();
             string jsfile = System.IO.File.ReadAllText(Server.MapPath("~/DesktopModules/ATI_Base/resources/scripts/leaders.js"));
             Response.Write("var __ati_group = {Name:'"+group.UserFirstName+"', UserName:'******', Id:"+group.Id+"}; var __ati_json = '"+jserializer.Serialize(leaderBoard)+"';");
             Response.Write(jsfile);
         }
         else
         {
             Response.Write("{ERROR:'invalid request'}");
         }
     }catch(Exception){
         Response.Write("{ERROR:'exception in request'}");
     }
 }
        protected void atiRadComboBoxSearchRoutes_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            RadComboBox atiRadComboSearchWorkouts = (RadComboBox)sender;
            atiRadComboSearchWorkouts.Items.Clear();
            const int TAKE = 5;
            aqufitEntities entities = new aqufitEntities();
            int itemOffset = e.NumberOfItems;
            IQueryable<MapRoute> routes = entities.User2MapRouteFav.Where(r => r.UserSettingsKey == UserSettings.Id).Select(w => w.MapRoute);
            routes = routes.OrderBy(r => r.Name);
            int length = routes.Count();
            routes = string.IsNullOrEmpty(e.Text) ? routes.Skip(itemOffset).Take(TAKE) : routes.Where(r => r.Name.ToLower().StartsWith(e.Text)).Skip(itemOffset).Take(TAKE);

            MapRoute[] routeArray = routes.ToArray();

            foreach (MapRoute r in routeArray)
            {
                RadComboBoxItem item = new RadComboBoxItem(r.Name);
                item.Value = "" + r.Id;
                atiRadComboSearchWorkouts.Items.Add(item);
            }
            int endOffset = Math.Min(itemOffset + TAKE + 1, length);
            e.EndOfItems = endOffset == length;
            e.Message = (length <= 0) ? "No matches" : String.Format("Items <b>1</b>-<b>{0}</b> of {1}", endOffset, length);
        }
 protected void RadGrid3_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
 {
     aqufitEntities entities = new aqufitEntities();
     IQueryable<CompetitionWOD> compWodQuery = entities.CompetitionWODs.Include("WOD").Include("WOD.WODType").Where(c => c.Competition.Id == CompetitionKey && c.CompetitionCategory.Id == (int)Affine.Utils.WorkoutUtil.CompetitionCategory.IND_FEMALE).OrderBy(c => c.Order);
     RadGrid3.DataSource = compWodQuery.Select(c =>
             new
             {
                 Id = c.Id,
                 WorkoutName = c.WOD.Name,
                 WorkoutType = c.WOD.WODType.Name,
                 WorkoutOrder = (c.Order + 1)
             }
         ).ToArray();
 }
        /// -----------------------------------------------------------------------------
        /// <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
            {
                aqufitEntities entities = new aqufitEntities();
                bool isAdmin = false;
                if (Request["c"] != null)
                {
                    // TODO: make sure they are a group admin to the comp..
                    CompetitionKey = Convert.ToInt64(Request["c"]);
                    Competition comp = entities.Competitions.Include("Group").FirstOrDefault(c => c.Id == CompetitionKey);
                    if (comp != null)
                    {
                        UserFriends admin = entities.UserFriends.FirstOrDefault(f => f.SrcUserSettingKey == UserSettings.Id && f.DestUserSettingKey == comp.Group.Id && f.Relationship <= (int)Affine.Utils.ConstsUtil.Relationships.GROUP_ADMIN);
                        if (admin != null)
                        {
                            isAdmin = true;
                        }
                        litCompOwner.Text = comp.Group.UserFirstName;
                        txtCompName.Text = comp.Name;
                        RadCompStartDate.SelectedDate = comp.CompetitionStartDate;
                        RadCompEndDate.SelectedDate = comp.CompetitionEndDate;
                    }
                }

                if( !isAdmin )
                {
                    Response.Redirect(ResolveUrl("~/") + UserSettings.UserName);
                }
                RadListBoxTeamSource.DataSource = entities.CompetitionRegistrations.Where(r => r.Competition.Id == CompetitionKey && r.CompetitionCategory.Id == (int)Affine.Utils.WorkoutUtil.CompetitionCategory.TEAM).Select(r => new { Name = r.TeamName, Value = r.Id }).ToArray();
                RadListBoxTeamSource.DataTextField = "Name";
                RadListBoxTeamSource.DataValueField = "Value";
                RadListBoxTeamSource.DataBind();

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    ddlTeamPools.DataSource = entities.CompetitionTeamPools.Where(tp => tp.Competition.Id == CompetitionKey).Select(tp => new { Name = tp.Name, Value = tp.Id }).ToArray();
                    ddlTeamPools.DataTextField = "Name";
                    ddlTeamPools.DataValueField = "Value";
                    ddlTeamPools.DataBind();

                    if (ddlTeamPools.Items.Count == 0)
                    {
                        buttonAddPoolWorkout.Visible = false;
                        RadGrid2.Visible = false;
                    }

                    baseUrl = ResolveUrl("~/");
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);

                }

            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected void RadGrid2_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                long tpKey = Convert.ToInt64(ddlTeamPools.SelectedValue);

                aqufitEntities entities = new aqufitEntities();
                IQueryable<CompetitionWOD> compWodQuery = entities.CompetitionWODs.Include("WOD").Include("WOD.WODType").Where(c => c.Competition.Id == CompetitionKey && c.CompetitionCategory.Id == (int)Affine.Utils.WorkoutUtil.CompetitionCategory.TEAM && c.CompetitionTeamPool.Id == tpKey).OrderBy(c => c.Order);
                RadGrid2.DataSource = compWodQuery.Select(c =>
                        new
                        {
                            Id = c.Id,
                            WorkoutName = c.WOD.Name,
                            WorkoutType = c.WOD.WODType.Name,
                            WorkoutOrder = (c.Order + 1)
                        }
                    ).ToArray();
            }
            catch { }
        }
Beispiel #20
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!string.IsNullOrEmpty(Request["w"]))
     {
         aqufitEntities entities = new aqufitEntities();
         long           wid      = Convert.ToInt64(Request["w"]);
         // TODO: need security
         Workout workout = entities.UserStreamSet.Include("WorkoutExtendeds").Include("UserSetting").OfType <Workout>().FirstOrDefault(w => w.Id == wid);
         if (workout != null)
         {
             Affine.Data.json.Workout json = new Affine.Data.json.Workout()
             {
                 Calories    = workout.Calories,
                 Date        = workout.Date.ToShortDateString(),
                 Description = workout.Description,
                 Distance    = workout.Distance,
                 Duration    = workout.Duration,
                 Emotion     = workout.Emotion,
                 Id          = workout.Id,
                 Title       = workout.Title,
                 PortalKey   = workout.PortalKey,
                 UserKey     = workout.UserSetting.UserKey,
                 Weather     = workout.Weather,
             };
             if (workout.WorkoutExtendeds.FirstOrDefault() != null)
             {
                 WorkoutExtended ext = workout.WorkoutExtendeds.First();
                 Affine.Data.json.WorkoutExtended jsonWorkoutExtended = new Affine.Data.json.WorkoutExtended()
                 {
                     Id     = ext.Id,
                     LatMax = ext.LatMax,
                     LatMin = ext.LatMin,
                     LngMax = ext.LngMax,
                     LngMin = ext.LngMin
                 };
                 Affine.Data.json.WorkoutSample[] samples = entities.WorkoutSamples.Where(s => s.WorkoutExtended.Id == ext.Id).OrderBy(s => s.SampleNumber)
                                                            .Select(s => new Affine.Data.json.WorkoutSample()
                 {
                     Date         = s.Date,
                     Time         = 0,
                     Distance     = s.Distance,
                     Elevation    = s.Elevation,
                     HeartRate    = s.HeartRate,
                     Id           = s.Id,
                     Lat          = s.Lat,
                     Lng          = s.Lng,
                     SampleNumber = s.SampleNumber
                 }).ToArray();
                 foreach (Affine.Data.json.WorkoutSample s in samples)
                 {
                     s.Time = s.Date.Ticks;
                 }
                 jsonWorkoutExtended.WorkoutSamples = samples;
                 json.WorkoutExtended = jsonWorkoutExtended;
             }
             JavaScriptSerializer jserializer = new JavaScriptSerializer();
             Response.Write(jserializer.Serialize(json));
         }
     }
     else if (Request["ed"] != null && Request["u"] != null && Request["sd"] != null)
     {
         long     uid       = Convert.ToInt64(Request["u"]);
         DateTime endDate   = DateTime.Parse(Request["ed"]);
         DateTime startDate = DateTime.Parse(Request["sd"]).ToUniversalTime();
         endDate = endDate.AddDays(1).ToUniversalTime();
         aqufitEntities entities = new aqufitEntities();
         IList <Affine.Data.json.Workout> ret = new List <Affine.Data.json.Workout>();
         IList <Workout> workoutList          = entities.UserStreamSet.Include("UserSetting").OfType <Workout>().
                                                Where(w => w.UserSetting.UserKey == uid && w.Date.CompareTo(endDate) <= 0 && w.Date.CompareTo(startDate) >= 0).OrderByDescending(w => w.Date).ToList();
         workoutList = workoutList.Reverse().ToList();
         foreach (Workout workout in workoutList)
         {
             Affine.Data.json.Workout json = new Affine.Data.json.Workout()
             {
                 Calories    = workout.Calories,
                 TimeStamp   = workout.TimeStamp,
                 Date        = workout.Date.ToShortDateString(),
                 Description = workout.Description,
                 Distance    = workout.Distance,
                 Duration    = workout.Duration,
                 Emotion     = workout.Emotion,
                 Id          = workout.Id,
                 Title       = workout.Title,
                 PortalKey   = workout.PortalKey,
                 UserKey     = workout.UserSetting.UserKey,
                 Weather     = workout.Weather,
                 DataSrc     = workout.DataSrc
             };
             ret.Add(json);
         }
         // TODO: need a case for empty data
         JavaScriptSerializer jserializer = new JavaScriptSerializer();
         Response.Write(jserializer.Serialize(ret.ToArray()));
     }
     else
     {
         Response.Write("{ERROR:'invalid request'}");
     }
 }
 protected void bAjaxPostback_Click(object sender, EventArgs e)
 {
     try
     {
         Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
         aqufitEntities entities = new aqufitEntities();
         switch (hiddenAjaxAction.Value)
         {
             case "AddWOD":
                 long wodKey = Convert.ToInt64(hiddenAjaxValue.Value);
                 int compType = Convert.ToInt32(hiddenAjaxValue2.Value);
                 long poolKey = 0;
                 if (compType == (int)Affine.Utils.WorkoutUtil.CompetitionCategory.TEAM)
                 {
                     poolKey = Convert.ToInt32(hiddenAjaxValue3.Value);
                 }
                 WOD wod = entities.WODs.Include("WODType").FirstOrDefault(w => w.Id == wodKey);
                 Competition comp = entities.Competitions.Include("CompetitionWODs").FirstOrDefault(c => c.Id == CompetitionKey);
                 if (wod != null && comp != null)
                 {
                     CompetitionWOD compWod = new CompetitionWOD()
                     {
                         WOD = wod,
                         Order = comp.CompetitionWODs.Count,
                         Competition = comp,
                         CompetitionCategory= entities.CompetitionCategories.FirstOrDefault( c => c.Id == compType ),
                         CompetitionTeamPool = entities.CompetitionTeamPools.FirstOrDefault( tp => tp.Id == poolKey )
                     };
                     entities.AddToCompetitionWODs(compWod);
                     entities.SaveChanges();
                     RadAjaxManager1.ResponseScripts.Add(" Aqufit.Windows.WorkoutFinder.close(); Aqufit.Page.Actions.refreshGrid("+compType+"); ");
                 }
                 break;
             case "DeleteWOD":
                 long compWodKey = Convert.ToInt64(hiddenAjaxValue.Value);
                 CompetitionWOD compW = entities.CompetitionWODs.Include("CompetitionCategory").FirstOrDefault(c => c.Id == compWodKey && c.Competition.Id == CompetitionKey);
                 if (compW != null)
                 {
                     RadAjaxManager1.ResponseScripts.Add(" Aqufit.Page.Actions.refreshGrid(" + compW.CompetitionCategory.Id + "); ");
                     entities.DeleteObject(compW);
                     entities.SaveChanges();
                     // rebuild the order of the workouts now..
                     CompetitionWOD[] orderList = entities.CompetitionWODs.Where(c => c.Competition.Id == CompetitionKey).OrderBy( c => c.Order ).ToArray();
                     int order = 0;
                     foreach (CompetitionWOD cw in orderList)
                     {
                         cw.Order = (order++);
                     }
                     entities.SaveChanges();
                 }
                 break;
             case "AddTeamPool":
                 string name = Convert.ToString(hiddenAjaxValue.Value);
                 CompetitionTeamPool pool = new CompetitionTeamPool()
                 {
                     Name = name,
                     Competition = entities.Competitions.FirstOrDefault( c => c.Id == CompetitionKey)
                 };
                 entities.AddToCompetitionTeamPools(pool);
                 entities.SaveChanges();
                 RadAjaxManager1.ResponseScripts.Add(" Aqufit.Windows.TeamPoolWin.close(); Aqufit.Page.Actions.refreshTeamPoolGrid(); ");
                 break;
             case "LoadTeamPool":
                 long tpKey = Convert.ToInt64(hiddenAjaxValue.Value);
                 string[] teamKeyArray = entities.CompetitionRegistrations.Where(r => r.CompetitionRegistration2TeamPool
                                                                          .FirstOrDefault(c => c.CompetitionTeamPool.Id == tpKey) != null)
                                                                          .Select( r => r.Id ).Cast<string>().ToArray();
                 string jsTeamArray = "[]";
                 if (teamKeyArray.Length > 0)
                 {
                     jsTeamArray = "[" + teamKeyArray.Aggregate((i, j) => "" + i + "," + j) + "]";
                 }
                 RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.TeamPoolManagerWin.loadData(" + jsTeamArray + "); ");
                 break;
             case "SaveTeamPool":
                 long tPoolKey = Convert.ToInt64(hiddenAjaxValue.Value);
                 CompetitionRegistration2TeamPool[] clearArray = entities.CompetitionRegistration2TeamPool.Where(c => c.CompetitionTeamPool.Id == tPoolKey).ToArray();
                 foreach (CompetitionRegistration2TeamPool clear in clearArray)
                 {
                     entities.DeleteObject(clear);
                 }
                 entities.SaveChanges();
                 CompetitionTeamPool tpool = entities.CompetitionTeamPools.FirstOrDefault(tp => tp.Id == tPoolKey);
                 foreach (RadListBoxItem item in RadListBoxPoolDest.Items)
                 {
                     long rId = Convert.ToInt64(item.Value);
                     CompetitionRegistration2TeamPool c2t = new CompetitionRegistration2TeamPool()
                     {
                         CompetitionTeamPool = tpool,
                         CompetitionRegistration = entities.CompetitionRegistrations.FirstOrDefault( r => r.Id == rId )
                     };
                     entities.AddToCompetitionRegistration2TeamPool(c2t);
                 }
                 entities.SaveChanges();
                 RadListBoxTeamSource.DataSource = entities.CompetitionRegistrations.Where(r => r.Competition.Id == CompetitionKey && r.CompetitionCategory.Id == (int)Affine.Utils.WorkoutUtil.CompetitionCategory.TEAM).Select(r => new { Name = r.TeamName, Value = r.Id }).ToArray();
                 RadAjaxManager1.ResponseScripts.Add(" Aqufit.Windows.TeamPoolManagerWin.close(); Aqufit.Page.Actions.refreshTeamPoolGrid(); ");
                 break;
         }
     }
     catch (Exception ex)
     {
         RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.Actions.ShowFail('ERROR: There was a problem with the action (" + ex.StackTrace.Replace("'","").Replace("\r","").Replace("\n","") + ")');");
     }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     ddlWorkoutTypeList.CssClass = this.CssClass;
     aqufitEntities entities = new aqufitEntities();
     if (Cache["WorkoutTypeList"] == null)
     {
         Cache["WorkoutTypeList"] = entities.WorkoutType.Where(wt => wt.Id != 5).ToList<WorkoutType>();
     }
     // Create a check list of all the workout types
     IList<WorkoutType> wtList = (IList<WorkoutType>)Cache["WorkoutTypeList"];
     if (this.TypeDisplayMode == null || this.TypeDisplayMode == DisplayMode.CHECK_BOX)
     {
         ddlWorkoutTypeList.Visible = false;
         Table t = new Table();
         TableRow tr = new TableRow();
         int i = 0;
         foreach (WorkoutType wt in wtList)
         {
             if (i++ % 3 == 0)
             {
                 if (i > 0) t.Rows.Add(tr);
                 tr = new TableRow();
             }
             CheckBox cb = new CheckBox()
             {
                 ID = "wt_" + wt.Id,
                 Text = wt.Name,
                 Checked = true
             };
             TableCell td = new TableCell()
             {
                 CssClass = "atiThreeList"
             };
             if (this.UncheckTypes != null && this.UncheckTypes.FirstOrDefault(w => w.Id == wt.Id) != null)
             {
                 cb.Checked = false;
             }
             this.CheckBoxList.Add(cb);
             td.Controls.Add(cb);
             tr.Cells.Add(td);
         }
         t.Rows.Add(tr);
         panelWorkoutTypeList.Controls.Add(t);
         if (!Page.IsPostBack && !Page.IsCallback)
         {
         }
     }
     else if (this.TypeDisplayMode == DisplayMode.DROP_DOWN)
     {
         if (!Page.IsPostBack && !Page.IsCallback)
         {
             ddlWorkoutTypeList.Visible = true;
             foreach (WorkoutType wt in wtList)
             {
                 ListItem li = new ListItem() { Text = wt.Name, Value = Convert.ToString(wt.Id) };
                 if (SelectedType != null && (int)SelectedType == wt.Id)
                 {
                     li.Selected = true;
                 }
                 ddlWorkoutTypeList.Items.Add(li);
             }
         }
     }
     else if (this.TypeDisplayMode == DisplayMode.ICONS)
     {
         string html = string.Empty;
         if (!Page.IsPostBack && !Page.IsCallback)
         {
             ddlWorkoutTypeList.Visible = false;
             html += "<ul class=\"hlist\">";
             foreach (WorkoutType wt in wtList)
             {
                 string css = string.Empty;
                 if (this.SelectedType != null && (int)this.SelectedType == wt.Id)
                 {
                     css = "class=\"workoutTypeSelected\" ";
                 }
                 string img = "<img src=\"" + ResolveUrl(wt.Icon) + "\" />";
                 html += "<li " + css + "><a title=\""+wt.Name+"\" href=\"javascript: ;\" " + (!string.IsNullOrWhiteSpace(this.OnClientWorkoutTypeChanged) ? "onclick=\"" + this.OnClientWorkoutTypeChanged + "(" + wt.Id + ");\"" : "") + ">" + img + "</a></li>";
             }
             html += "</ul>";
             panelWorkoutTypeList.Controls.Add(new Literal() { Text = html });
         }
     }
 }
 protected void RadGridUsers_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
 {
     aqufitEntities entities = new aqufitEntities();
     RadGridUsers.DataSource = entities.UserSettings.OfType<User>().Where( u => u.PortalKey == PortalId).OrderBy(u => u.UserName).Select(u => new { UserName = u.UserName, Id = u.Id, UserFirstName = u.UserFirstName, UserLastName = u.UserLastName, FBKey = u.FBUid, UserEmail = u.UserEmail }).ToArray();
 }
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            try
            {
                aqufitEntities entities = new aqufitEntities();
                Affine.Data.Managers.IDataManager dataMan = Affine.Data.Managers.LINQ.DataManager.Instance;
                long pId = -1;
                switch (hiddenAjaxAction.Value)
                {
                case "loadPhoto":
                    pId = Convert.ToInt64(hiddenAjaxValue.Value);
                    string url = SetupPhoto(pId);
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.Actions.LoadImage('" + url + "', " + lPhotoNum.Text + ");");
                    break;

                case "makeProfile":
                    pId = Convert.ToInt64(hiddenAjaxValue.Value);
                    Affine.Utils.ImageUtil.MakeProfileFromPhoto(UserSettings.Id, pId, Server.MapPath("~"));
                    string profileUrl = ResolveUrl("~") + UserSettings.UserName;
                    RadAjaxManager1.ResponseScripts.Add("top.location.href='" + profileUrl + "'; Aqufit.Page.atiLoading.remove();");
                    break;

                case "tagPhoto":
                    Affine.Data.Helpers.PhotoTag json = JsonExtensionsWeb.FromJson <Affine.Data.Helpers.PhotoTag>(hiddenAjaxValue.Value);
                    pId = Convert.ToInt64(hiddenPhotoId.Value);
                    // TODO: security
                    dataMan.TagPhoto(UserSettings.Id, json.FriendId, pId, json.Top, json.Left, json.Width, json.Height);
                    RadAjaxManager1.ResponseScripts.Add("radalert('<div style=\"width: 100%; height: 100%; padding: 0px;\"><span style=\"color: #FFF;\"><img src=\"" + ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png") + "\" align=\"absmiddle\"/> Photo has been tagged</span></div>', 330, 100, 'Success');");
                    break;

                case "addComment":
                    pId = Convert.ToInt64(hiddenPhotoId.Value);
                    string            comment = hiddenAjaxValue.Value;
                    AttachmentComment pc      = dataMan.SavePhotoComment(UserSettings.Id, pId, comment);
                    string            j       = new { UserName = pc.UserSetting.UserName, UserKey = pc.UserSetting.UserKey, Comment = pc.Comment }.ToJson();
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.Actions.appendComment('" + j + "'); ");
                    break;

                case "deletePhoto":
                    pId = Convert.ToInt64(hiddenPhotoId.Value);
                    dataMan.DeletePhoto(UserSettings.Id, pId);
                    Response.Redirect(ResolveUrl("~") + UserSettings.UserName + "/photos", true);
                    //RadAjaxManager1.ResponseScripts.Add("alert('"+pId+"');");
                    break;

                case "deleteAlbum":
                    long aId = Convert.ToInt64(hiddenAlbumKey.Value);
                    dataMan.DeleteAlbum(UserSettings.Id, aId);
                    Response.Redirect(ResolveUrl("~") + UserSettings.UserName + "/photos", true);
                    //RadAjaxManager1.ResponseScripts.Add("alert('"+pId+"');");
                    break;

                case "deleteTag":
                    long       tId = Convert.ToInt64(hiddenAjaxValue.Value);
                    User2Photo u2p = entities.User2Photo.FirstOrDefault(p => p.Id == tId && (p.UserSettingsKey == UserSettings.Id || p.TaggerUserSettingsKey == UserSettings.Id));
                    if (u2p != null)
                    {
                        entities.DeleteObject(u2p);
                        entities.SaveChanges();
                        RadAjaxManager1.ResponseScripts.Add("radalert('<div style=\"width: 100%; height: 100%; padding: 0px;\"><span style=\"color: #FFF;\"><img src=\"" + ResolveUrl("~/DesktopModules/ATI_Base/resources/images/iCheck.png") + "\" align=\"absmiddle\"/> Tag has been removed</span></div>', 330, 100, 'Success');");
                    }
                    RadAjaxManager1.ResponseScripts.Add("Aqufit.Page.atiLoading.remove(); ");
                    break;
                }
            }
            catch (Exception ex)
            {
                // TODO: better error handling
                RadAjaxManager1.ResponseScripts.Add(" alert('" + ex.Message + "'); ");
            }
        }
 private void deleteMessageForUser(long mid)
 {
     aqufitEntities entities = new aqufitEntities();
     MessageRecipiant mr = entities.MessageRecipiants.Where(m => m.Message.Id == mid && m.UserSettingsKey == this.UserSettings.Id).First();
     entities.DeleteObject(mr);
     entities.SaveChanges();
     litStatus.Text = "Message has been deleted.";
 }
        private string SetupPhoto(long pId)
        {
            string         ret      = string.Empty;
            aqufitEntities entities = new aqufitEntities();

            hiddenNextPhotoId.Value = "-1";
            hiddenPrevPhotoId.Value = "-1";
            panelPhotoList.Visible  = false;
            panelPhoto.Visible      = true;
            Photo[] photos    = null;
            Photo   photoPrev = null;

            if (hiddenAlbumKey.Value == string.Empty)
            {
                // lets first check that the photo is not in any album?
                Album album = entities.UserAttachments.OfType <Photo>().Include("Album").FirstOrDefault(p => p.Id == pId).Album;
                if (album != null)
                {
                    hiddenAlbumKey.Value = "" + album.Id;
                }
            }
            if (hiddenAlbumKey.Value != string.Empty)
            {
                long aId = Convert.ToInt64(hiddenAlbumKey.Value);
                IQueryable <Photo> photoQuery = entities.UserAttachments.OfType <Photo>().Include("UserSetting").OrderBy(p => p.Id).Where(p => p.Album.Id == aId);
                int total = photoQuery.Count();
                litPhotoCount.Text = "" + total;
                photoQuery         = photoQuery.Where(p => p.Id >= pId);
                total++;    // avoid saying 0 of 4 ....
                lPhotoNum.Text = "" + (total - photoQuery.Count());
                photos         = photoQuery.Take(2).ToArray();
                photoPrev      = entities.UserAttachments.OfType <Photo>().Include("UserSetting").OrderByDescending(p => p.Id).FirstOrDefault(p => p.Id < pId && p.Album.Id == aId);
            }
            else
            {
                IQueryable <Photo> photoQuery = entities.User2Photo.OrderBy(p => p.Photo.Id).Where(p => p.UserSettingsKey == ProfileSettings.Id).Select(p => p.Photo).OfType <Photo>();
                int total = photoQuery.Count();
                litPhotoCount.Text = "" + photoQuery.Count();
                photoQuery         = photoQuery.Where(p => p.Id >= pId);
                total++;    // avoid saying (0 of 4) ....
                lPhotoNum.Text = "" + (total - photoQuery.Count());
                photos         = photoQuery.Take(2).ToArray();
                User2Photo u2p = entities.User2Photo.Include("Photo").OrderByDescending(p => p.Photo.Id).FirstOrDefault(p => p.Photo.Id < pId);
                if (u2p != null)
                {
                    photoPrev = (Photo)u2p.Photo;
                }
            }
            if (photos.Length > 0)
            {
                if (photos[0].UserSetting.Id == UserSettings.Id)
                {
                    liDeletePhoto.Visible = true;
                }

                ret = photos[0].ImageUri;
                hiddenPhotoId.Value = "" + photos[0].Id;
                // setup tags...
                pId = photos[0].Id; // yes this is needed
                User2Photo[] photoTags = entities.User2Photo.Where(p => p.Photo.Id == pId).ToArray();
                string       js        = string.Empty;
                js += "Aqufit.Page.atiPhotoTagger.clearTags();";
                foreach (User2Photo u2p in photoTags)
                {
                    User person = entities.UserSettings.OfType <User>().FirstOrDefault(u => u.Id == u2p.UserSettingsKey);
                    js += "Aqufit.Page.atiPhotoTagger.addTagElement(" + person.Id + "," + u2p.Id + ",'" + person.UserName + " (" + person.UserFirstName + " " + person.UserLastName + ")'," + u2p.Top + ", " + u2p.Left + ", " + u2p.Width + ", " + u2p.Height + ");";
                }
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    this.StartupFunction = "Aqufit.Page.Actions.onLoadHelper = function(){ " + js + " };";
                }
                else
                {
                    RadAjaxManager1.ResponseScripts.Add("$(function(){ " + js + " });");
                }
            }
            if (photos.Length > 1)
            {
                hiddenNextPhotoId.Value = "" + photos[1].Id;
            }

            if (photoPrev != null)
            {
                hiddenPrevPhotoId.Value = "" + photoPrev.Id;
            }
            return(ret);
        }
        /// -----------------------------------------------------------------------------
        /// <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
            {
                // ***************
                // TODO: security ... make sure firends ... ect ...

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

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    if (UserSettings == null)
                    {   // Users must be signed in to view photos
                        panelAll.Visible = false;
                        string retUrl = ResolveUrl("~") + ProfileSettings.UserName + "/photos";
                        if (Request["p"] != null)
                        {
                            retUrl += "?p=" + Request["p"];
                        }
                        RadAjaxManager1.ResponseScripts.Add(" top.location.href='" + ResolveUrl("~/Login") + "?returnurl=" + Server.UrlEncode(retUrl) + "'; ");
                        Response.End();
                        return;
                    }

                    if (Settings["Configure"] != null && string.Compare(Settings["Configure"].ToString(), "ConfigurePhotoView", true) == 0)
                    {
                        atiPhotosTitle.InnerText = "Photos";
                        imgAd.Visible            = false;
                        this.PageUrl             = ResolveUrl("~") + ProfileSettings.UserName + "/ViewPhoto";
                        atiWorkoutAlbum.Visible  = false;
                    }
                    else
                    {
                        if (ProfileSettings == null && UserSettings != null)
                        {
                            Response.Redirect(ResolveUrl("~") + UserSettings.UserName + "/photos", true);
                            return;
                        }
                        atiPhotosTitle.InnerText = "Photos of " + ProfileSettings.UserName;
                        this.PageUrl             = ResolveUrl("~") + ProfileSettings.UserName + "/photos";
                    }
                    photoTabTitle.Text = "Photos of " + ProfileSettings.UserName;



                    hlBackAlbums.HRef       = "javascript: top.location.href='" + ResolveUrl("~") + ProfileSettings.UserName + "/photos" + "';";
                    atiWorkoutAlbum.Visible = base.Permissions == AqufitPermission.OWNER;
                    long           pId      = 0;
                    aqufitEntities entities = new aqufitEntities();
                    if (HttpContext.Current.Items["p"] != null)
                    {
                        pId = Convert.ToInt64(HttpContext.Current.Items["p"]);
                    }
                    else if (Request["p"] != null)
                    {
                        pId = Convert.ToInt64(Request["p"]);
                    }
                    if (Request["a"] != null)
                    {
                        RadListViewTags.Visible = false;
                        hiddenAlbumKey.Value    = Request["a"];
                        long  aId   = Convert.ToInt64(hiddenAlbumKey.Value);
                        Album album = entities.Albums.Include("UserSetting").FirstOrDefault(a => a.Id == aId);
                        bDeleteAlbum.Visible = (album.UserSetting.Id == UserSettings.Id && album.AlbumType == (int)Affine.Utils.ImageUtil.AlbumType.USER);
                        int total = entities.UserAttachments.OfType <Photo>().Where(p => p.Album.Id == album.Id).Count();
                        atiPhotosTitle.InnerText = "Photos: " + total + " photos in album (" + album.Name + ")";
                        litPhotoNav.Text         = "<a href=\"" + ResolveUrl("~") + ProfileSettings.UserName + "/photos\">Back to photos</a>";
                        litAlbumName.Text        = "<a style=\"border-bottom: 0;\" href=\"?a=" + album.Id + "\">" + album.Name + "</a>";
                        atiAlbumList.Visible     = false;
                    }
                    else
                    {
                        RadListViewAlbumPhotos.Visible = false;
                    }
                    // Are we viewing a specific photo
                    if (pId > 0)
                    {
                        // TODO: security ... make sure firends ... ect ...
                        imgPhoto.Src    = SetupPhoto(pId);
                        imgThisUser.Src = ResolveUrl("~/DesktopModules/ATI_Base/services/images/profile.aspx") + "?u=" + UserSettings.UserKey + "&p=" + UserSettings.PortalKey;
                        long[]            friendIds = entities.UserFriends.Where(f => (f.SrcUserSettingKey == UserSettings.Id || f.DestUserSettingKey == UserSettings.Id) && f.Relationship != (int)Affine.Utils.ConstsUtil.Relationships.FOLLOW).Select(f => (f.SrcUserSettingKey == UserSettings.Id ? f.DestUserSettingKey : f.SrcUserSettingKey)).ToArray();
                        IQueryable <User> userQuery = entities.UserSettings.OfType <User>().Where(Affine.Utils.Linq.LinqUtils.BuildContainsExpression <User, long>(s => s.Id, friendIds));
                        userQuery = userQuery.Concat(entities.UserSettings.OfType <User>().Where(us => us.Id == UserSettings.Id));
                        atiPhotoTagger.DataSource = userQuery.OrderBy(us => us.UserName).Select(us => new{ UserName = us.UserName + " (" + us.UserFirstName + " " + us.UserLastName + ")", Id = us.Id });
                    }
                    else
                    {
                        panelPhotoList.Visible      = true;
                        panelPhoto.Visible          = false;
                        hiddenUserSettingsKey.Value = "" + ProfileSettings.Id;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Beispiel #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack && !Page.IsCallback)
        {
            // imgNikePlus.ImageUrl = ResolveUrl("~/DesktopModules/ATI_Fitness/resources/images/iSyncNikePlus.png");
            // set date control to today
            atiRadDatePicker.SelectedDate = DateTime.Now;

            // setup the units control
            atiDistanceUnits.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES);
            atiDistanceUnits.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KM);
            atiDistanceUnits.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_M);
            atiDistanceUnits.Selected = Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES;

            atiMaxWeightUnits.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS);
            atiMaxWeightUnits.UnitList.Add(Affine.Utils.UnitsUtil.MeasureUnit.UNIT_KG);
            atiMaxWeightUnits.Selected = Affine.Utils.UnitsUtil.MeasureUnit.UNIT_LBS;

            // Setup the units to the users last used units
            if (this.PortalSettings.UserInfo.UserID != -1)
            {
                aqufitEntities aqufitEntities = new aqufitEntities();
                UserSettings   aqufitSettings = aqufitEntities.UserSettings.FirstOrDefault <UserSettings>(us => us.UserKey == this.PortalSettings.UserInfo.UserID && us.PortalKey == this.PortalSettings.PortalId);
                if (aqufitSettings != null) // TODO: this really should never happen
                {
                    if (aqufitSettings.DistanceUnits != null)
                    {
                        atiDistanceUnits.Selected = (Affine.Utils.UnitsUtil.MeasureUnit)Enum.ToObject(typeof(Affine.Utils.UnitsUtil.MeasureUnit), aqufitSettings.DistanceUnits);
                    }
                    if (aqufitSettings.WeightUnits != null)
                    {
                        atiMaxWeightUnits.Selected = (Affine.Utils.UnitsUtil.MeasureUnit)Enum.ToObject(typeof(Affine.Utils.UnitsUtil.MeasureUnit), aqufitSettings.WeightUnits);
                    }
                }
            }

            if (this.SetControlToWOD != null)
            {
                atiWorkoutTypes.SelectedType = Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT;
                Aqufit.Helpers.WodItem wi = new Aqufit.Helpers.WodItem()
                {
                    Id = this.SetControlToWOD.Id, Type = (short)this.SetControlToWOD.WODType.Id
                };
                string          json = _serializer.Serialize(wi);
                RadComboBoxItem item = new RadComboBoxItem(this.SetControlToWOD.Name, json);
                item.Selected = true;
                atiRadComboBoxCrossfitWorkouts.Items.Add(item);
                ScriptManager.RegisterStartupScript(this, Page.GetType(), "InitialWOD", "Aqufit.addLoadEvent(function(){ Aqufit.Page." + this.ID + ".configureFormView(" + (int)Affine.Utils.WorkoutUtil.WorkoutType.CROSSFIT + "); Aqufit.Page.Controls.atiWodSelector.SetupWOD('" + json + "') });", true);
            }
            else if (this.SetControlToMapRoute != null)
            {
                Affine.Utils.UnitsUtil.MeasureUnit units = Affine.Utils.UnitsUtil.MeasureUnit.UNIT_MILES;
                double dist = Affine.Utils.UnitsUtil.systemDefaultToUnits(this.SetControlToMapRoute.RouteDistance, units);
                dist = Math.Round(dist, 2);
                Aqufit.Helpers.RouteItem ri = new Aqufit.Helpers.RouteItem()
                {
                    Dist = this.SetControlToMapRoute.RouteDistance, Id = this.SetControlToMapRoute.Id
                };
                string          json = _serializer.Serialize(ri);
                RadComboBoxItem item = new RadComboBoxItem(Affine.Utils.Web.WebUtils.FromWebSafeString(this.SetControlToMapRoute.Name) + " (" + dist + " " + Affine.Utils.UnitsUtil.unitToStringName(units) + ")", json);
                item.Selected = true;
                item.ImageUrl = Affine.Utils.ImageUtil.GetGoogleMapsStaticImage(this.SetControlToMapRoute, 200, 150);
                atiRouteSelector.Items.Add(item);
            }
        }
    }
 /// -----------------------------------------------------------------------------
 /// <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)
         {
             imgSpinner.Src          = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/loading.gif");
             atiLogin.Visible        = true;
             panelStream.Visible     = false;
             hiddenAccountType.Value = Request["a"];
             if (!string.IsNullOrEmpty(Request["a"])) // this tells us the account type (garmin/nike+)
             {
                 if (Request["a"].ToLower() == "nike")
                 {
                     litAccountName.Text     = "<h1>Nike+</h1>";
                     litInstructions.Visible = false;
                     imgLogo.Src             = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/logoNike.png");
                     atiLogin.UserNameField  = "Nike+ Email";
                     atiLogin.PasswordField  = "Nike+ Password";
                 }
                 else
                 {
                     atiLogin.UserNameField = "Garmin Username";
                     atiLogin.PasswordField = "Garmin Password";
                     litInstructions.Text   = "Enter your Garmin Connect credentials. If you don't have an account, <a href=\"http://connect.garmin.com\">sign up free</a><br /><br />";
                     litAccountName.Text    = "<h1>Garmin</h1>";
                     imgLogo.Src            = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/logoGarmin.png");
                 }
                 aqufitEntities entities    = new aqufitEntities();
                 AccountType    accountType = entities.AccountType.FirstOrDefault(at => at.Name == hiddenAccountType.Value);
                 if (accountType != null)
                 {
                     ThirdPartyAccounts account = entities.ThirdPartyAccounts.Include("UserSettings").Include("AccountType").FirstOrDefault(a => a.UserSettings.UserKey == this.UserId && a.UserSettings.PortalKey == this.PortalId && a.AccountType.Id == accountType.Id);
                     if (account != null)     // we have already setup an account so just do the sync
                     {
                         panelLogin.Visible      = false;
                         litInstructions.Visible = false;
                         if (account.AccountType.Id == (short)Affine.Services.ThirdParty.AccountTypes.NIKE)
                         {
                             WorkoutConnectorFactory connectorFactory = new WorkoutConnectorFactory(); // TODO: Initialize to an appropriate value
                             IWorkoutConnector       connector        = connectorFactory.GetWorkoutConnector(account);
                             if (connector.Login(account))
                             {
                                 // now try to get the records
                                 IList <Workout> workoutList = connector.SyncWorkouts();
                                 BindWorkouts(workoutList, account);
                             }
                         }
                         else if (account.AccountType.Id == (short)Affine.Services.ThirdParty.AccountTypes.GARMIN)
                         {   // unfortunatly garmin fuct us up with the ssl login change .... so here is the new code..
                             litGarminAccountName.Text = account.AccountUserName;
                             panelGarmin.Visible       = true;
                             panelLogin.Visible        = false;
                             panelStream.Visible       = false;
                         }
                     }
                 } // end if (nikeAccountType != null)
             }     // end if (string.IsNullOrEmpty(Request["a"]))
         }
     }
     catch (Exception exc) //Module failed to load
     {
         Exceptions.ProcessModuleLoadException(this, exc);
     }
 }
Beispiel #30
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
            {
                this.IsFavorite = true;
                base.Page_Load(sender, e);
                this.RecipeId = 0;
                if (Request["r"] != null || HttpContext.Current.Items["r"] != null)
                {
                    if (Request["r"] != null)
                    {
                        this.RecipeId = Convert.ToInt64(Request["r"]);
                    }
                    else if (HttpContext.Current.Items["r"] != null)
                    {
                        this.RecipeId = Convert.ToInt64(HttpContext.Current.Items["r"]);
                    }
                }
                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    atiSearchBar.Visible = Settings["ShowSearchBar"] == null ? true : Convert.ToBoolean(Settings["ShowSearchBar"]);
                    ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                    service.InlineScript = true;
                    ScriptManager.GetCurrent(Page).Services.Add(service);
                    if (Request["r"] != null || HttpContext.Current.Items["r"] != null)
                    {
                        atiRecipePanel.Visible   = true;
                        atiRecipe.ShowLogin      = this.UserId <= 0;
                        atiSearchResults.Visible = false;
                        atiRecipe.RecipeId       = Convert.ToString(this.RecipeId);
                        aqufitEntities       entities = new aqufitEntities();
                        User2StreamFavorites rFav     = entities.User2StreamFavorites.FirstOrDefault(f => f.UserKey == this.UserId && f.PortalKey == this.PortalId && f.UserStream.Id == this.RecipeId);
                        this.IsFavorite       = (rFav != null);
                        atiAddRemFav.ImageUrl = this.IsFavorite ? ResolveUrl("~/DesktopModules/ATI_Base/resources/images/remFromFav.png"):ResolveUrl("~/DesktopModules/ATI_Base/resources/images/addToFav.png");
                        imgCorner.Src         = ResolveUrl("~/DesktopModules/ATI_Base/resources/images/corner.png");
                    }
                    else
                    {
                        atiSearchResults.Visible    = true;
                        atiRecipePanel.Visible      = false;
                        atiStreamScript.EditUrl     = ResolveUrl("~/AddRecipe.aspx");
                        atiStreamScript.DefaultTake = Settings["DefaultTake"] != null?Convert.ToInt32(Settings["DefaultTake"]) : 10;

                        // pick out a featured chef
                        aqufitEntities            entities = new aqufitEntities();
                        IQueryable <UserSettings> possible = entities.UserStreamSet.OfType <Recipe>().OrderByDescending(r => r.Date).Select(r => r.UserSetting).Distinct();
                        // radomize 20
                        int    max  = possible.Count() < 20 ? possible.Count() : 20;
                        Random rand = new Random();
                        IQueryable <UserSettings> featureQuery = possible.OrderByDescending(u => u.Id).Skip(rand.Next(max)).Take(1);
                        // Hydrate users metrics
                        featureQuery.Select(m => m.Metrics).ToArray();
                        featureQuery.Select(s => s.UserStreams.OrderByDescending(r => r.Date)).First();
                        UserSettings featured = featureQuery.First();
                        atiFeaturedProfile.Settings = featured;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected void RadGridTeamPool_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            aqufitEntities entities = new aqufitEntities();
             IQueryable<CompetitionTeamPool> compPoolQuery = entities.CompetitionTeamPools.Include("CompetitionRegistration2TeamPool").Where(c => c.Competition.Id == CompetitionKey);
             CompPoolData[] ctArray = compPoolQuery.Select(c =>
                     new CompPoolData()
                     {
                         Id = c.Id,
                         Pool = c.Name,
                         Teams = ""
                     }
                 ).ToArray();

            CompetitionTeamPool[] compoolArray = entities.CompetitionTeamPools.Include("CompetitionRegistration2TeamPool.CompetitionRegistration").Where(c => c.Competition.Id == CompetitionKey).ToArray();
            for( int i=0; i<ctArray.Length; i++){
                foreach( CompetitionRegistration2TeamPool reg2team in compoolArray[i].CompetitionRegistration2TeamPool)
                {
                    ctArray[i].Teams += reg2team.CompetitionRegistration.TeamName + ",";
                }
            }

            RadGridTeamPool.DataSource = ctArray;
        }
        protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            aqufitEntities entities = new aqufitEntities();
            Competition    comp     = null;
            long           compKey  = 0;

            if (Request["c"] != null)
            {
                compKey = Convert.ToInt64(Request["c"]);
                comp    = entities.Competitions.FirstOrDefault(c => c.Id == compKey);
            }
            if (compKey <= 0)
            {
                comp = entities.Competitions.FirstOrDefault();
            }
            IQueryable <CompetitionAthlete> athleteQuery = entities.CompetitionAthletes.Include("CompetitionWODs").Where(a => a.Competition.Id == comp.Id);

            if (rblSex.SelectedValue != "A")
            {
                athleteQuery = athleteQuery.Where(a => a.Sex == rblSex.SelectedValue);
            }
            long rid = Convert.ToInt64(ddlRegion.SelectedValue);

            if (rid > 0)
            {
                athleteQuery = athleteQuery.Where(a => a.CompetitionRegion.Id == rid);
            }

            try
            {
                long aId = Convert.ToInt64(atiRadComboSearchAffiliates.SelectedValue);
                if (aId > 0)
                {
                    athleteQuery = athleteQuery.Where(a => a.CompetitionAffiliate.Id == aId);
                }
            }
            catch (Exception) { }
            RadGrid1.DataSource = athleteQuery.Select(a =>
                                                      new {
                FlexId        = (a.UserSetting != null ? a.UserSetting.UserName : ""),
                AffiliateName = a.AffiliateName,
                AthleteName   = a.AthleteName,
                Country       = a.Country,
                Height        = a.Height,
                Age           = (a.BirthYear.HasValue ? (DateTime.Today.Year - a.BirthYear.Value) : 0),
                Hometown      = a.Hometown,
                Id            = a.Id,
                ImgUrl        = a.ImgUrl,
                OverallRank   = a.OverallRank,
                OverallScore  = a.OverallScore,
                RegionKey     = (a.CompetitionRegion != null ? a.CompetitionRegion.Id : 0),
                Sex           = a.Sex,
                RegionName    = a.RegionName,
                Weight        = a.Weight,
                UId           = a.UId,
                W1Score       = a.CompetitionWODs.Count > 0 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 0).Score : 0,
                W1Rank        = a.CompetitionWODs.Count > 0 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 0).Rank  : 0,
                W2Score       = a.CompetitionWODs.Count > 1 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 1).Score : 0,
                W2Rank        = a.CompetitionWODs.Count > 1 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 1).Rank : 0,
                W3Score       = a.CompetitionWODs.Count > 2 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 2).Score : 0,
                W3Rank        = a.CompetitionWODs.Count > 2 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 2).Rank : 0,
                W4Score       = a.CompetitionWODs.Count > 3 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 3).Score : 0,
                W4Rank        = a.CompetitionWODs.Count > 3 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 3).Rank : 0,
                W5Score       = a.CompetitionWODs.Count > 4 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 4).Score : 0,
                W5Rank        = a.CompetitionWODs.Count > 4 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 4).Rank : 0,
                W6Score       = a.CompetitionWODs.Count > 5 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 5).Score : 0,
                W6Rank        = a.CompetitionWODs.Count > 5 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 5).Rank : 0
            }
                                                      ).ToArray();
        }
        /// -----------------------------------------------------------------------------
        /// <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);
            }
        }
        protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            aqufitEntities entities = new aqufitEntities();
            Competition comp = null;
            long compKey = 0;
            if (Request["c"] != null)
            {
                compKey = Convert.ToInt64(Request["c"]);
                comp = entities.Competitions.FirstOrDefault(c => c.Id == compKey);
            }
            if (compKey <= 0)
            {
                comp = entities.Competitions.FirstOrDefault();
            }
            IQueryable<CompetitionAthlete> athleteQuery = entities.CompetitionAthletes.Include("CompetitionWODs").Where(a => a.Competition.Id == comp.Id);
            if (rblSex.SelectedValue != "A" )
            {
                athleteQuery = athleteQuery.Where(a => a.Sex == rblSex.SelectedValue);
            }
            long rid = Convert.ToInt64( ddlRegion.SelectedValue );
            if (rid > 0)
            {
                athleteQuery = athleteQuery.Where(a => a.CompetitionRegion.Id == rid);
            }

            try
            {
                long aId = Convert.ToInt64(atiRadComboSearchAffiliates.SelectedValue);
                if (aId > 0)
                {
                    athleteQuery = athleteQuery.Where(a => a.CompetitionAffiliate.Id == aId);
                }
            }
            catch (Exception) { }
            RadGrid1.DataSource = athleteQuery.Select(a =>
                    new {
                        FlexId =  (a.UserSetting != null ? a.UserSetting.UserName : ""),
                        AffiliateName = a.AffiliateName,
                        AthleteName = a.AthleteName,
                        Country = a.Country,
                        Height = a.Height,
                        Age = (a.BirthYear.HasValue ? (DateTime.Today.Year - a.BirthYear.Value) : 0),
                        Hometown = a.Hometown,
                        Id = a.Id,
                        ImgUrl = a.ImgUrl,
                        OverallRank = a.OverallRank,
                        OverallScore = a.OverallScore,
                        RegionKey = (a.CompetitionRegion != null ? a.CompetitionRegion.Id : 0),
                        Sex = a.Sex,
                        RegionName = a.RegionName,
                        Weight = a.Weight,
                        UId = a.UId,
                        W1Score = a.CompetitionWODs.Count > 0 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 0).Score : 0,
                        W1Rank = a.CompetitionWODs.Count > 0 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 0).Rank  : 0,
                        W2Score = a.CompetitionWODs.Count > 1 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 1).Score : 0,
                        W2Rank = a.CompetitionWODs.Count > 1 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 1).Rank : 0,
                        W3Score = a.CompetitionWODs.Count > 2 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 2).Score : 0,
                        W3Rank = a.CompetitionWODs.Count > 2 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 2).Rank : 0,
                        W4Score = a.CompetitionWODs.Count > 3 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 3).Score : 0,
                        W4Rank = a.CompetitionWODs.Count > 3 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 3).Rank : 0,
                        W5Score = a.CompetitionWODs.Count > 4 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 4).Score : 0,
                        W5Rank = a.CompetitionWODs.Count > 4 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 4).Rank : 0,
                        W6Score = a.CompetitionWODs.Count > 5 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 5).Score : 0,
                        W6Rank = a.CompetitionWODs.Count > 5 ? a.CompetitionWODs.FirstOrDefault(w => w.Order == 5).Rank : 0
                    }
                ).ToArray();
        }
        /*
        private long RegisterGroup(string name, string email, string address, string city, string url, string phone, double lat, double lng)
        {
            //3-933 Ellery Street, Victoria, BC V9A 4R9, Canada
            //1840 Gadsden Hwy # 112, Birmingham, AL
            string postal = string.Empty;
            string street = string.Empty;
            string region = string.Empty;
            string country = string.Empty;
            if (address != null)
            {
                string[] split = address.Split(',');
                if (split.Length > 0)
                {
                    street = split[0];
                }
                if (split.Length > 1)
                {
                    // city we have
                }
                if (split.Length > 2)
                {
                    region = split[2];
                }
            }
            // check required fields
            string uName = name.Replace(" ", "_").Replace("'", "");
            aqufitEntities entities = new aqufitEntities();
            Group test = entities.UserSettings.OfType<Group>().FirstOrDefault(g => g.UserName == uName);
                // if a user is found with that username, error. this prevents you from adding a username with the same name as a superuser.
           if (test != null)
           {
               throw new Exception("We already have an entry for the Group Name.");

           }
            Affine.WebService.RegisterService regService = new WebService.RegisterService();
            Group us = new Data.Group();
            us.UserKey = 0;
            us.PortalKey = PortalId;
            us.UserEmail = email;
            us.UserName = uName;
            us.UserFirstName = name;
            us.UserLastName = "";
            us.GroupType = entities.GroupTypes.FirstOrDefault(g => g.Id == 1);
            us.DefaultMapLat = lat;
            us.DefaultMapLng = lng;
            us.LngHome = lat;
            us.LngHome = lng;
            //us.Status = atTxtGroupDescription.Text;
            // TODO: don't make the Place required for groups..

            us.Places.Add(new Place()
            {
                City = city,
                Country = country,
                Email = email,
                Lat = lat,
                Lng = lng,
                Name = name,
                Postal = postal,
                Region = region,
                Street = street,
                Website = url,
                Phone = phone
            });
            entities.AddToUserSettings(us);
            entities.SaveChanges();
            // Now assign the creator of the group as an admin
            Group group = entities.UserSettings.OfType<Group>().First(g => g.UserName == us.UserName);
            return group.Id;

        }
        */
        protected void bAjaxPostback_Click(object sender, EventArgs e)
        {
            try
            {
                switch (hiddenAjaxAction.Value)
                {
                    case "su":
                        long uid = Convert.ToInt64(hiddenAjaxValue.Value);
                        aqufitEntities entities = new aqufitEntities();
                        User fbUser = entities.UserSettings.OfType<User>().FirstOrDefault(u => u.Id == uid);
                        UserController uc = new UserController();
                        UserInfo ui = uc.GetUser((int)fbUser.PortalKey, (int)fbUser.UserKey);
                        UserController.UserLogin(PortalId,ui,PortalSettings.PortalName, Request.UserHostAddress, true);
                        Response.Redirect(ResolveUrl("~"), true);
                        break;
                }
            }
            catch (Exception ex)
            {
                RadAjaxManager1.ResponseScripts.Add("Aqufit.Windows.ErrorDialog('" + ex.Message.Replace("'", "") + "'); ");
            }
        }
 protected void bBetaTest_Click(object sender, EventArgs e)
 {
     aqufitEntities aqufitEntities = new aqufitEntities();
     Preview p = CreatePreview(atiBetaTest.FirstName, atiBetaTest.LastName, atiBetaTest.Email, atiBetaTest.Comments);
     p.Ip = Request.ServerVariables["REMOTE_ADDR"];
     p.IsBetaTester = true;
     p.EnteredByPortalId = PortalId;
     p.EnteredByUserId = UserId;
     p.EnteredByUserName = UserInfo.Username;
     aqufitEntities.AddToPreview(p);
     aqufitEntities.SaveChanges();
     string body = "New Beta Tester signed up<br />First Name: " + p.FirstName + "<br />Last Name: " + p.LastName + "<br />Email: " + p.Email + "<br />IP: " + p.Ip;
     DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "Beta Tester Signed up!", body, "", "HTML", "", "", "", "");
     DotNetNuke.Services.Mail.Mail.SendMail("*****@*****.**", "*****@*****.**", "", "Beta Tester Signed up!", body, "", "HTML", "", "", "", "");
     panelBeta.Visible = false;
     panelThankYou.Visible = true;
     RadAjaxManager1.ResponseScripts.Add("AjaxResponseSuccess();");
 }
        private UserSettings populateUserSettings(UserSettings us, UserInfo ui)
        {
            aqufitEntities entities = new aqufitEntities();

            long usId = us.Id;
            us.UserKey = ui.UserID;
            us.PortalKey = ui.PortalID;
            us.UserEmail = ui.Email;
            us.UserName = ui.Username;
            us.UserFirstName = ui.FirstName;
            us.UserLastName = ui.LastName;
            //us.TimeZone = ui.Profile.TimeZone;
            return us;
        }
        protected void bSaveAndClose_Click(object sender, EventArgs e)
        {
            // TODO: a try catch.. for failure to import

            // TODO: security check ...
            // TODO: need to keep running totals for the user.
            // here we  add the nike+ data to the users workouts
            IList <Workout> workouts = atiStream.DataSource.Cast <Workout>().ToList <Workout>();

            // Now we know "workouts" that the user wants to import.  So we need to try to get the extended data for each workout.

            aqufitEntities          entities         = new aqufitEntities();
            AccountType             accountType      = entities.AccountType.FirstOrDefault(at => at.Name == hiddenAccountType.Value);
            ThirdPartyAccounts      account          = entities.ThirdPartyAccounts.Include("UserSettings").Include("AccountType").FirstOrDefault(a => a.UserSettings.UserKey == this.UserId && a.UserSettings.PortalKey == this.PortalId && a.AccountType.Id == accountType.Id);
            WorkoutConnectorFactory connectorFactory = new WorkoutConnectorFactory(); // TODO: Initialize to an appropriate value
            IWorkoutConnector       connector        = connectorFactory.GetWorkoutConnector(account);

            if (!connector.Login(account))
            {
                // TODO: error handle
                throw new Exception("Error: login third party data sync failed.");
            }

            workouts = workouts.OrderByDescending(w => w.Date).ToList();     // we want to insert from past to present

            // make some vaiables for totals
            double totalDistance = 0.0;
            long   totalTime     = 0;
            // So here is the deal with the next bit of code.  If someone syncs more runs then "3"? We don't want to flood the
            // friends streams with all those runs.  So we sync all the runs to the owner steam and NOT friends (publish setting 1)
            // Then we sync a notive to ONLY the friends stream that a bunch of runs were synced (publish setting 2)
            double       absTotalDist = 0.0;
            double       absTotalCal  = 0.0;
            long         absTotalTime = 0;
            UserSettings settings     = entities.UserSettings.FirstOrDefault(us => us.UserKey == this.UserId && us.PortalKey == this.PortalId);

            Affine.Data.Managers.IDataManager dataManager = Affine.Data.Managers.LINQ.DataManager.Instance;
            if (workouts.Count > 3)
            {
                foreach (Workout w in workouts)
                {
                    totalDistance    += Convert.ToDouble(w.Distance);
                    absTotalDist     += totalDistance;
                    totalTime        += Convert.ToInt64(w.Duration);
                    absTotalTime     += totalTime;
                    absTotalCal      += Convert.ToDouble(w.Calories);
                    w.PublishSettings = 1; // TODO: no magic number (1) is to publish for yourself but NOT your friends
                    w.Id          = 0;     // make sure our third party id does not show up in the id
                    w.UserSetting = settings;
                    WorkoutExtended ext = new WorkoutExtended();
                    w.WorkoutExtendeds.Add(ext);
                    // entities.AddToUserStreamSet(w);

                    try
                    {
                        IList <WorkoutSample> samples = connector.SyncDeviceSamplesForWorkout(ext);
                        samples.ToList().ForEach(s => entities.AddToWorkoutSamples(s));
                    }
                    catch (NoExtendedDataException)
                    {
                        // change the workout src so we dont expect extended data with this one.
                        w.DataSrc = (int)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP;
                    }
                    dataManager.SaveWorkout(entities, w);
                    // We got all the data that we require so save the workout
                }

                Utils.UnitsUtil.MeasureUnit distUnit = Affine.Utils.UnitsUtil.ToUnit(settings.DistanceUnits.Value);
                TimeSpan     duration            = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(totalTime));
                TimeSpan     pace                = new TimeSpan(0, 0, 0, 0, totalDistance > 0 ? Convert.ToInt32(totalTime / totalDistance) : 0);
                Notification workoutNotification = new Notification()
                {
                    PortalKey   = this.PortalId,
                    UserSetting = settings,
                    Date        = DateTime.Now.ToUniversalTime(),
                    Title       = "Notification <em>" + account.AccountType.Name + " Sync</em>",
                    Description = "Nike+ sync of " + workouts.Count + " workouts.<br />Total Distance: "
                                  + String.Format("{0:0.0}", Affine.Utils.UnitsUtil.systemDefaultToUnits(totalDistance, distUnit)) + " " + Affine.Utils.UnitsUtil.unitToStringName(distUnit) + "<br />"
                                  + "Total Time: " + String.Format("{0:00}", duration.Hours) + ":" + String.Format("{0:00}", duration.Minutes) + ":" + String.Format("{0:00}", duration.Seconds) + "<br />"
                                  + "Avg. Pace: " + String.Format("{0:0}", pace.Minutes) + ":" + String.Format("{0:00}", pace.Seconds),
                    TimeStamp        = DateTime.Now.ToUniversalTime(),
                    NotificationType = (int)Affine.Utils.ConstsUtil.NotificationTypes.NIKE_PLUS,
                    PublishSettings  = (int)Affine.Utils.ConstsUtil.PublishSettings.FRIEND_ONLY
                };
                entities.AddToUserStreamSet(workoutNotification);
                // Adjust the totals now

                /*
                 * WorkoutTotal totals = entities.WorkoutTotals.FirstOrDefault(wt => wt.UserKey == this.UserId && wt.PortalKey == this.PortalId && wt.WorkoutTypeKey == 0);   // When workout type key == 0 This is the "Entire" totals for all workout types
                 * if (totals == null)
                 * {
                 *  totals = new WorkoutTotal();
                 *  totals.PortalKey = this.PortalId;
                 *  totals.UserKey = this.UserId;
                 *  entities.AddToWorkoutTotals(totals);
                 * }
                 * totals.Distance += absTotalDist;
                 * totals.Calories += absTotalCal;
                 * totals.Time += absTotalTime;
                 * totals.Count+=workouts.Count;
                 * entities.SaveChanges();
                 */
            }
            else  // just add the 3 or less runs normaly
            {
                foreach (Workout w in workouts)
                {
                    totalDistance += Convert.ToDouble(w.Distance);
                    absTotalDist  += totalDistance;
                    totalTime     += Convert.ToInt64(w.Duration);
                    absTotalTime  += totalTime;
                    absTotalCal   += Convert.ToDouble(w.Calories);
                    w.Id           = 0; // make sure our third party id does not show up in the id
                    w.UserSetting  = settings;
                    WorkoutExtended ext = new WorkoutExtended();
                    w.WorkoutExtendeds.Add(ext);
                    // entities.AddToUserStreamSet(w);
                    try
                    {
                        IList <WorkoutSample> samples = connector.SyncDeviceSamplesForWorkout(ext);
                        samples.ToList().ForEach(s => entities.AddToWorkoutSamples(s));
                    }
                    catch (NoExtendedDataException)
                    {
                        // TODO: log this... change the workout src so we dont expect extended data with this one.
                        w.DataSrc = (int)Utils.WorkoutUtil.DataSrc.MANUAL_NO_MAP;
                    }
                    dataManager.SaveWorkout(entities, w);
                }
            }
            RadAjaxManager1.ResponseScripts.Add("self.close();  top.location.href = '" + ResolveUrl("~") + UserSettings.UserName + "'; ");
        }
        /// -----------------------------------------------------------------------------
        /// <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);

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    aqufitEntities entities = new aqufitEntities();
                    if (Request["a"] != null)
                    {
                        long aId = Convert.ToInt64(Request["a"]);
                        CompetitionAffiliate affiliate = entities.CompetitionAffiliates.FirstOrDefault(a => a.Id == aId);
                        atiRadComboSearchAffiliates.Items.Add(new RadComboBoxItem() { Selected = true, Text = affiliate.Name, Value = "" + affiliate.Id });
                        // set the sex to all
                        rblSex.Items.FindByValue("A").Selected = true;
                    }

                    baseUrl = ResolveUrl("~/");

                    Competition comp = null;
                    long compKey = 0;
                    if (Request["c"] != null)
                    {
                        compKey = Convert.ToInt64(Request["c"]);
                        comp = entities.Competitions.FirstOrDefault(c => c.Id == compKey);
                    }
                    if (compKey <= 0)
                    {
                        comp = entities.Competitions.FirstOrDefault();
                    }
                    workoutTabTitle.Text = "Competition: "+comp.Name;
                    atiWorkoutPanel.Visible = true;

                    var regionList = entities.CompetitionRegions.Select(r => new {Text = r.Name, Id = r.Id }).ToList();
                    ddlRegion.DataTextField = "Text";
                    ddlRegion.DataValueField = "Id";
                   // ddlRegion.DataSource = regionList;
                 //   ddlRegion.DataBind();
                    ddlRegion.Items.Add(new ListItem() { Text = "All Regions", Value = "0", Selected = true });
                    foreach (var item in regionList)
                    {
                        ddlRegion.Items.Add(new ListItem() { Text = item.Text, Value = "" + item.Id });
                    }
                    //RadGrid1.MasterTable

                    //var regionList = entities.Com.Select(r => new {Text = r.Name, Id = r.Id }).ToList();
                    //ddlAffiliate
                    if (RadGrid1.MasterTableView.SortExpressions.Count == 0)
                    {
                        GridSortExpression expression = new GridSortExpression();
                        expression.FieldName = "OverallRank";
                        expression.SortOrder = GridSortOrder.Ascending;
                        RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);
                    }
                    User angie = entities.UserSettings.OfType<User>().Include("CompetitionAthletes").FirstOrDefault(u => u.Id == 515);
                    atiFeaturedProfile.Settings = angie;
                    litRank.Text = "<span class=\"grad-FFF-EEE\" style=\"float: right; display: inline-block; border: 1px solid #ccc; text-align: center; padding: 7px;\">World Rank<br /><em style=\"font-size: 18px;\">" + angie.CompetitionAthletes.First().OverallRank + "</em></span>";

                    //grad-FFF-EEE
                }
            }
            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
            {
                ServiceReference service = new ServiceReference("~/DesktopModules/ATI_Base/resources/services/StreamService.asmx");
                service.InlineScript = true;
                ScriptManager.GetCurrent(Page).Services.Add(service);

                if (!Page.IsPostBack && !Page.IsCallback)
                {
                    aqufitEntities entities = new aqufitEntities();
                    if (Request["a"] != null)
                    {
                        long aId = Convert.ToInt64(Request["a"]);
                        CompetitionAffiliate affiliate = entities.CompetitionAffiliates.FirstOrDefault(a => a.Id == aId);
                        atiRadComboSearchAffiliates.Items.Add(new RadComboBoxItem()
                        {
                            Selected = true, Text = affiliate.Name, Value = "" + affiliate.Id
                        });
                        // set the sex to all
                        rblSex.Items.FindByValue("A").Selected = true;
                    }

                    baseUrl = ResolveUrl("~/");

                    Competition comp    = null;
                    long        compKey = 0;
                    if (Request["c"] != null)
                    {
                        compKey = Convert.ToInt64(Request["c"]);
                        comp    = entities.Competitions.FirstOrDefault(c => c.Id == compKey);
                    }
                    if (compKey <= 0)
                    {
                        comp = entities.Competitions.FirstOrDefault();
                    }
                    workoutTabTitle.Text    = "Competition: " + comp.Name;
                    atiWorkoutPanel.Visible = true;

                    var regionList = entities.CompetitionRegions.Select(r => new { Text = r.Name, Id = r.Id }).ToList();
                    ddlRegion.DataTextField  = "Text";
                    ddlRegion.DataValueField = "Id";
                    // ddlRegion.DataSource = regionList;
                    //   ddlRegion.DataBind();
                    ddlRegion.Items.Add(new ListItem()
                    {
                        Text = "All Regions", Value = "0", Selected = true
                    });
                    foreach (var item in regionList)
                    {
                        ddlRegion.Items.Add(new ListItem()
                        {
                            Text = item.Text, Value = "" + item.Id
                        });
                    }
                    //RadGrid1.MasterTable

                    //var regionList = entities.Com.Select(r => new {Text = r.Name, Id = r.Id }).ToList();
                    //ddlAffiliate
                    if (RadGrid1.MasterTableView.SortExpressions.Count == 0)
                    {
                        GridSortExpression expression = new GridSortExpression();
                        expression.FieldName = "OverallRank";
                        expression.SortOrder = GridSortOrder.Ascending;
                        RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);
                    }
                    User angie = entities.UserSettings.OfType <User>().Include("CompetitionAthletes").FirstOrDefault(u => u.Id == 515);
                    atiFeaturedProfile.Settings = angie;
                    litRank.Text = "<span class=\"grad-FFF-EEE\" style=\"float: right; display: inline-block; border: 1px solid #ccc; text-align: center; padding: 7px;\">World Rank<br /><em style=\"font-size: 18px;\">" + angie.CompetitionAthletes.First().OverallRank + "</em></span>";

                    //grad-FFF-EEE
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }