private SupplementCycleDefinition publishCycleDefinition(SupplementCycleDefinition db, Profile dbProfile)
        {
            if (dbProfile != db.Profile)
            {
                throw new CrossProfileOperationException("Cannot publish cycle definition for another user");
            }

            if (db.Profile.Statistics.SupplementEntriesCount < Constants.StrengthTrainingEntriesCount)
            {
                throw new ProfileRankException("You must have at least " + Constants.StrengthTrainingEntriesCount + " supplements entries to publish supplements cycle definition");
            }

            //we cannot modify published definition
            if (db.Status == PublishStatus.Published)
            {
                throw new PublishedObjectOperationException("Cannot change published cycle definition");
            }
            db.PublishDate = Configuration.TimerService.UtcNow;
            db.Status      = PublishStatus.Published;
            Session.Update(db);
            ProfileStatisticsUpdater.UpdateSupplementsDefinitions(Session, dbProfile);
            return(db);
            //now update cache modification date
            //TODO:Maybe finish?
            //profileDb.DataInfo.LastPlanModification = Configuration.TimerService.UtcNow;
            //session.Update(profileDb);
        }
Exemplo n.º 2
0
        //public WorkoutPlanDTO VoteWorkoutPlan( WorkoutPlanDTO planDto)
        //{
        //    Log.WriteWarning("VoteWorkoutPlan: Username={0},planId={1}", SecurityInfo.SessionData.Profile.UserName, planDto.GlobalId);

        //    var session = Session;
        //    using (var tx = session.BeginTransaction())
        //    {
        //        var dbProfile = session.Load<Profile>(SecurityInfo.SessionData.Profile.Id);
        //        var planFromDb = (from p in session.Query<BodyArchitect.Model.TrainingPlan>()
        //                          where p.GlobalId == planDto.GlobalId
        //                          select p).SingleOrDefault();
        //        saveRating(SecurityInfo, planDto, dbProfile, planFromDb);

        //        tx.Commit();

        //        try
        //        {
        //            //send message only when someone else vote
        //            if (planFromDb.Profile != dbProfile)
        //            {
        //                if (planFromDb.Profile.Settings.NotificationWorkoutPlanVoted)
        //                {
        //                    string param = string.Format("{0},{1},{2},{3}", planFromDb.Name, dbProfile.UserName, DateTime.Now, planDto.UserRating);
        //                    MessageService messageService = new MessageService(Session, SecurityInfo, Configuration, pushNotification);
        //                    messageService.SendSystemMessage(param, dbProfile, planFromDb.Profile, BodyArchitect.Model.MessageType.WorkoutPlanVoted);
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            ExceptionHandler.Default.Process(ex);
        //        }

        //        session.Refresh(planFromDb);
        //        Mapper.Map<BodyArchitect.Model.TrainingPlan, WorkoutPlanDTO>(planFromDb, planDto);
        //        return planDto;
        //    }

        //}

        //public ExerciseDTO VoteExercise( ExerciseDTO exercise)
        //{
        //    Log.WriteWarning("VoteExercise: Username={0},planId={1}", SecurityInfo.SessionData.Profile.UserName, exercise.GlobalId);

        //    var session = Session;
        //    using (var tx = session.BeginTransaction())
        //    {
        //        var dbProfile = session.Load<Profile>(SecurityInfo.SessionData.Profile.Id);
        //        var planFromDb = (from p in session.Query<BodyArchitect.Model.Exercise>()
        //                          where p.GlobalId == exercise.GlobalId
        //                          select p).SingleOrDefault();
        //        saveRating(SecurityInfo, exercise, dbProfile, planFromDb);

        //        tx.Commit();

        //        try
        //        {
        //            //send message only when someone else vote
        //            if (planFromDb.Profile != null && planFromDb.Profile != dbProfile)
        //            {
        //                if (planFromDb.Profile.Settings.NotificationExerciseVoted)
        //                {
        //                    string param = string.Format("{0},{1},{2},{3}", planFromDb.Name, dbProfile.UserName, DateTime.Now, exercise.UserRating);
        //                    MessageService messageService = new MessageService(Session, SecurityInfo, Configuration, pushNotification);
        //                    messageService.SendSystemMessage(param, dbProfile, planFromDb.Profile, BodyArchitect.Model.MessageType.ExerciseVoted);
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            ExceptionHandler.Default.Process(ex);
        //        }

        //        session.Refresh(planFromDb);
        //        Mapper.Map<BodyArchitect.Model.Exercise, ExerciseDTO>(planFromDb, exercise);
        //        return exercise;
        //    }

        //}

        float saveRating(SecurityInfo SecurityInfo, VoteParams ratingable, Profile profile, BodyArchitect.Model.IRatingable globalObject)
        {
            var session = Session;

            if (ratingable.UserRating != null)// && (ratingObject == null || ratingObject != null && ratingObject.Rating != ratingable.UserRating.Value))
            {
                var ratingObject = (from rating in session.Query <RatingUserValue>()
                                    where rating.ProfileId == profile.GlobalId && rating.RatedObjectId == globalObject.GlobalId
                                    select rating).SingleOrDefault();

                if (ratingObject == null)
                {
                    ratingObject               = new RatingUserValue();
                    ratingObject.ProfileId     = profile.GlobalId;
                    ratingObject.RatedObjectId = globalObject.GlobalId;
                }
                ratingObject.LoginData    = SecurityInfo.LoginData;
                ratingObject.Rating       = ratingable.UserRating.Value;
                ratingObject.ShortComment = ratingable.UserShortComment;
                ratingObject.VotedDate    = Configuration.TimerService.UtcNow;
                session.SaveOrUpdate(ratingObject);
                ProfileStatisticsUpdater.UpdateVotings(session, profile);
                //session.SaveOrUpdate(globalObject);
                //var res = (from t in session.Query<RatingUserValue>() where t.RatedObjectId == globalObject.GlobalId select t).Average(t => t.Rating);
                var res = session.QueryOver <RatingUserValue>().Where(t => t.RatedObjectId == globalObject.GlobalId).
                          SelectList(t => t.SelectAvg(r => r.Rating)).SingleOrDefault <double>();
                globalObject.Rating = (float)res;
                session.SaveOrUpdate(globalObject);

                return((float)res);
            }
            return(globalObject.Rating);
        }
        internal MyTraining StopMyTraining(Guid myTrainingId, Profile dbProfile)
        {
            var dbCycle = Session.QueryOver <MyTraining>()
                          .Fetch(x => x.EntryObjects).Eager
                          .Fetch(x => x.EntryObjects.First().TrainingDay).Eager
                          .Fetch(x => (((SuplementsEntry)x.EntryObjects.First()).Items).First().Suplement).Eager
                          .Fetch(x => ((StrengthTrainingEntry)x.EntryObjects.First()).Entries).Eager
                          .Fetch(x => ((StrengthTrainingEntry)x.EntryObjects.First()).MyPlace).Eager
                          .Fetch(x => (((StrengthTrainingEntry)x.EntryObjects.First()).Entries).First().Exercise).Eager
                          .Fetch(x => (((StrengthTrainingEntry)x.EntryObjects.First()).Entries.First().Series)).Eager
                          .Where(
                x => x.GlobalId == myTrainingId).SingleOrDefault();

            dbCycle = Session.Get <MyTraining>(myTrainingId);
            if (dbCycle.Profile != dbProfile)
            {
                throw new CrossProfileOperationException("MyTraining doesn't belong to this profile");
            }
            dbCycle.Complete(Configuration.TimerService);
            var plannedEntries = dbCycle.EntryObjects
                                 .Where(x => x.Status == EntryObjectStatus.Planned).ToList();
            bool trainingDayDeleted = false;

            foreach (var entryObject in plannedEntries)
            {
                dbCycle.EntryObjects.Remove(entryObject);
                var td = entryObject.TrainingDay;
                td.RemoveEntry(entryObject);
                Session.Delete(entryObject);
                if (td.IsEmpty)
                {
                    Session.Delete(td);
                    trainingDayDeleted = true;
                }
            }
            Session.Flush();
            if (trainingDayDeleted)
            {
                ProfileStatisticsUpdater.UpdateTrainindDay(Session, dbProfile);
            }
            Session.Update(dbCycle);
            return(dbCycle);
        }
