Exemple #1
0
        /// <summary>
        /// Function to change password
        /// </summary>
        /// <param></param>
        /// <returns>bool</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 07/24/2015
        /// </devdoc>
        public static bool ChangePassword(EditPasswordVM model)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                EncryptDecrypt objEncrypt = null;
                Credentials    cred       = null;
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChangePassword");
                    bool flag = false;
                    cred = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    if (cred != null)
                    {
                        if (IsOldPasswordCorrect(model.OldPassword, cred.Id))
                        {
                            objEncrypt = new EncryptDecrypt();
                            tblCredentials objCredential = _dbContext.Credentials.Where(crd => crd.Id == cred.Id).FirstOrDefault();
                            model.NewPassword = objEncrypt.EncryptString(model.NewPassword);
                            if (objCredential != null)
                            {
                                objCredential.Password = model.NewPassword;
                            }
                            _dbContext.SaveChanges();
                            flag = true;
                        }
                    }
                    return(flag);
                }
                finally
                {
                    if (objEncrypt != null)
                    {
                        objEncrypt.Dispose();
                        objEncrypt = null;
                    }
                    traceLog.AppendLine("End: ChangePassword --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Select UserPersonalTrainer
        /// </summary>
        /// <param name="usertrainerdetails"></param>
        /// <returns></returns>
        public static bool SelectUserPersonalTrainer(UserPersonalTrainerVM usertrainerdetails)
        {
            StringBuilder traceLog = new StringBuilder();

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                try
                {
                    traceLog.AppendLine("Start: SelectUserPersonalTrainer---- " + DateTime.Now.ToLongDateString());
                    if (usertrainerdetails.TrainerCredID > 0)
                    {
                        Credentials cred = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                        if (cred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                        {
                            tblUser user = dataContext.User.FirstOrDefault(usr => usr.UserId == cred.UserId);
                            if (user != null)
                            {
                                user.PersonalTrainerCredId = usertrainerdetails.TrainerCredID;
                                dataContext.SaveChanges();
                                if (usertrainerdetails.TrainerCredID > 0)
                                {
                                    string selectedUserName = string.Empty;
                                    selectedUserName = user.FirstName + " " + user.LastName;
                                    NotificationApiBL.SendSelectPrimaryTrainerNotificationToTrainer(usertrainerdetails.TrainerCredID, selectedUserName, cred.UserId, cred.UserType);
                                }
                                return(true);
                            }
                        }
                    }
                    return(false);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetTrainerLibraryChallengeList : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Function to post boom on challenge completed(Comment Section)
        /// </summary>
        /// <returns>int</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 05/06/2015
        /// </devdoc>
        public static int PostBoom(ViewPostVM model)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChallengeMessageFeedBL PostBoom");
                    Credentials objCred = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    if (!_dbContext.Booms.Any(b => b.MessageStraemId == model.PostId && b.BoomedBy == objCred.Id))
                    {
                        tblBoom objBoom = new tblBoom();
                        objBoom.BoomedBy        = objCred.Id;
                        objBoom.BoomedDate      = DateTime.Now;
                        objBoom.MessageStraemId = model.PostId;
                        _dbContext.Booms.Add(objBoom);
                        _dbContext.SaveChanges();
                        // Send the User Notification to user on result boomed
                        if (model.UserId > 0 && !string.IsNullOrEmpty(model.UserType) && !(objCred.UserType == model.UserType && objCred.UserId == model.UserId))
                        {
                            NotificationApiBL.SendNotificationToALLNType(model.UserId, model.UserType, NotificationType.NewsFeedBoomed.ToString(), objCred, model.PostId);
                        }
                    }

                    return(_dbContext.Booms.Count(b => b.MessageStraemId == model.PostId));
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End : ChallengeMessageFeedBL PostBoom  : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Save Chat History
        /// </summary>
        /// <param name="chatHistory"></param>
        /// <returns></returns>
        public static void SaveChatHistory(ChatHistoryVM chatHistory)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                traceLog = new StringBuilder();
                try
                {
                    traceLog.AppendLine("Start: SaveChatHistory() for receiver Id");
                    Credentials cred = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    if (chatHistory != null && chatHistory.ReceiverCredId > 0 && chatHistory.SenderCredId > 0 && !string.IsNullOrEmpty(chatHistory.Message))
                    {
                        tblChatHistory objChatHistory = new tblChatHistory()
                        {
                            ReceiverCredId     = chatHistory.ReceiverCredId,
                            SenderCredId       = cred.Id,
                            Message            = chatHistory.Message,
                            IsRead             = false,
                            TrasactionDateTime = DateTime.UtcNow,
                        };
                        dataContext.ChatHistory.Add(objChatHistory);
                        dataContext.SaveChanges();
                    }
                    return;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("SaveChatHistory  end() : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Get trainer challenge list with free from for trainer
        /// </summary>
        /// <returns></returns>
        /// <devdoc>
        /// Developer Name - Irshad Ansari
        /// Date - 04/26/2016
        /// </devdoc>
        public static List <MainChallengeVM> GetTrainerLibraryChallengeListWithFreeForm(ref bool isTeamJoined)
        {
            StringBuilder traceLog = new StringBuilder();

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                try
                {
                    traceLog.AppendLine("Start: GetTrainerLibraryChallengeListWithFreeForm---- " + DateTime.Now.ToLongDateString());
                    int         teamId         = -1;
                    List <int>  trainerCrediId = new List <int>();
                    Credentials cred           = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    if (cred.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                    {
                        var objtrainer = dataContext.Trainer.FirstOrDefault(u => u.TrainerId == cred.UserId);
                        if (objtrainer != null)
                        {
                            teamId = objtrainer.TeamId;
                        }
                        trainerCrediId.Add(cred.Id);
                    }
                    else if (cred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                    {
                        var objuser = dataContext.User.FirstOrDefault(u => u.UserId == cred.UserId);
                        if (objuser != null)
                        {
                            teamId = objuser.TeamId;
                        }
                        trainerCrediId = (from tr in dataContext.Trainer
                                          join crd in dataContext.Credentials
                                          on tr.TrainerId equals crd.UserId
                                          where crd.UserType == Message.UserTypeTrainer && tr.TeamId == teamId
                                          select crd.Id
                                          ).ToList();
                    }
                    isTeamJoined = teamId > 0 ? true : false;
                    List <MainChallengeVM> listMainVM = (from c in dataContext.Challenge
                                                         join ct in dataContext.ChallengeType on c.ChallengeSubTypeId equals ct.ChallengeSubTypeId
                                                         where c.IsActive && trainerCrediId.Contains(c.TrainerId)
                                                         orderby c.CreatedDate descending
                                                         select new MainChallengeVM
                    {
                        ChallengeId = c.ChallengeId,
                        ChallengeName = c.ChallengeName,
                        DifficultyLevel = c.DifficultyLevel,
                        ChallengeType = ct.ChallengeType,
                        Description = c.Description,
                        IsSubscription = c.IsSubscription,
                        TempEquipments = (from trzone in dataContext.ChallengeEquipmentAssociations
                                          join bp in dataContext.Equipments
                                          on trzone.EquipmentId equals bp.EquipmentId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.Equipment).Distinct().ToList <string>(),
                        TempTargetZone = (from trzone in dataContext.TrainingZoneCAssociations
                                          join bp in dataContext.BodyPart
                                          on trzone.PartId equals bp.PartId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.PartName).Distinct().ToList <string>(),
                        Strenght = dataContext.UserChallenge.Where(uc => uc.ChallengeId == c.ChallengeId).Select(y => y.UserId).Distinct().Count(),
                        ResultUnit = ct.ResultUnit,
                        IsWellness = (ct.ChallengeSubTypeId == ConstantHelper.constWellnessChallengeSubType) ? true : false,
                    }).ToList();
                    if (listMainVM != null && listMainVM.Count > 0)
                    {
                        listMainVM.ForEach(r =>
                        {
                            r.ChallengeType = r.ChallengeType.Split(' ')[0];
                            if (r.TempTargetZone != null && r.TempTargetZone.Count > 0)
                            {
                                r.TargetZone = string.Join(", ", r.TempTargetZone);
                            }
                            r.TempTargetZone = null;
                            if (r.TempEquipments != null && r.TempEquipments.Count > 0)
                            {
                                r.Equipment = string.Join(", ", r.TempEquipments);
                            }
                            r.TempEquipments = null;
                        });
                        //Challenge feed sorted by acceptors
                        listMainVM = listMainVM.OrderByDescending(chlng => chlng.Strenght).ToList();
                    }
                    return(listMainVM);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetTrainerLibraryChallengeListWithFreeForm : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Get FreePremium ChallengeList basd on team Id
        /// </summary>
        /// <param name="isTeamJoined"></param>
        /// <returns></returns>
        /// <devdoc>
        /// Developer Name - Irshad Ansari
        /// Date - 04/26/2016
        /// </devdoc>
        public static PremimumChallengeVM GetFreePremiumChallengeList(ref bool isTeamJoined)
        {
            StringBuilder traceLog = new StringBuilder();

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                try
                {
                    traceLog.AppendLine("Start: GetFreePremiumChallengeList---- " + DateTime.Now.ToLongDateString());
                    PremimumChallengeVM objPremimumChallengeVM = new PremimumChallengeVM();
                    List <int>          trainerCrediId         = new List <int>();
                    Credentials         cred    = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    List <int>          teamIds = new List <int>();
                    switch (cred.UserType)
                    {
                    case ConstantHelper.constuser:
                        teamIds = (from usr in dataContext.User
                                   join crd in dataContext.Credentials
                                   on usr.UserId equals crd.UserId
                                   where crd.Id == cred.Id && crd.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase)
                                   select usr.TeamId).ToList();
                        break;

                    case ConstantHelper.consttrainer:
                        teamIds = (from crd in dataContext.Credentials
                                   join tms in dataContext.TrainerTeamMembers
                                   on crd.Id equals tms.UserId
                                   orderby tms.RecordId ascending
                                   where crd.Id == cred.Id && crd.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase)
                                   select tms.TeamId).ToList();
                        break;
                    }
                    if (teamIds.Count > 0)
                    {
                        trainerCrediId = (from crd in dataContext.Credentials
                                          join tms in dataContext.TrainerTeamMembers
                                          on crd.Id equals tms.UserId
                                          where teamIds.Contains(tms.TeamId) && crd.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase)
                                          select tms.UserId).ToList();
                    }
                    if (teamIds != null && teamIds.Count > 0)
                    {
                        isTeamJoined = true;
                    }
                    List <MainChallengeVM> listMainVM = (from c in dataContext.Challenge
                                                         join ct in dataContext.ChallengeType on c.ChallengeSubTypeId equals ct.ChallengeSubTypeId
                                                         where c.IsActive &&
                                                         (trainerCrediId.Contains(c.TrainerId) || (c.IsPremium && c.TrainerId == 0))
                                                         orderby c.ChallengeName ascending
                                                         select new MainChallengeVM
                    {
                        ChallengeId = c.ChallengeId,
                        ChallengeName = c.ChallengeName,
                        DifficultyLevel = c.DifficultyLevel,
                        ChallengeType = ct.ChallengeType,
                        Description = c.Description,
                        IsSubscription = c.IsSubscription,
                        TempEquipments = (from trzone in dataContext.ChallengeEquipmentAssociations
                                          join bp in dataContext.Equipments
                                          on trzone.EquipmentId equals bp.EquipmentId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.Equipment).Distinct().ToList <string>(),
                        TempTargetZone = (from trzone in dataContext.TrainingZoneCAssociations
                                          join bp in dataContext.BodyPart
                                          on trzone.PartId equals bp.PartId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.PartName).Distinct().ToList <string>(),
                        Strenght = dataContext.UserChallenge.Where(uc => uc.ChallengeId == c.ChallengeId).Select(y => y.UserId).Distinct().Count(),
                        ResultUnit = ct.ResultUnit
                    }).ToList();
                    if (listMainVM != null && listMainVM.Count > 0)
                    {
                        listMainVM.ForEach(r =>
                        {
                            r.ChallengeType = r.ChallengeType.Split(' ')[0];
                            if (r.TempTargetZone != null && r.TempTargetZone.Count > 0)
                            {
                                r.TargetZone = string.Join(", ", r.TempTargetZone);
                            }
                            r.TempTargetZone = null;
                            if (r.TempEquipments != null && r.TempEquipments.Count > 0)
                            {
                                r.Equipment = string.Join(", ", r.TempEquipments);
                            }
                            r.TempEquipments = null;
                        });
                        //Challenge feed sorted by acceptors
                        listMainVM = listMainVM.OrderBy(chlng => chlng.ChallengeName).ToList();
                    }

                    objPremimumChallengeVM.PremimumChallegeList = listMainVM;
                    objPremimumChallengeVM.PremimumTypeList     = ChallengesCommonBL.GetPremiumChallengeCategoryList();

                    var challengeCategoryList = ChallengesCommonBL.GetapiPreminumChallengeCategoryList(ConstantHelper.constWorkoutChallengeSubType, trainerCrediId);
                    if (challengeCategoryList != null)
                    {
                        objPremimumChallengeVM.PremimumWorksoutList = challengeCategoryList.ChallengeCategoryList;
                        objPremimumChallengeVM.FeaturedList         = challengeCategoryList.FeaturedList;
                        objPremimumChallengeVM.TrendingList         = challengeCategoryList.TrendingCategoryList;
                    }
                    return(objPremimumChallengeVM);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetFreePremiumChallengeList : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Function to get challenge details of sponsor challenge
        /// </summary>
        /// <returns>SponsorChallengeDetailVM</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 03/31/2015
        /// </devdoc>
        public static SponsorChallengeDetailVM GetSponsorChallengeDetails(int challengeId)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: GetSponsorChallengeDetails---- " + DateTime.Now.ToLongDateString());
                    SponsorChallengeDetailVM objChallengedetail = (from c in _dbContext.Challenge
                                                                   join cred in _dbContext.Credentials on c.CreatedBy equals cred.Id
                                                                   join ct in _dbContext.ChallengeType on c.ChallengeSubTypeId equals ct.ChallengeSubTypeId
                                                                   join tc in _dbContext.TrainerChallenge on c.ChallengeId equals tc.ChallengeId
                                                                   join uc in _dbContext.UserChallenge on tc.ResultId equals uc.Id
                                                                   join h in _dbContext.HypeVideos on tc.HypeVideoId equals h.RecordId
                                                                   where c.ChallengeId == challengeId && c.IsActive == true
                                                                   select new SponsorChallengeDetailVM
                    {
                        ChallengeId = c.ChallengeId,
                        ChallengeName = c.ChallengeName,
                        DifficultyLevel = c.DifficultyLevel,
                        ChallengeType = ct.ChallengeType,
                        Strenght = _dbContext.UserChallenge.Where(uchlng => uchlng.ChallengeId == c.ChallengeId).Select(y => y.UserId).Distinct().Count(),
                        ResultUnit = ct.ResultUnit,
                        ResultUnitSuffix = uc.ResultUnit,
                        ChallengeDescription = ct.ChallengeSubType,
                        Excercises = (from exer in _dbContext.Exercise
                                      join ce in _dbContext.CEAssociation on exer.ExerciseId equals ce.ExerciseId
                                      where ce.ChallengeId == c.ChallengeId
                                      select new ExerciseVM
                        {
                            ExerciseId = exer.ExerciseId,
                            ExerciseName = exer.ExerciseName,
                            ExcersiceDescription = exer.Description,
                            ChallengeExcerciseDescription = ce.Description,
                            VedioLink = exer.VideoLink,
                            Index = exer.Index,
                            Reps = ce.Reps,
                            WeightForManDB = ce.WeightForMan,
                            WeightForWomanDB = ce.WeightForWoman,
                        }).ToList(),
                        HypeVideo = h.HypeVideo,
                        Result = (uc.Result == null ? "" : uc.Result) + " " + (uc.Fraction == null ? "" : uc.Fraction),
                        VariableValue = c.VariableValue,
                        ChallengeSubTypeId = ct.ChallengeSubTypeId,
                        VariableUnit = ct.Unit,
                        CreatedByUserType = cred.UserType,
                        CreatedByTrainerId = cred.UserId,
                        PersonalBestUserId = uc.UserId
                    }).FirstOrDefault();
                    if (objChallengedetail != null)
                    {
                        if (objChallengedetail.ResultUnit.Equals("Time"))
                        {
                            objChallengedetail.Result = CommonApiBL.GetChallengeResultBasedOnResultUnit(objChallengedetail.Result);
                        }
                        if (!string.IsNullOrEmpty(objChallengedetail.Result))
                        {
                            objChallengedetail.Result = objChallengedetail.Result.Trim();
                        }
                        if (!string.IsNullOrEmpty(objChallengedetail.ChallengeType))
                        {
                            objChallengedetail.ChallengeType = objChallengedetail.ChallengeType.Split(' ')[0];
                        }
                        if (objChallengedetail.CreatedByUserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                        {
                            var objTrainer = _dbContext.Trainer.FirstOrDefault(t => t.TrainerId == objChallengedetail.CreatedByTrainerId);
                            if (objTrainer != null)
                            {
                                objChallengedetail.CreatedByTrainerName = objTrainer.FirstName + " " + objTrainer.LastName;
                                objChallengedetail.CreatedByProfilePic  = string.IsNullOrEmpty(objTrainer.TrainerImageUrl) ? string.Empty :
                                                                          CommonUtility.VirtualPath + Message.ProfilePicDirectory + objTrainer.TrainerImageUrl;
                            }
                        }
                        else
                        {
                            objChallengedetail.CreatedByTrainerId = 0;
                        }
                    }
                    objChallengedetail.Excercises.ForEach(
                        exer =>
                    {
                        exer.WeightForMan     = exer.WeightForManDB > 0 ? exer.WeightForManDB.ToString() + " " + ConstantHelper.constlbs : null;
                        exer.WeightForWoman   = exer.WeightForWomanDB > 0 ? exer.WeightForWomanDB.ToString() + " " + ConstantHelper.constlbs : null;
                        exer.VedioLink        = CommonUtility.VirtualFitComExercisePath + Message.ExerciseVideoDirectory + exer.VedioLink;
                        exer.ExerciseThumnail = CommonWebApiBL.GetSaveExerciseThumbnail(exer.VedioLink, exer.ExerciseName);
                    });
                    string tempdesc = string.Empty;
                    if (objChallengedetail != null && !string.IsNullOrEmpty(objChallengedetail.VariableValue))
                    {
                        tempdesc = CommonApiBL.GetChallengeVariableValueBasedVariableUnit(objChallengedetail.VariableValue, objChallengedetail.VariableUnit);
                    }
                    ////End the modification
                    if (!string.IsNullOrEmpty(tempdesc))
                    {
                        tempdesc = tempdesc.Trim();
                    }
                    objChallengedetail.ChallengeDescription = objChallengedetail.ChallengeDescription.Replace("____", tempdesc)
                                                              .Replace(ConstantHelper.constAmoutOfTime, ConstantHelper.constQustionMark).
                                                              Replace(ConstantHelper.constAmoutOfTimeSecond, ConstantHelper.constQustionMark);
                    if (objChallengedetail != null && !string.IsNullOrEmpty(objChallengedetail.VariableValue))
                    {
                        objChallengedetail.VariableValue = CommonApiBL.GetChallengeVariableValueBasedOnTime(objChallengedetail.VariableValue);
                    }
                    tblCredentials objCredentials = _dbContext.Credentials.FirstOrDefault(c => c.Id == objChallengedetail.PersonalBestUserId);
                    if (objCredentials != null)
                    {
                        objChallengedetail.PersonalBestUserName = CommonReportingUtility.GetUserFullNameBasedUserCredIdAndUserType(_dbContext, objCredentials.Id, objCredentials.UserType);
                    }
                    return(objChallengedetail);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetSponsorChallengeDetails : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Function to get comment list of a challenge completed(Comment Section)
        /// </summary>
        /// <returns>Total<List<CommentVM>></returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 05/06/2015
        /// </devdoc>
        public static Total <List <CommentVM> > GetCommentList(int messageStreamId, int startIndex, int endIndex)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChallengeMessageFeedBL GetCommentList");

                    var result = (from cmnt in _dbContext.Comments
                                  join c in _dbContext.Credentials on cmnt.CommentedBy equals c.Id
                                  where cmnt.MessageStraemId == messageStreamId
                                  orderby cmnt.CommentedDate descending
                                  select new
                    {
                        _Credential = c,
                        _Comment = cmnt
                    }).ToList();
                    List <CommentVM> objCommentList = new List <CommentVM>();
                    foreach (var item in result)
                    {
                        CommentVM objComment = new CommentVM();
                        objComment.CommentDate       = CommonWebApiBL.GetDateTimeFormat(item._Comment.CommentedDate);
                        objComment.PostedCommentDate = item._Comment.CommentedDate.ToUniversalTime();
                        objComment.CommentId         = item._Comment.CommentId;
                        objComment.Message           = item._Comment.Message;
                        if (item._Credential.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                        {
                            var user = _dbContext.User.FirstOrDefault(u => u.UserId == item._Credential.UserId);
                            if (user != null)
                            {
                                objComment.UserName = user.FirstName + " " + user.LastName;
                                objComment.ImageUrl = string.IsNullOrEmpty(user.UserImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + user.UserImageUrl;
                                objComment.UserId   = user.UserId;
                                objComment.UserType = Message.UserTypeUser;
                            }
                        }
                        else if (item._Credential.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                        {
                            var trainer = _dbContext.Trainer.FirstOrDefault(t => t.TrainerId == item._Credential.UserId);
                            if (trainer != null)
                            {
                                objComment.UserName = trainer.FirstName + " " + trainer.LastName;
                                objComment.ImageUrl = string.IsNullOrEmpty(trainer.TrainerImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + trainer.TrainerImageUrl;
                                objComment.UserId   = trainer.TrainerId;
                                objComment.UserType = Message.UserTypeTrainer;
                            }
                        }
                        objCommentList.Add(objComment);
                    }
                    Total <List <CommentVM> > objresult = new Total <List <CommentVM> >();
                    objresult.TotalList = (from l in objCommentList
                                           select l).Skip(startIndex).Take(endIndex - startIndex).ToList().OrderBy(c => c.CommentId).ToList();;
                    objresult.TotalCount = objCommentList.Count();
                    if ((objresult.TotalCount) > endIndex)
                    {
                        objresult.IsMoreAvailable = true;
                    }
                    return(objresult);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End : ChallengeMessageFeedBL GetCommentList  : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Function to post comment on challenge completed(Comment Section)
        /// </summary>
        /// <returns>CommentVM</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 05/06/2015
        /// </devdoc>
        public static CommentVM PostComment(CommentVM model)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChallengeMessageFeedBL PostComment");
                    Credentials cred       = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    tblComment  objComment = new tblComment();
                    objComment.CommentedBy     = cred.Id;
                    objComment.CommentedDate   = DateTime.Now;
                    objComment.Message         = model.Message;
                    objComment.MessageStraemId = model.PostId;
                    _dbContext.Comments.Add(objComment);
                    _dbContext.SaveChanges();
                    // User Notification when user post message on other user or trainer post data their team member
                    if (!string.IsNullOrEmpty(model.UserType) && model.UserId == cred.UserId && cred.UserType == model.UserType)
                    {
                        NotificationApiBL.SendALLSenderNotificationByUser(model.PostId, NotificationType.NewsFeedCommented.ToString(), NotificationType.PostCommentedReplyMsg.ToString(), cred);
                    }
                    else if (model.UserId > 0 && !string.IsNullOrEmpty(model.UserType))
                    {
                        NotificationApiBL.SendNotificationToALLNType(model.UserId, model.UserType, NotificationType.NewsFeedCommented.ToString(), cred, model.PostId);
                        NotificationApiBL.SendALLSenderNotificationByUser(model.PostId, NotificationType.NewsFeedCommented.ToString(), NotificationType.PostCommentedReplyMsg.ToString(), cred);
                    }
                    CommentVM objCommentVM = new CommentVM()
                    {
                        CommentId         = objComment.CommentId,
                        PostId            = model.PostId,
                        CommentBy         = objComment.CommentedBy,
                        Message           = model.Message,
                        CommentDate       = CommonWebApiBL.GetDateTimeFormat(objComment.CommentedDate),
                        PostedCommentDate = objComment.CommentedDate.ToUniversalTime()
                    };

                    if (cred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                    {
                        var user = _dbContext.User.FirstOrDefault(u => u.UserId == cred.UserId);
                        if (user != null)
                        {
                            objCommentVM.ImageUrl = string.IsNullOrEmpty(user.UserImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + user.UserImageUrl;
                            objCommentVM.UserName = user.FirstName + " " + user.LastName;
                            objCommentVM.UserId   = user.UserId;
                            objCommentVM.UserType = Message.UserTypeUser;
                        }
                    }
                    else if (cred.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                    {
                        var trainer = _dbContext.Trainer.FirstOrDefault(t => t.TrainerId == cred.UserId);
                        if (trainer != null)
                        {
                            objCommentVM.ImageUrl = string.IsNullOrEmpty(trainer.TrainerImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + trainer.TrainerImageUrl;
                            objCommentVM.UserName = trainer.FirstName + " " + trainer.LastName;
                            objCommentVM.UserId   = trainer.TrainerId;
                            objCommentVM.UserType = Message.UserTypeTrainer;
                        }
                    }
                    return(objCommentVM);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End : ChallengeMessageFeedBL PostComment  : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Function to post Share message text on challenge completed(Comment Section)
        /// </summary>
        /// <returns>ViewPostVM</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 05/06/2015
        /// </devdoc>
        public static ViewPostVM PostShare(PostVM <TextMessageStream> message)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChallengeMessageFeedBL PostShare");
                    Credentials      objCred          = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    tblMessageStream objMessageStream = new tblMessageStream();
                    objMessageStream.Content          = message.Stream.TextMessage;
                    objMessageStream.MessageType      = Message.TextMessageType;
                    objMessageStream.PostedDate       = DateTime.Now;
                    objMessageStream.TargetType       = Message.ChallengeTargetType;
                    objMessageStream.SubjectId        = objCred.Id;
                    objMessageStream.TargetId         = message.TargetId; //ChallengeId is assigned.
                    objMessageStream.IsTextImageVideo = true;
                    objMessageStream.IsImageVideo     = message.IsImageVideo;
                    _dbContext.MessageStraems.Add(objMessageStream);
                    _dbContext.SaveChanges();
                    if (objCred.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                    {
                        // User Notification when user post message on other user or trainer post data their team member
                        NotificationApiBL.SendALLTeamNotificationByTrainer(objCred.UserId, objMessageStream.MessageStraemId, objCred.UserId, objCred.UserType);
                    }
                    ViewPostVM objViewPostVM = new ViewPostVM()
                    {
                        PostId        = objMessageStream.MessageStraemId,
                        Message       = objMessageStream.Content,
                        PostedDate    = CommonWebApiBL.GetDateTimeFormat(objMessageStream.PostedDate),
                        BoomsCount    = _dbContext.Booms.Count(b => b.MessageStraemId == objMessageStream.MessageStraemId),
                        CommentsCount = _dbContext.Comments.Count(cmnt => cmnt.MessageStraemId == objMessageStream.MessageStraemId)
                    };
                    if (objCred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                    {
                        var user = (from usr in _dbContext.User
                                    join crd in _dbContext.Credentials on usr.UserId equals crd.UserId
                                    where crd.UserType == Message.UserTypeUser && crd.Id == objMessageStream.SubjectId
                                    select new
                        {
                            usr.FirstName,
                            usr.LastName,
                            usr.UserImageUrl,
                            crd.UserId,
                            crd.UserType
                        }).FirstOrDefault();
                        if (user != null)
                        {
                            objViewPostVM.PostedByImageUrl = string.IsNullOrEmpty(user.UserImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + user.UserImageUrl;
                            objViewPostVM.UserName         = user.FirstName + " " + user.LastName;
                            objViewPostVM.UserId           = user.UserId;
                            objViewPostVM.UserType         = user.UserType;
                        }
                    }
                    else if (objCred.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                    {
                        var trainer = (from t in _dbContext.Trainer
                                       join crd in _dbContext.Credentials on t.TrainerId equals crd.UserId
                                       where crd.UserType == Message.UserTypeTrainer && crd.Id == objMessageStream.SubjectId
                                       select new
                        {
                            t.FirstName,
                            t.LastName,
                            t.TrainerImageUrl,
                            crd.UserId,
                            crd.UserType
                        }).FirstOrDefault();
                        if (trainer != null)
                        {
                            objViewPostVM.PostedByImageUrl = string.IsNullOrEmpty(trainer.TrainerImageUrl) ? string.Empty :
                                                             CommonUtility.VirtualPath + Message.ProfilePicDirectory + trainer.TrainerImageUrl;
                            objViewPostVM.UserName = trainer.FirstName + " " + trainer.LastName;
                            objViewPostVM.UserId   = trainer.UserId;
                            objViewPostVM.UserType = trainer.UserType;
                        }
                    }
                    return(objViewPostVM);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End:ChallengeMessageFeedBL PostShare --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Function to get post list on challenge completed(Comment Section)
        /// </summary>
        /// <returns>Total<List<ChallengeViewPostVM>></returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 05/13/2015
        /// </devdoc>
        public static Total <List <ChallengeViewPostVM> > GetPostListForChallenge(int challengeId, int startIndex, int endIndex)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: ChallengeMessageFeedBL GetPostList");

                    Credentials userCredential         = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    List <ChallengeViewPostVM> objList = (from m in _dbContext.MessageStraems
                                                          join c in _dbContext.Credentials on m.SubjectId equals c.Id
                                                          where m.TargetId == challengeId && m.IsImageVideo &&
                                                          (!(string.IsNullOrEmpty(m.Content)) || m.IsImageVideo) &&
                                                          m.TargetType == Message.ChallengeTargetType &&
                                                          m.IsTextImageVideo == true
                                                          orderby m.PostedDate descending
                                                          select new ChallengeViewPostVM
                    {
                        PostId = m.MessageStraemId,
                        DbPostedDate = m.PostedDate,
                        Message = m.Content,
                        BoomsCount = _dbContext.Booms.Count(b => b.MessageStraemId == m.MessageStraemId),
                        CommentsCount = _dbContext.Comments.Count(cmnt => cmnt.MessageStraemId == m.MessageStraemId),
                        PostedBy = m.SubjectId,
                        UserId = _dbContext.Credentials.FirstOrDefault(crede => crede.Id == m.SubjectId).UserId,
                        UserType = _dbContext.Credentials.FirstOrDefault(crede => crede.Id == m.SubjectId).UserType,
                        IsLoginUserBoom = _dbContext.Booms.Where(bm => bm.MessageStraemId == m.MessageStraemId).Any(b => b.BoomedBy == userCredential.Id),
                        IsLoginUserComment = _dbContext.Comments.Where(cm => cm.MessageStraemId == m.MessageStraemId).Any(b => b.CommentedBy == userCredential.Id),
                        VideoList = (from vl in _dbContext.MessageStreamVideo
                                     where vl.MessageStraemId == m.MessageStraemId && !string.IsNullOrEmpty(vl.VideoUrl)
                                     select new VideoInfo
                        {
                            RecordId = vl.RecordId,
                            VideoUrl = vl.VideoUrl
                        }).ToList(),
                        PicList = (from pl in _dbContext.MessageStreamPic
                                   where pl.MessageStraemId == m.MessageStraemId && !string.IsNullOrEmpty(pl.PicUrl)
                                   select new PicsInfo
                        {
                            PicId = pl.RecordId,
                            PicsUrl = pl.PicUrl,
                            ImageMode = pl.ImageMode,
                            Width = pl.Width,
                            Height = pl.Height
                        }).ToList()
                    }).ToList();
                    foreach (var item in objList)
                    {
                        tblCredentials objCred  = _dbContext.Credentials.FirstOrDefault(cr => cr.Id == item.PostedBy);
                        string         imageUrl = string.Empty;
                        if (objCred != null && objCred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                        {
                            tblUser userTemp = _dbContext.User.FirstOrDefault(usr => usr.UserId == objCred.UserId);
                            if (userTemp != null)
                            {
                                imageUrl = string.IsNullOrEmpty(userTemp.UserImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + userTemp.UserImageUrl;
                            }
                        }
                        else if (objCred != null && objCred.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                        {
                            tblTrainer trainerTemp = _dbContext.Trainer.FirstOrDefault(usr => usr.TrainerId == objCred.UserId);
                            if (trainerTemp != null)
                            {
                                imageUrl = string.IsNullOrEmpty(trainerTemp.TrainerImageUrl) ? string.Empty : CommonUtility.VirtualPath +
                                           Message.ProfilePicDirectory + trainerTemp.TrainerImageUrl;
                            }
                        }
                        item.PostedByImageUrl = imageUrl;
                        item.UserName         = (objCred.UserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase)
                                         ? _dbContext.User.FirstOrDefault(usr => usr.UserId == objCred.UserId).FirstName + " "
                                                 + _dbContext.User.FirstOrDefault(usr => usr.UserId == objCred.UserId).LastName
                                         : _dbContext.Trainer.FirstOrDefault(tnr => tnr.TrainerId == objCred.UserId).FirstName + " "
                                                 + _dbContext.Trainer.FirstOrDefault(tnr => tnr.TrainerId == objCred.UserId).LastName);
                        item.PostedDate = CommonWebApiBL.GetDateTimeFormat(item.DbPostedDate);
                        //Code For Getting Posted Pics
                        item.PicList.ForEach(pic =>
                        {
                            pic.PicsUrl = (!string.IsNullOrEmpty(pic.PicsUrl) && System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/" + Message.ResultPicDirectory + pic.PicsUrl))) ?
                                          CommonUtility.VirtualPath + Message.ResultPicDirectory + pic.PicsUrl : string.Empty;
                        }
                                             );
                        string thumnailHeight, thumnailWidth;
                        //Code For Getting Posted Videos
                        item.VideoList.ForEach(vid =>
                        {
                            string thumnailFileName = vid.VideoUrl.Split('.')[0] + Message.JpgImageExtension;
                            vid.ThumbNailUrl        = string.IsNullOrEmpty(vid.VideoUrl) ? string.Empty : CommonUtility.VirtualPath +
                                                      Message.ResultVideoDirectory + vid.VideoUrl.Split('.')[0] + Message.JpgImageExtension;
                            vid.VideoUrl   = !string.IsNullOrEmpty(vid.VideoUrl) ? CommonUtility.VirtualPath + Message.ResultVideoDirectory + vid.VideoUrl : string.Empty;
                            thumnailHeight = string.Empty;
                            thumnailWidth  = string.Empty;
                            CommonWebApiBL.GetThumNailDemension(thumnailFileName, out thumnailHeight, out thumnailWidth);
                            vid.ThumbNailHeight = thumnailHeight;
                            vid.ThumbNailWidth  = thumnailWidth;
                        }
                                               );
                    }
                    Total <List <ChallengeViewPostVM> > objresult = new Total <List <ChallengeViewPostVM> >();
                    objresult.TotalList = (from l in objList
                                           orderby l.DbPostedDate descending
                                           select l).Skip(startIndex).Take(endIndex - startIndex).ToList();
                    objresult.TotalCount = objList.Count();
                    if ((objresult.TotalCount) > endIndex)
                    {
                        objresult.IsMoreAvailable = true;
                    }
                    return(objresult);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End :ChallengeMessageFeedBL GetPostList  : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="credUserId"></param>
        /// <param name="message"></param>
        private static void SendChatNotification(SocketSentChatVM chatHistory)
        {
            byte[] certificate = File.ReadAllBytes(chatHistory.CeritifcatePath);
            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = false;
                lock (syncLock)
                {
                    StringBuilder traceLog = null;
                    List <UserNotification> allactiveDevices = null;
                    using (LinksMediaContext dataContext = new LinksMediaContext())
                    {
                        try
                        {
                            traceLog = new StringBuilder();
                            traceLog.Append("Start:SendChatNotification()");
                            string notificationType = string.Empty;
                            traceLog.AppendLine("Start: SendChallegesNotificationToUser()");

                            List <tblCredentials> chatsenderReceiverDetails = dataContext.Credentials.Where(em => string.Compare(em.EmailId, chatHistory.ReceiverEmailId, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(em.EmailId, chatHistory.SenderEmailId, StringComparison.OrdinalIgnoreCase) == 0).ToList();
                            int receiverCredId    = 0;
                            int senderCredId      = 0;
                            string senderUserType = string.Empty;
                            if (chatsenderReceiverDetails != null)
                            {
                                receiverCredId = chatsenderReceiverDetails.Where(em => em.EmailId.Equals(chatHistory.ReceiverEmailId, StringComparison.OrdinalIgnoreCase)).Select(cr => cr.Id).FirstOrDefault();
                                senderCredId   = chatsenderReceiverDetails.Where(em => em.EmailId.Equals(chatHistory.SenderEmailId, StringComparison.OrdinalIgnoreCase)).Select(cr => cr.Id).FirstOrDefault();
                                senderUserType = chatsenderReceiverDetails.Where(em => em.EmailId.Equals(chatHistory.SenderEmailId, StringComparison.OrdinalIgnoreCase)).Select(cr => cr.UserType).FirstOrDefault();
                            }

                            if (chatHistory != null && receiverCredId > 0 && senderCredId > 0 && !string.IsNullOrEmpty(chatHistory.Message))
                            {
                                bool isRead = false;
                                if (!chatHistory.IsOffine)
                                {
                                    isRead = true;
                                }
                                tblChatHistory objChatHistory = new tblChatHistory()
                                {
                                    ReceiverCredId     = receiverCredId,
                                    SenderCredId       = senderCredId,
                                    Message            = chatHistory.Message,
                                    IsRead             = isRead,
                                    TrasactionDateTime = Convert.ToDateTime(chatHistory.TrasactionDateTime),
                                };
                                dataContext.ChatHistory.Add(objChatHistory);
                                dataContext.SaveChanges();
                                if (chatHistory.IsOffine)
                                {
                                    string message         = string.Empty;
                                    allactiveDevices       = PushNotificationBL.GetLastUserDeviceID(receiverCredId);
                                    string senderFirstName = string.Empty;
                                    if (senderUserType.Equals(Message.UserTypeUser, StringComparison.OrdinalIgnoreCase))
                                    {
                                        senderFirstName = (from usr in dataContext.User
                                                           join crd in dataContext.Credentials
                                                           on usr.UserId equals crd.UserId
                                                           where crd.Id == senderCredId && crd.UserType == Message.UserTypeUser
                                                           select usr.FirstName + " " + usr.LastName).FirstOrDefault();
                                    }
                                    else if (senderUserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                                    {
                                        senderFirstName = (from usr in dataContext.Trainer
                                                           join crd in dataContext.Credentials
                                                           on usr.TrainerId equals crd.UserId
                                                           where crd.Id == senderCredId && crd.UserType == Message.UserTypeTrainer
                                                           select usr.FirstName + " " + usr.LastName).FirstOrDefault();
                                    }
                                    message = senderFirstName + " sent you a message!";
                                    bool isSaveSuccessfully = false;
                                    foreach (UserNotification objuserNotification in allactiveDevices)
                                    {
                                        // If Deives Token null then by pass to sending push notification
                                        if (!string.IsNullOrEmpty(objuserNotification.DeviceID))
                                        {
                                            if (!isSaveSuccessfully)
                                            {
                                                notificationType = ConstantHelper.constChatNotification;
                                                tblUserNotifications objdeviceNft = new tblUserNotifications
                                                {
                                                    SenderCredlID    = senderCredId,
                                                    ReceiverCredID   = receiverCredId,
                                                    NotificationType = notificationType,
                                                    SenderUserName   = senderFirstName,
                                                    Status           = true,
                                                    IsRead           = false,
                                                    TargetID         = 0,
                                                    CreatedDate      = DateTime.Parse(chatHistory.TrasactionDateTime),
                                                    TokenDevicesID   = objuserNotification.DeviceID
                                                };
                                                dataContext.UserNotifications.Add(objdeviceNft);
                                                dataContext.SaveChanges();
                                                isSaveSuccessfully = true;
                                            }
                                            PushNotificationiOSAndriod objPushNotificationiOSAndriod = new PushNotificationiOSAndriod();
                                            int totalNotificationcount = dataContext.ChatHistory.Count(ch => ch.ReceiverCredId == receiverCredId && ch.IsRead == false);
                                            int totalbudget            = CommonWebApiBL.GetTotalUSerNotification(receiverCredId, objuserNotification.DeviceID);
                                            if (objuserNotification.DeviceType.Equals(DeviceType.IOS.ToString(), StringComparison.OrdinalIgnoreCase))
                                            {
                                                objPushNotificationiOSAndriod.SendPushNotificationForiOS(objuserNotification.DeviceID, message, notificationType, totalNotificationcount, certificate, totalbudget, 0);
                                            }
                                            else if (objuserNotification.DeviceType.Equals(DeviceType.Android.ToString(), StringComparison.OrdinalIgnoreCase))
                                            {
                                                objPushNotificationiOSAndriod.SendPushNotificationForAndriod(objuserNotification.DeviceID, message, notificationType, totalNotificationcount, totalbudget, 0);
                                            }
                                        }
                                    }
                                    message = string.Empty;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.LogManagerInstance.WriteErrorLog(ex);
                        }
                        finally
                        {
                            traceLog.AppendLine("End: SendChatNotification()  --- " + DateTime.Now.ToLongDateString());
                            LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                            traceLog         = null;
                            allactiveDevices = null;
                        }
                    }
                }
            }).Start();
        }
        /// <summary>
        ///  Get ChatHistory based on Sender and Receiver Id
        /// </summary>
        /// <param name="chatRequest"></param>
        /// <returns></returns>
        public static Total <List <SocketSentChatVM> > GetChatHistory(ChatHistoryRequest chatRequest, int startIndex, int endIndex)
        {
            StringBuilder traceLog = null;
            Total <List <SocketSentChatVM> > chatHistoryList = new Total <List <SocketSentChatVM> >();

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                traceLog = new StringBuilder();
                try
                {
                    traceLog.AppendLine("Start: GetChatHistory() for receiver Id");
                    if (chatRequest != null && chatRequest.SenderCredId > 0)
                    {
                        Credentials cred                       = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                        int         currentUserCrdId           = cred.Id;
                        int         senderCredId               = chatRequest.SenderCredId;
                        List <SocketSentChatResponse> chatlist = (from ch in dataContext.ChatHistory
                                                                  where (ch.ReceiverCredId == currentUserCrdId && ch.SenderCredId == senderCredId) || (ch.ReceiverCredId == senderCredId && ch.SenderCredId == currentUserCrdId)
                                                                  orderby ch.ChatHistoryId descending
                                                                  select new SocketSentChatResponse
                        {
                            ChatHistoryId = ch.ChatHistoryId,
                            Message = ch.Message,
                            ReceiverEmailId = dataContext.Credentials.Where(crd => crd.Id == ch.ReceiverCredId).Select(s => s.EmailId).FirstOrDefault(),
                            SenderEmailId = dataContext.Credentials.Where(crd => crd.Id == ch.SenderCredId).Select(s => s.EmailId).FirstOrDefault(),
                            TrasactionDateTime = ch.TrasactionDateTime
                        }).ToList();

                        if (chatlist != null)
                        {
                            var chathistorylist = chatlist.Skip(startIndex).Take(endIndex - startIndex).ToList().OrderBy(ch => ch.ChatHistoryId).ToList();
                            chatHistoryList.TotalList = (from m in chathistorylist
                                                         orderby m.ChatHistoryId
                                                         select new SocketSentChatVM
                            {
                                ChatHistoryId = m.ChatHistoryId,
                                Message = m.Message,
                                ReceiverEmailId = m.ReceiverEmailId,
                                SenderEmailId = m.SenderEmailId,
                                TrasactionDateTime = m.TrasactionDateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff")
                            }).ToList();


                            chatHistoryList.TotalCount = chatlist.Count();
                            if ((chatHistoryList.TotalCount) > endIndex)
                            {
                                chatHistoryList.IsMoreAvailable = true;
                            }
                        }
                        // Update IsRead when user
                        if (chatRequest.IsRead || currentUserCrdId > 0)
                        {
                            UpdateChatHistory(currentUserCrdId, senderCredId);
                            UpdateChatNotification(currentUserCrdId, senderCredId);
                        }
                    }
                    return(chatHistoryList);
                }
                finally
                {
                    traceLog.AppendLine("GetChatHistory  end() : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Function to get challenge details of challenge of the day
        /// </summary>
        /// <returns>ChallengeOfTheDayDetailVM</returns>
        /// <devdoc>
        /// Developer Name - Arvind Kumar
        /// Date - 03/30/2015
        /// </devdoc>
        public static ChallengeOfTheDayDetailVM GetChallengeOfTheDayDetails(int challengeId)
        {
            StringBuilder traceLog = null;

            using (LinksMediaContext _dbContext = new LinksMediaContext())
            {
                try
                {
                    traceLog = new StringBuilder();
                    traceLog.AppendLine("Start: GetChallengeOfTheDayDetails---- " + DateTime.Now.ToLongDateString());
                    char[] splitChar = { ConstantHelper.constCharchatColon };
                    string tempValue = string.Empty;
                    ChallengeOfTheDayDetailVM objChallengedetail = (from c in _dbContext.Challenge
                                                                    join cred in _dbContext.Credentials on c.CreatedBy equals cred.Id
                                                                    join ct in _dbContext.ChallengeType on c.ChallengeSubTypeId equals ct.ChallengeSubTypeId
                                                                    join cod in _dbContext.ChallengeofTheDayQueue on c.ChallengeId equals cod.ChallengeId
                                                                    join uc in _dbContext.UserChallenge on cod.ResultId equals uc.Id
                                                                    join h in _dbContext.HypeVideos on cod.HypeVideoId equals h.RecordId
                                                                    where c.ChallengeId == challengeId && c.IsActive
                                                                    select new ChallengeOfTheDayDetailVM
                    {
                        ChallengeId = c.ChallengeId,
                        ChallengeName = c.ChallengeName,
                        DifficultyLevel = c.DifficultyLevel,
                        ChallengeType = ct.ChallengeType,
                        TempEquipments = (from trzone in _dbContext.ChallengeEquipmentAssociations
                                          join bp in _dbContext.Equipments
                                          on trzone.EquipmentId equals bp.EquipmentId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.Equipment).Distinct().ToList <string>(),
                        TempTargetZone = (from trzone in _dbContext.TrainingZoneCAssociations
                                          join bp in _dbContext.BodyPart
                                          on trzone.PartId equals bp.PartId
                                          where trzone.ChallengeId == c.ChallengeId
                                          select bp.PartName).Distinct().ToList <string>(),
                        Strenght = _dbContext.UserChallenge.Where(uchlng => uchlng.ChallengeId == c.ChallengeId).Select(y => y.UserId).Distinct().Count(),
                        ResultUnit = ct.ResultUnit,
                        ResultUnitSuffix = uc.ResultUnit,
                        ChallengeDescription = ct.ChallengeSubType,
                        Excercises = (from exer in _dbContext.Exercise
                                      join ce in _dbContext.CEAssociation on exer.ExerciseId equals ce.ExerciseId
                                      where ce.ChallengeId == challengeId
                                      select new ExerciseVM
                        {
                            ExerciseId = exer.ExerciseId,
                            ExerciseName = exer.ExerciseName,
                            ExcersiceDescription = exer.Description,
                            ChallengeExcerciseDescription = ce.Description,
                            VedioLink = exer.VideoLink,
                            Index = exer.Index,
                            Reps = ce.Reps,
                            WeightForManDB = ce.WeightForMan,
                            WeightForWomanDB = ce.WeightForWoman,
                        }).ToList(),
                        HypeVideo = h.HypeVideo,
                        Result = (uc.Result == null ? string.Empty : uc.Result) + " " + (uc.Fraction == null ? string.Empty : uc.Fraction),
                        VariableValue = c.VariableValue,
                        ChallengeSubTypeId = ct.ChallengeSubTypeId,
                        VariableUnit = ct.Unit,
                        CreatedByUserType = cred.UserType,
                        CreatedByTrainerId = cred.UserId,
                        PersonalBestUserId = uc.UserId
                    }).FirstOrDefault();
                    if (objChallengedetail != null)
                    {
                        if (objChallengedetail.TempEquipments != null && objChallengedetail.TempEquipments.Count > 0)
                        {
                            objChallengedetail.Equipment = string.Join(", ", objChallengedetail.TempEquipments);
                        }
                        objChallengedetail.TempEquipments = null;
                        if (objChallengedetail.TempTargetZone != null && objChallengedetail.TempTargetZone.Count > 0)
                        {
                            objChallengedetail.TargetZone = string.Join(", ", objChallengedetail.TempTargetZone);
                        }
                        objChallengedetail.TempTargetZone = null;
                        if (objChallengedetail.ResultUnit.Equals(ConstantHelper.constTime))
                        {
                            string   tempResult = objChallengedetail.Result;
                            string[] spliResult = tempResult.Split(splitChar);
                            if (spliResult[0].Equals(ConstantHelper.constTimeVariableUnit))
                            {
                                objChallengedetail.Result = spliResult[1] + ConstantHelper.constColon + spliResult[2];
                            }
                            else if (spliResult[2].Equals(ConstantHelper.constTimeVariableUnit))
                            {
                                objChallengedetail.Result = spliResult[0] + ConstantHelper.constColon + spliResult[1];
                            }
                        }
                        if (!string.IsNullOrEmpty(objChallengedetail.Result))
                        {
                            objChallengedetail.Result = objChallengedetail.Result.Trim();
                        }
                        if (!string.IsNullOrEmpty(objChallengedetail.ChallengeType))
                        {
                            objChallengedetail.ChallengeType = objChallengedetail.ChallengeType.Split(' ')[0];
                        }
                        if (objChallengedetail.CreatedByUserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                        {
                            var objTrainer = _dbContext.Trainer.FirstOrDefault(t => t.TrainerId == objChallengedetail.CreatedByTrainerId);
                            if (objTrainer != null)
                            {
                                objChallengedetail.CreatedByTrainerName = objTrainer.FirstName + " " + objTrainer.LastName;
                                objChallengedetail.CreatedByProfilePic  = string.IsNullOrEmpty(objTrainer.TrainerImageUrl) ? string.Empty : CommonUtility.VirtualPath + Message.ProfilePicDirectory + objTrainer.TrainerImageUrl;
                            }
                        }
                        else
                        {
                            objChallengedetail.CreatedByTrainerId = 0;
                        }
                    }

                    objChallengedetail.Excercises.ForEach(
                        exer =>
                    {
                        exer.WeightForMan     = exer.WeightForManDB > 0 ? exer.WeightForManDB.ToString() + " " + ConstantHelper.constlbs : null;
                        exer.WeightForWoman   = exer.WeightForWomanDB > 0 ? exer.WeightForWomanDB.ToString() + " " + ConstantHelper.constlbs : null;
                        exer.VedioLink        = string.IsNullOrEmpty(exer.VedioLink) ? string.Empty : CommonUtility.VirtualPath + Message.ExerciseVideoDirectory + exer.VedioLink;
                        exer.ExerciseThumnail = CommonWebApiBL.GetSaveExerciseThumbnail(exer.VedioLink, exer.ExerciseName);
                    });
                    //// Modify the varivale in 02 Hour(s), 05 Minute(s), 10 Second(s) format
                    string tempdesc = string.Empty;
                    if (objChallengedetail != null && !string.IsNullOrEmpty(objChallengedetail.VariableValue))
                    {
                        if (objChallengedetail.VariableUnit == ConstantHelper.constVariableUnitminutes || objChallengedetail.VariableUnit == ConstantHelper.constVariableUnitseconds)
                        {
                            string[] variableValueWithMS = objChallengedetail.VariableValue.Split(new char[1] {
                                '.'
                            });
                            if (!string.IsNullOrEmpty(variableValueWithMS[0]))
                            {
                                if (variableValueWithMS[0].Contains(':'))  // If containd colon(:) then true for time type like minutes and seconds
                                {
                                    //Code for HH:MM:SS And MM:SS format
                                    string[] spliResult = variableValueWithMS[0].Split(splitChar);
                                    tempValue = spliResult[0].Equals(ConstantHelper.constTimeVariableUnit) ? string.Empty : spliResult[0] + ConstantHelper.constHourdisplay;
                                    if (!string.IsNullOrEmpty(tempValue))
                                    {
                                        tempValue += spliResult[1].Equals(ConstantHelper.constTimeVariableUnit) ? string.Empty : ", " + spliResult[1] + ConstantHelper.constMinutedisplay;
                                    }
                                    else
                                    {
                                        tempValue += spliResult[1].Equals(ConstantHelper.constTimeVariableUnit) ? string.Empty : spliResult[1] + ConstantHelper.constMinutedisplay;
                                    }
                                    if (!string.IsNullOrEmpty(tempValue))
                                    {
                                        tempValue += spliResult[2].Equals(ConstantHelper.constTimeVariableUnit) ? string.Empty : ", " + spliResult[2] + ConstantHelper.constSeconddisplay;
                                    }
                                    else
                                    {
                                        tempValue += spliResult[2].Equals(ConstantHelper.constTimeVariableUnit) ? string.Empty : spliResult[2] + ConstantHelper.constSeconddisplay;
                                    }
                                    tempdesc = tempValue;
                                }
                                else
                                {
                                    tempdesc = variableValueWithMS[0].ToString();
                                }
                            }
                        }
                        else
                        {
                            tempdesc = objChallengedetail.VariableValue;
                        }
                    }
                    ////End the modification
                    if (!string.IsNullOrEmpty(tempdesc))
                    {
                        tempdesc = tempdesc.Trim();
                    }
                    objChallengedetail.ChallengeDescription = objChallengedetail.ChallengeDescription.Replace("____", tempdesc).Replace(" amount of time?", "?").Replace(" seconds?", "?");
                    if (objChallengedetail != null && !string.IsNullOrEmpty(objChallengedetail.VariableValue))
                    {
                        string[] variableValueWithMS = objChallengedetail.VariableValue.Split(new char[1] {
                            '.'
                        });
                        if (!string.IsNullOrEmpty(variableValueWithMS[0]))
                        {
                            if (variableValueWithMS[0].Contains(':'))  // If containd colon(:) then true for time type like minutes and seconds
                            {
                                //Code for HH:MM:SS And MM:SS format
                                tempValue = variableValueWithMS[0];
                                string[] spliResult = tempValue.Split(splitChar);
                                if (spliResult[0].Equals(ConstantHelper.constTimeVariableUnit))
                                {
                                    variableValueWithMS[0] = spliResult[1] + ConstantHelper.constColon + spliResult[2];
                                }
                                else if (spliResult[2].Equals(ConstantHelper.constTimeVariableUnit))
                                {
                                    variableValueWithMS[0] = spliResult[0] + ConstantHelper.constColon + spliResult[1];
                                }
                                objChallengedetail.VariableValue = variableValueWithMS[0] + (variableValueWithMS[1].Equals(ConstantHelper.constTimeVariableUnit) ?
                                                                                             ConstantHelper.constDotDoubleZero : (ConstantHelper.constDot + variableValueWithMS[1]));
                            }
                        }
                    }
                    var objCredentials = _dbContext.Credentials.FirstOrDefault(c => c.Id == objChallengedetail.PersonalBestUserId);
                    if (objCredentials != null && objCredentials.UserType.Equals(Message.UserTypeUser))
                    {
                        objChallengedetail.PersonalBestUserName = (from usr in _dbContext.User
                                                                   join creden in _dbContext.Credentials on usr.UserId equals creden.UserId
                                                                   where creden.Id == objCredentials.Id
                                                                   select new { UserName = usr.FirstName }).FirstOrDefault().UserName;
                    }
                    else if (objCredentials != null && objCredentials.UserType.Equals(Message.UserTypeTrainer))
                    {
                        objChallengedetail.PersonalBestUserName = (from trnr in _dbContext.Trainer
                                                                   join creden in _dbContext.Credentials on trnr.TrainerId equals creden.UserId
                                                                   where creden.Id == objCredentials.Id
                                                                   select new { UserName = trnr.FirstName }).FirstOrDefault().UserName;
                    }
                    return(objChallengedetail);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetChallengeOfTheDayDetails : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }
        /// <summary>
        /// Get FreeForm TrainerLibrary Challenges By SubCategory
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ChallengeTabVM GetFreeFormTrainerLibraryChallengesBySubCategory(TrainerLibraryWorkoutListByCategory model)
        {
            StringBuilder traceLog = new StringBuilder();

            using (LinksMediaContext dataContext = new LinksMediaContext())
            {
                try
                {
                    traceLog.AppendLine("Start: GetFreeFormTrainerLibraryChallengesBySubCategory---- " + DateTime.Now.ToLongDateString());
                    int            trainerCredId     = -1;
                    ChallengeTabVM objChallengeTabVM = new ChallengeTabVM();
                    Credentials    objCred           = CommonWebApiBL.GetUserId(Thread.CurrentPrincipal.Identity.Name);
                    int            usercredId        = objCred.Id;
                    if (!string.IsNullOrEmpty(model.UserType) && model.UserType.Equals(Message.UserTypeTrainer, StringComparison.OrdinalIgnoreCase))
                    {
                        trainerCredId = (from tr in dataContext.Trainer
                                         join crd in dataContext.Credentials
                                         on tr.TrainerId equals crd.UserId
                                         where crd.UserType == Message.UserTypeTrainer && tr.TrainerId == model.UserId
                                         select crd.Id).FirstOrDefault();
                    }
                    if (trainerCredId > 0)
                    {
                        List <MainChallengeVM> listMainVM = (from c in dataContext.Challenge
                                                             join ct in dataContext.ChallengeType on c.ChallengeSubTypeId equals ct.ChallengeSubTypeId
                                                             where c.IsActive && c.TrainerId == trainerCredId &&
                                                             ct.ChallengeSubTypeId == model.WorkoutCategoryID
                                                             //  && c.IsPremium == true
                                                             orderby c.CreatedDate descending
                                                             select new MainChallengeVM
                        {
                            ChallengeId = c.ChallengeId,
                            ChallengeName = c.ChallengeName,
                            DifficultyLevel = c.DifficultyLevel,
                            ChallengeType = ct.ChallengeType,
                            Description = c.Description,
                            IsSubscription = c.IsSubscription,
                            TempEquipments = (from trzone in dataContext.ChallengeEquipmentAssociations
                                              join bp in dataContext.Equipments
                                              on trzone.EquipmentId equals bp.EquipmentId
                                              where trzone.ChallengeId == c.ChallengeId
                                              select bp.Equipment).Distinct().ToList <string>(),
                            TempTargetZone = (from trzone in dataContext.TrainingZoneCAssociations
                                              join bp in dataContext.BodyPart
                                              on trzone.PartId equals bp.PartId
                                              where trzone.ChallengeId == c.ChallengeId
                                              select bp.PartName).Distinct().ToList <string>(),
                            IsActive = dataContext.UserActivePrograms.Where(uc => uc.ProgramId == c.ChallengeId && uc.IsCompleted == false &&
                                                                            uc.UserCredId == usercredId).Select(y => y.ProgramId).Distinct().Count() > 0,
                            Strenght = dataContext.UserChallenge.Where(uc => uc.ChallengeId == c.ChallengeId).Select(y => y.UserId).Distinct().Count(),
                            ResultUnit = ct.ResultUnit,
                            IsWellness = (ct.ChallengeSubTypeId == ConstantHelper.constWellnessChallengeSubType) ? true : false,
                            ProgramImageUrl = c.ProgramImageUrl,
                            ChallengeCategoryList = dataContext.ChallengeCategoryAssociations.
                                                    Where(cc => cc.ChallengeId == c.ChallengeId && cc.IsProgram == (ConstantHelper.constProgramChallengeSubType == c.ChallengeSubTypeId)).Select(ch => ch.ChallengeCategoryId).ToList()
                        }).ToList();


                        if (listMainVM != null && listMainVM.Count > 0)
                        {
                            listMainVM = listMainVM.Where(ch => ch.ChallengeCategoryList != null && ch.ChallengeCategoryList.Contains(model.WorkoutSubCategoryID)).ToList();
                            listMainVM.ForEach(r =>
                            {
                                string filePath = HttpContext.Current.Server.MapPath("~") + "\\images\\profilepic\\" + r.ProgramImageUrl;
                                if (System.IO.File.Exists(filePath))
                                {
                                    using (Bitmap objBitmap = new Bitmap(filePath))
                                    {
                                        double sourceWidth  = Convert.ToDouble(objBitmap.Size.Width, CultureInfo.CurrentCulture);
                                        double sourceHeight = Convert.ToDouble(objBitmap.Size.Height, CultureInfo.CurrentCulture);
                                        r.Height            = (sourceWidth > 0) ? Convert.ToString(sourceHeight, CultureInfo.CurrentCulture) : string.Empty;
                                        r.Width             = (sourceWidth > 0) ? Convert.ToString(sourceWidth, CultureInfo.CurrentCulture) : string.Empty;
                                    }
                                }
                                else
                                {
                                    r.Height = string.Empty;
                                    r.Width  = string.Empty;
                                }
                                r.ChallengeType   = r.ChallengeType.Split(' ')[0];
                                r.ProgramImageUrl = (string.IsNullOrEmpty(r.ProgramImageUrl)) ? string.Empty :
                                                    File.Exists(HttpContext.Current.Server.MapPath("~/" + Message.ProfilePicDirectory + r.ProgramImageUrl)) ?
                                                    CommonUtility.VirtualPath + Message.ProfilePicDirectory + r.ProgramImageUrl : string.Empty;
                                if (r.TempTargetZone != null && r.TempTargetZone.Count > 0)
                                {
                                    r.TargetZone = string.Join(", ", r.TempTargetZone);
                                }
                                r.TempTargetZone = null;
                                if (r.TempEquipments != null && r.TempEquipments.Count > 0)
                                {
                                    r.Equipment = string.Join(", ", r.TempEquipments);
                                }
                                r.TempEquipments = null;
                            });

                            int totalcount = listMainVM.Count();
                            listMainVM = (from l in listMainVM
                                          select l).Skip(model.StartIndex).Take(model.EndIndex - model.StartIndex).ToList();

                            if ((totalcount) > model.StartIndex)
                            {
                                objChallengeTabVM.IsMoreAvailable = true;
                            }
                            //Challenge feed sorted by acceptors
                            if (listMainVM != null)
                            {
                                listMainVM = listMainVM.OrderByDescending(chlng => chlng.Strenght).ToList();
                            }
                            objChallengeTabVM.ChallengeList = new List <MainChallengeVM>();
                            objChallengeTabVM.ChallengeList = listMainVM;
                        }
                    }
                    return(objChallengeTabVM);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    traceLog.AppendLine("End  GetFreeFormTrainerLibraryChallengesBySubCategory : --- " + DateTime.Now.ToLongDateString());
                    LogManager.LogManagerInstance.WriteTraceLog(traceLog);
                }
            }
        }