Exemplo n.º 4
0
        void acceptInvitation(ISession session, Profile inviter, Profile invited, FriendInvitation existingInvitation, InviteFriendOperationData data)
        {
            Log.WriteVerbose("accept invitation. Friend:{0}, Inviter:{1}", inviter.UserName, invited.UserName);
            inviter.Friends.Add(invited);
            invited.Friends.Add(inviter);
            session.Update(inviter);
            session.Update(invited);
            session.Delete(existingInvitation);

            //now check and remove this user from followers list
            invited.FavoriteUsers.Remove(inviter);
            inviter.FavoriteUsers.Remove(invited);
            ProfileStatisticsUpdater.UpdateFriends(session, invited, inviter);
            //MessageService messageService = new MessageService(Session, null, Configuration, PushNotification);
            //messageService.SendSystemMessage(data.Message,invited, inviter, MessageType.InvitationAccepted);
            //SendMessage(inviter.Settings.NotificationSocial, invited, inviter, data.Message, MessageType.InvitationAccepted, "AcceptInvitationEMailSubject", "AcceptInvitationEMailMessage", inviter.UserName,DateTime.Now,data.Message);

            NewSendMessageEx(inviter.Settings.NotificationSocial, invited, inviter, "AcceptInvitationEMailSubject", "AcceptInvitationEMailMessage", inviter.UserName, DateTime.Now, data.Message);
        }
        public MyTrainingDTO MyTrainingOperation(MyTrainingOperationParam param)
        {
            Log.WriteWarning("MyTrainingOperation:Username={0},operation={1}", SecurityInfo.SessionData.Profile.UserName, param.Operation);

            using (var trans = Session.BeginSaveTransaction())
            {
                var        dbProfile = Session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId);
                MyTraining dbCycle   = null;
                if (param.Operation == MyTrainingOperationType.Start || param.Operation == MyTrainingOperationType.Simulate)
                {
                    dbCycle = param.MyTraining.Map <MyTraining>();
                    ensureCanStartMyTraining(dbCycle, dbProfile);
                    dbCycle.Profile = dbProfile;
                    if (dbCycle is A6WTraining)
                    {
                        startA6WTraining(param, (A6WTraining)dbCycle, dbProfile);
                    }
                    else if (dbCycle is SupplementCycle)
                    {
                        SupplementsCycleDTO cycleDto = (SupplementsCycleDTO)param.MyTraining;
                        startSupplementsCycle(param, (SupplementCycle)dbCycle, dbProfile, cycleDto.SupplementsCycleDefinitionId);
                    }
                    Session.Flush();
                    ProfileStatisticsUpdater.UpdateTrainindDay(Session, dbProfile);
                }
                else
                {
                    dbCycle = StopMyTraining(param.MyTraining.GlobalId, dbProfile);
                }
                Session.SaveOrUpdate(dbCycle);

                if (param.Operation != MyTrainingOperationType.Simulate)
                {//for simulate we must reject all changes in the db
                    trans.Commit();
                }

                return(dbCycle.Map <MyTrainingDTO>());
            }
        }
Exemplo n.º 6
0
        private BodyArchitect.Model.TrainingPlan publishWorkoutPlan(BodyArchitect.Model.TrainingPlan db, Profile dbProfile)
        {
            if (dbProfile != db.Profile)
            {
                throw new CrossProfileOperationException("Cannot publish cycle definition for another user");
            }

            //we cannot modify published definition
            if (db.Status == PublishStatus.Published)
            {
                throw new PublishedObjectOperationException("Cannot change published cycle definition");
            }
            if (db.Profile.Statistics.StrengthTrainingEntriesCount < Portable.Constants.StrengthTrainingEntriesCount)
            {
                throw new ProfileRankException("You must have at least " + Portable.Constants.StrengthTrainingEntriesCount + " strength training entries to publish workout plan");
            }

            db.PublishDate = Configuration.TimerService.UtcNow;
            db.Status      = PublishStatus.Published;

            var missingExercises = db.Days.SelectMany(x => x.Entries).Count(x => x.Exercise.IsDeleted);

            if (missingExercises > 0)
            {
                throw new ValidationException("Training plan cannot have missing exercises");
            }
            //workoutPlanExercisesOperation(Session, dbProfile, db, delegate(Exercise exercise)
            //{
            //    //if (exercise.Status != PublishStatus.Published)
            //    //{
            //    //    throw new PublishedObjectOperationException("Exercise: " + exercise.Name + " is not global so you cannot publish this workout plan");
            //    //}
            //});
            Session.Update(db);
            ProfileStatisticsUpdater.UpdateWorkoutPlans(Session, dbProfile);
            return(db);
        }
Exemplo n.º 7
0
        public TrainingDayCommentDTO TrainingDayCommentOperation(TrainingDayCommentOperationParam arg)
        {
            Log.WriteWarning("TrainingDayCommentOperationParam:Username={0},operation: {1},TrainingDayId={2}", SecurityInfo.SessionData.Profile.UserName, arg.OperationType, arg.TrainingDayId);

            if (SecurityInfo.SessionData.Profile.GlobalId != arg.Comment.Profile.GlobalId)
            {
                throw new CrossProfileOperationException("Cannot add comment for another user");
            }
            var session = Session;

            if (string.IsNullOrWhiteSpace(arg.Comment.Comment))
            {
                throw new ArgumentNullException("Comment cannot be empty");
            }
            var dbComment = Mapper.Map <TrainingDayCommentDTO, TrainingDayComment>(arg.Comment);

            using (var tx = session.BeginSaveTransaction())
            {
                var trainingDay = session.Get <TrainingDay>(arg.TrainingDayId);
                var dbProfile   = session.Get <Profile>(arg.Comment.Profile.GlobalId);
                if (trainingDay == null)
                {
                    throw new Shared.ObjectNotFoundException("Training Day doesn't exist");
                }
                if (!trainingDay.AllowComments)
                {
                    throw new InvalidOperationException("Comments are disabled for this training day");
                }

                if (arg.OperationType == TrainingDayOperationType.Add)
                {
                    if (!dbComment.IsNew)
                    {
                        throw new InvalidOperationException("Cannot add again existing comment");
                    }

                    dbComment.DateTime    = Configuration.TimerService.UtcNow;
                    dbComment.TrainingDay = trainingDay;
                    dbComment.Profile     = dbProfile;
                    dbComment.LoginData   = SecurityInfo.LoginData;
                    session.SaveOrUpdate(dbComment);

                    trainingDay.LastCommentDate = dbComment.DateTime;
                    session.SaveOrUpdate(trainingDay);
                }
                ProfileStatisticsUpdater.UpdateBlogComments(session, dbProfile);
                ProfileStatisticsUpdater.UpdateMyBlogComments(session, trainingDay);


                try
                {
                    //send message only when someone else add comment (when blog autor add the comment we don't need to send the message)
                    if (trainingDay.Profile != dbProfile)
                    {
                        //if ((trainingDay.Profile.Settings.NotificationBlogCommentAdded & ProfileNotification.Message) == ProfileNotification.Message)
                        //{
                        //    string param = string.Format("{0},{1},{2}", trainingDay.TrainingDate.ToShortDateString(), dbProfile.UserName, dbComment.DateTime);
                        //    MessageService messageService = new MessageService(Session, SecurityInfo, Configuration, pushNotification);
                        //    messageService.SendSystemMessage(param, dbProfile, trainingDay.Profile, MessageType.TrainingDayCommentAdded);
                        //}
                        //if ((trainingDay.Profile.Settings.NotificationBlogCommentAdded & ProfileNotification.Email) == ProfileNotification.Email)
                        //{
                        //    emailService.SendEMail(trainingDay.Profile, "AddTrainingDayCommentEMailSubject", "AddTrainingDayCommentEMailMessage", DateTime.Now, dbProfile.UserName, trainingDay.TrainingDate, arg.Comment);
                        //}
                        //string messageFormat = string.Format("{0},{1},{2}", trainingDay.TrainingDate.ToShortDateString(), dbProfile.UserName, dbComment.DateTime);
                        //SendMessage(trainingDay.Profile.Settings.NotificationBlogCommentAdded, dbProfile, trainingDay.Profile, messageFormat, MessageType.TrainingDayCommentAdded, "AddTrainingDayCommentEMailSubject", "AddTrainingDayCommentEMailMessage", DateTime.Now, dbProfile.UserName, trainingDay.TrainingDate, arg.Comment);
                        NewSendMessageEx(trainingDay.Profile.Settings.NotificationBlogCommentAdded, dbProfile, trainingDay.Profile, "AddTrainingDayCommentEMailSubject", "AddTrainingDayCommentEMailMessage", DateTime.Now, dbProfile.UserName, trainingDay.TrainingDate.ToShortDateString(), arg.Comment.Comment);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Default.Process(ex);
                }
                tx.Commit();
                return(Mapper.Map <TrainingDayComment, TrainingDayCommentDTO>(dbComment));
            }
        }
Exemplo n.º 8
0
        public FriendInvitationDTO InviteFriendOperation(InviteFriendOperationData data)
        {
            Log.WriteWarning("InviteFriendOperation:Username={0},Operation:{1},User:{2}", SecurityInfo.SessionData.Profile.UserName, data.Operation, data.User.UserName);

            if (SecurityInfo.SessionData.Profile.GlobalId == data.User.GlobalId)
            {
                throw new InvalidOperationException("You cannot add yourself as a friend");
            }
            var session = Session;

            FriendInvitation returnValue = null;

            using (var tx = session.BeginSaveTransaction())
            {
                var friendProfile = session.Get <Profile>(data.User.GlobalId);
                var inviter       = session.Get <Profile>(SecurityInfo.SessionData.Profile.GlobalId);

                if (friendProfile.IsDeleted)
                {
                    throw new UserDeletedException("Cannot invite a deleted profile");
                }
                if (data.Operation == Model.InviteFriendOperation.Invite)
                {
                    if (inviter.Friends.Contains(friendProfile))
                    {
                        throw new ProfileAlreadyFriendException("Specified profile is already a friend");
                    }
                    //check if user add invitation second time
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = inviter,
                        Invited = friendProfile
                    });
                    if (existingInvitation == null)
                    {
                        Log.WriteVerbose("1: existingInvitation == null");
                        existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                        {
                            Inviter = friendProfile,
                            Invited = inviter
                        });
                        if (existingInvitation == null)
                        {
                            Log.WriteVerbose("2: existingInvitation == null. Perform invite operation");
                            FriendInvitation invitation = new FriendInvitation();
                            invitation.Inviter        = inviter;
                            invitation.Invited        = friendProfile;
                            invitation.Message        = data.Message;
                            invitation.CreateDate     = Configuration.TimerService.UtcNow;
                            invitation.InvitationType = FriendInvitationType.Invite;
                            session.Save(invitation);
                            returnValue = invitation;

                            if ((friendProfile.Settings.NotificationSocial & ProfileNotification.Email) == ProfileNotification.Email)
                            {
                                EmailService.SendEMail(friendProfile, "InviteFriendEMailSubject", "InviteFriendEMailMessage", inviter.UserName, DateTime.Now, data.Message);
                            }
                        }
                        else
                        {
                            acceptInvitation(session, friendProfile, inviter, existingInvitation, data);
                        }
                    }
                }
                else if (data.Operation == Model.InviteFriendOperation.Accept)
                {
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = friendProfile,
                        Invited = inviter
                    });
                    if (existingInvitation != null)
                    {
                        acceptInvitation(session, friendProfile, inviter, existingInvitation, data);
                    }
                    else
                    {
                        throw new CannotAcceptRejectInvitationDoesntExistException("You are not invited to be a friend for specified user");
                    }
                }
                else
                {//reject
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = friendProfile,
                        Invited = inviter
                    });

                    if (existingInvitation != null)
                    {
                        Log.WriteVerbose("3: existingInvitation != null.");
                        if (existingInvitation.InvitationType == FriendInvitationType.Invite)
                        {
                            session.Delete(existingInvitation);

                            //messageService.SendSystemMessage(data.Message, inviter, friendProfile, MessageType.InvitationRejected);
                            //SendMessage(friendProfile.Settings.NotificationSocial, inviter, friendProfile, data.Message, MessageType.InvitationRejected
                            //, "RejectInvitationEmailSubject", "RejectInvitationEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                            NewSendMessageEx(inviter.Settings.NotificationSocial, inviter, friendProfile, "RejectInvitationEmailSubject", "RejectInvitationEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        }
                        else
                        {
                            Log.WriteError("4:This should not be invoked.");
                        }
                    }
                    else if (inviter.Friends.Contains(friendProfile))
                    {
                        Log.WriteVerbose("Reject friendship");
                        inviter.Friends.Remove(friendProfile);
                        friendProfile.Friends.Remove(inviter);
                        ProfileStatisticsUpdater.UpdateFriends(session, inviter, friendProfile);
                        //SendMessage(friendProfile.Settings.NotificationSocial, inviter, friendProfile, data.Message, MessageType.FriendshipRejected
                        //    , "RejectFriendshipEmailSubject", "RejectFriendshipEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        NewSendMessageEx(inviter.Settings.NotificationSocial, inviter, friendProfile, "RejectFriendshipEmailSubject", "RejectFriendshipEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        //messageService.SendSystemMessage(data.Message, inviter, friendProfile, MessageType.FriendshipRejected);
                    }
                    else
                    {
                        existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                        {
                            Inviter = inviter,
                            Invited = friendProfile
                        });
                        //user whats to cancel invitation
                        if (existingInvitation != null)
                        {
                            Log.WriteVerbose("Reject invitation");
                            session.Delete(existingInvitation);
                        }
                        else
                        {
                            throw new CannotAcceptRejectInvitationDoesntExistException("There is no invitation to reject");
                        }
                    }
                }


                tx.Commit();
                Log.WriteVerbose("Operation completed");
                if (returnValue != null)
                {
                    return(ObjectsConverter.ConvertFriendInvitation(inviter, returnValue));
                }
                return(null);
            }
        }