Esempio n. 1
0
        public async Task <IActionResult> AddReport(ReportAddDto model)
        {
            if (ModelState.IsValid)
            {
                var entity = _mapper.Map <ReportEntity>(model);

                _reportService.Add(entity);
                // rolü admin olan kullanıcılara bildirim eklenecek
                var adminUsers = await _userManager.GetUsersInRoleAsync(RoleInfo.Admin);

                var activeUser = await GetOnlineUser();

                foreach (var adminUser in adminUsers)
                {
                    _notificationService.Add(new NotificationEntity
                    {
                        State       = false,
                        AppUserId   = adminUser.Id,
                        Description = $"{activeUser.Name} {activeUser.Surname} yeni bir rapor yazdı."
                    });
                }
                return(RedirectToAction("Index"));
            }
            return(View(model));
        }
Esempio n. 2
0
        public IActionResult PostReference(Reference reference, string id)
        {
            string userId;

            try
            {
                userId = User.Claims.First(c => c.Type == "UserID").Value;
            }
            catch
            {
                return(Unauthorized());
            }
            reference.Sender   = _userService.GetSingleByCondition(s => s.Id == userId, null);
            reference.Receiver = _userService.GetSingleByCondition(s => s.Id == id, null);
            if (reference.Receiver == null)
            {
                return(NotFound());
            }
            reference.CreateDate = DateTime.Now;
            _referenceService.Add(reference);
            var notification = new Notification()
            {
                Type     = NotificationType.Reference,
                Sender   = reference.Sender,
                Receiver = reference.Receiver,
            };

            _notificationService.Add(notification);
            _referenceService.SaveChanges();
            return(Ok(reference));
        }
Esempio n. 3
0
        public async Task <IActionResult> AddNotification([FromBody] Notification notification)
        {
            var status = await _notificationService.Add(notification);

            await _hubContext.Clients.All.SendAsync("SendMessage");

            return(Ok(status));
        }
        public ActionResult Create([Bind(Exclude = "Pictures")] CreateLandmarkViewModel model)
        {
            var landmark = Mapper.Map <CreateLandmarkViewModel, Landmark>(model);

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                if (file.ContentLength == 0)
                {
                    break;
                }
                byte[] imageBytes = null;
                using (var binary = new BinaryReader(file.InputStream))
                {
                    imageBytes = binary.ReadBytes(file.ContentLength);
                    landmark.Pictures.Add(CreatePictures(imageBytes, model.Name + "" + i));
                }
            }
            var location = Mapper.Map <CreateLandmarkViewModel, Location>(model);
            var town     = GetTown(model.Town);

            location.Town     = town;
            landmark.Location = location;
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            _landmarkService.Add(landmark);
            _landmarkService.SaveLandmark();

            var notification = new Notification()
            {
                DateTime = DateTime.Now,
                Landmark = landmark,
                Type     = NotificationType.Created
            };

            _notificationService.Add(notification);
            _notificationService.Save();

            var users = _userService.GetUsers();

            users.ForEach(u => u.Notify(notification));
            _userNotificationService.Save();
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 5
0
        /// <inheritdoc />
        public void OnNext(NotificationValue value)
        {
            var notification = new Notification(_client.Id, value);

            if (!_notificationService.Exist(notification))
            {
                _notificationService.Add(notification);
            }
        }
        public IActionResult Add(Notification notification)
        {
            var result = _notificationService.Add(notification);

            if (result.Success)
            {
                return(Ok(result.Message));
            }
            return(BadRequest(result.Message));
        }
        public IActionResult AddNotification([FromBody] Notification notification)
        {
            var identity = (ClaimsIdentity)User.Identity;
            var userId   = identity.FindFirst("user_id").Value;

            notification.SeenIds = new List <string>();
            notification.Date    = DateTime.Now;

            var result = _notificationService.Add(notification);

            return(Ok(result));
        }
        public async Task <ActionResult> AddPermission([FromBody] CheckPermissionDto permissionDto)
        {
            if (!IsAvailableOperation() || permissionDto.UserIds.Count() == 0 && permissionDto.ClientIds.Count() == 0 && permissionDto.GroupIds.Count() == 0)
            {
                return(BadRequest());
            }

            var result = await _fileStorageService.CheckPermission(permissionDto, UserId, ClientId);

            AddLog(LogType.Create, LogMessage.CreatePermissionMessage(permissionDto.FileStorageId, LogMessage.CreateVerb, UserId));

            foreach (var recipient in result.Recipients)
            {
                var message = MessageUtil.GetMessage(permissionDto.Type, recipient, result.Storage, result.Sender);

                try
                {
                    await _emailSender.Send(EmailType.Notification, new MailAddress(recipient.Email, recipient.UserName), message.Subject, message.MessageBody);

                    await _notificationService.Add(recipient.Id, result.Storage.Id, message.Subject, message.MessageBody, Enums.NotificationType.Success);
                }
                catch (Exception)
                {
                    await _notificationService.Add(recipient.Id, result.Storage.Id, message.Subject, message.MessageBody, Enums.NotificationType.NotSent);
                }
            }

            return(Ok());
        }
Esempio n. 9
0
        public async Task SendMessage(string messageText, int recipientId, string recipientName)
        {
            int userId = _authService.GetCurrentUserId();
            //Create MessageAddRequest
            MessageAddRequest message = new MessageAddRequest();

            message.RecipientId = recipientId;
            message.MessageText = messageText;
            message.DateSent    = DateTime.Now;

            //DB Call
            int createdMessageId = _service.Add(message, userId);

            //Create message to send
            Message     createdMessage = new Message();
            UserProfile recipient      = new UserProfile();

            recipient.UserId = recipientId;
            UserProfile sender = new UserProfile();

            sender.UserId              = userId;
            createdMessage.Recipient   = recipient;
            createdMessage.Sender      = sender;
            createdMessage.MessageText = messageText;
            createdMessage.DateSent    = DateTime.Now;
            Random rnd = new Random();

            createdMessage.Id = rnd.Next(500000);

            // TODO Try/catch sql exception

            //Get current chatroom and send
            NotificationAddRequest notification = new NotificationAddRequest();

            notification.UserId             = recipientId;
            notification.NotificationTypeId = 2;
            notification.NotificationText   = $"New message from {recipientName}";
            Notification notification1 = new Notification();

            notification1.NotificationText   = $"New message from {recipientName}";
            notification1.UserId             = recipientId;
            notification1.NotificationTypeId = 2;
            notification1.DateCreated        = new DateTime();

            _notificationService.Add(notification);
            string chatRoomId = await _chatHubService.GetCurrentUserRoom(userId);

            await Clients.Group(chatRoomId).SendAsync("AddMessage", createdMessage);

            await _notificationHubContext.Clients.User(recipientId.ToString()).SendAsync("ReceiveNotification", notification1);
        }
        public void Process(Core.IUnitOfWork db,
                            DTO.OrderToTrackDTO shipping,
                            string status,
                            DateTime?statusDate,
                            IList <TrackingRecord> records,
                            DateTime when)
        {
            //USPS Desc: No record of that item
            //Pre-Shipment Info Sent to USPS

            if (IsAccept(shipping, status, statusDate, records))
            {
                var type = NotificationType.LabelNeverShipped;

                var recordId = shipping.ShipmentInfoId.HasValue
                    ? shipping.ShipmentInfoId.Value
                    : (shipping.MailInfoId ?? 0);

                var additionalParams = new LabelNeverShippedParams()
                {
                    BuyDate      = shipping.BuyDate,
                    ShippingName = shipping.ShippingName,

                    Carrier         = shipping.Carrier,
                    OrderNumber     = shipping.OrderNumber,
                    LabelFromTypeId =
                        shipping.ShipmentInfoId.HasValue ? (int)LabelFromType.Batch : (int)LabelFromType.Mail,
                    ShippingInfoId = recordId,
                    ReasonId       = shipping.ReasonId
                };

                var result = _notificationService.Add(shipping.TrackingNumber,
                                                      EntityType.Tracking,
                                                      String.Empty,

                                                      additionalParams,

                                                      shipping.OrderNumber,
                                                      type);

                if (result.HasValue)
                {
                    _log.Info("Added notification, type=" + type + ", id=" + shipping.TrackingNumber);
                }
            }
            else
            {
                _notificationService.RemoveExist(shipping.TrackingNumber, Type);
            }
        }
        public IActionResult AssignTaskOnUser(TaskAssignUserDto model)
        {
            var taskEntity = _taskService.Get(model.TaskId);

            taskEntity.AppUserId = model.AppUserId;
            _taskService.Update(taskEntity);

            _notificationService.Add(new NotificationEntity
            {
                AppUserId   = model.AppUserId,
                Description = $"{taskEntity.Name} adlı iş için görevlendirildiniz."
            });
            return(RedirectToAction("Index"));
        }
Esempio n. 12
0
        public ActionResult SendNotification(int id)
        {
            notification notification = new notification()
            {
                date = DateTime.Now, job_id = id, message = "New Job", recruitmentManager_cin = CurrentUser.Id
            };

            _notificationService.Add(notification);
            _notificationService.commit();
            //job job = _jobService.GetById(id);


            return(RedirectToAction("Index"));
        }
Esempio n. 13
0
 public ResponseMessage CreateNotification([FromBody] NotificationViewModel notification)
 {
     if (ModelState.IsValid)
     {
         _notificationService.Add(notification);
         return(new ResponseMessage {
             IsSuccess = true
         });
     }
     else
     {
         return(new ResponseMessage {
             IsSuccess = false, Message = "Model is not valid"
         });
     }
 }
Esempio n. 14
0
        public IHttpActionResult AddNotification([FromBody] NotificationDto dto)
        {
            if (dto == null)
            {
                return(BadRequest());
            }

            var result = _notificationService.Add(dto);

            if (result == true)
            {
                return(Ok());
            }

            return(BadRequest());
        }
Esempio n. 15
0
        public IActionResult AcceptFriendRequest(int id)
        {
            string userId;

            try
            {
                userId = User.Claims.First(c => c.Type == "UserID").Value;
            }
            catch
            {
                return(Unauthorized());
            }
            var receiver      = _userService.GetSingleByCondition(s => s.Id == userId, null);
            var friendRequest = _friendRequestService.GetSingleByCondition(s => s.FriendRequestId == id, new string[] { "Sender" });
            var friend        = new Friend()
            {
                ApplicationUser1 = friendRequest.Sender,
                ApplicationUser2 = receiver,
                CreateDate       = DateTime.Now
            };

            if (friendRequest == null)
            {
                return(NotFound());
            }
            if (receiver.Id != userId)
            {
                return(NotFound());
            }
            var notification = new Notification()
            {
                Type       = NotificationType.FriendRequest,
                Sender     = receiver,
                Receiver   = friendRequest.Sender,
                CreateDate = DateTime.Now,
            };

            _notificationService.Add(notification);
            friendRequest.IsAccepted = true;
            _friendService.Add(friend);
            _friendRequestService.SaveChanges();
            return(Ok(friendRequest));
        }
        public HttpResponseMessage Post(HttpRequestMessage request, Notification n)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;
                if (ModelState.IsValid)
                {
                    request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
                else
                {
                    var notification = _notificationService.Add(n);
                    _notificationService.SaveChanges();

                    response = request.CreateResponse(HttpStatusCode.Created, notification);
                }
                return response;
            }));
        }
Esempio n. 17
0
        public ActionResult Create(Notification model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    NotificationService.Add(model);
                    NotificationService.SaveChanges();
                }
                else
                {
                    return(View(model));
                }
                // TODO: Add insert logic here

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 18
0
        public IActionResult AcceptHostOffer(int id)
        {
            string userId;

            try
            {
                userId = User.Claims.First(c => c.Type == "UserID").Value;
            }
            catch
            {
                return(Unauthorized());
            }
            var receiver  = _userService.GetSingleByCondition(s => s.Id == userId, null);
            var hostOffer = _hostOfferService.GetSingleByCondition(s => s.HostOfferId == id, new string[] { "Sender" });

            if (hostOffer == null)
            {
                return(NotFound());
            }
            if (receiver.Id != userId)
            {
                return(NotFound());
            }
            var notification = new Notification()
            {
                Type       = NotificationType.HostOffer,
                Sender     = receiver,
                Receiver   = hostOffer.Sender,
                CreateDate = DateTime.Now,
            };

            _notificationService.Add(notification);
            hostOffer.IsAccepted = true;
            _hostOfferService.SaveChanges();
            return(Ok(hostOffer));
        }
Esempio n. 19
0
        public virtual void Subscribe(EmailSubscriptionViewModel subscription)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    // Add logic to add subscr
                    var isGroup = subscription.SubscriptionType.Contains("Group");
                    var isTag   = subscription.SubscriptionType.Contains("tag");
                    var id      = subscription.Id;
                    var dbUser  = MembershipService.GetUser(User.Identity.Name);

                    if (isGroup)
                    {
                        // get the Group
                        var cat = _groupService.Get(id);

                        if (cat != null)
                        {
                            // Create the notification
                            var GroupNotification = new GroupNotification
                            {
                                Group = cat,
                                User  = dbUser
                            };
                            //save

                            _notificationService.Add(GroupNotification);
                        }
                    }
                    else if (isTag)
                    {
                        // get the tag
                        var tag = _topicTagService.Get(id);

                        if (tag != null)
                        {
                            // Create the notification
                            var tagNotification = new TagNotification
                            {
                                Tag  = tag,
                                User = dbUser
                            };
                            //save

                            _notificationService.Add(tagNotification);
                        }
                    }
                    else
                    {
                        // get the Group
                        var topic = _topicService.Get(id);

                        // check its not null
                        if (topic != null)
                        {
                            // Create the notification
                            var topicNotification = new TopicNotification
                            {
                                Topic = topic,
                                User  = dbUser
                            };
                            //save

                            _notificationService.Add(topicNotification);
                        }
                    }

                    Context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Context.RollBack();
                    LoggingService.Error(ex);
                    throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                }
            }
            else
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
        }
Esempio n. 20
0
        public async Task <CommentForReturnViewModel> AddComment(AddCommentViewModel entity, int levelIDOfUserComment)
        {
            var listEmail       = new List <string[]>();
            var listTags        = new List <Tag>();
            var listFullNameTag = new List <string>();
            var user            = _dbContext.Users;

            var    dataModel   = _dbContext.Datas;
            string queryString = string.Empty;
            var    LinkDedault = entity.DefaultLink;

            try
            {
                //add vao comment
                var tamp    = new List <string>();
                var message = string.Empty;
                foreach (var item in entity.Tag.Split(","))
                {
                    if (item == "")
                    {
                        tamp.Add(entity.CommentMsg);
                        message = entity.CommentMsg;
                    }
                    else
                    {
                        var Msgs = user.FirstOrDefault(x => x.Username == item).Alias;
                        tamp.Add("@" + Msgs);
                        message = entity.CommentMsg.Split("@").First() + string.Join(" ", tamp);
                    }
                }
                //string content = @"<p><b style='color:red'>" + string.Join(" ", tamp) + "</b></p>";
                var comment = await CreateComment(new Comment
                {
                    CommentMsg = message,
                    //CommentMsg = entity.CommentMsg,
                    DataID = entity.DataID,
                    UserID = entity.UserID,//sender
                    Link   = entity.Link,
                    Title  = entity.Title
                });

                //if (comment.ID > 0)
                //{
                //    var updateLink = await _dbContext.Comments.FirstOrDefaultAsync(x => x.ID == comment.ID);

                //    if (!updateLink.Link.Contains("title"))
                //    {
                //        //Replace Remark become Action Plan
                //        var title = Regex.Replace(comment.Title.Split('-')[0].ToSafetyString(), @"\s+", "-");
                //        updateLink.Link = updateLink.Link ;
                //        await _dbContext.SaveChangesAsync();
                //        queryString = updateLink.Link;

                //    }
                //}

                if (comment.ID > 0)
                {
                    var updateLink = await _dbContext.Comments.FirstOrDefaultAsync(x => x.ID == comment.ID);

                    if (!updateLink.Link.Contains("title"))
                    {
                        //Replace Remark become Action Plan
                        var title  = Regex.Replace(comment.Title.Split('-')[0].ToSafetyString(), @"\s+", "-");
                        var qrlink = updateLink.Link.Split('#').First();
                        var udlink = LinkDedault + $"/remark/{comment.ID}/{comment.DataID}/{title}";
                        updateLink.Link = udlink;
                        await _dbContext.SaveChangesAsync();

                        queryString = qrlink + '#' + updateLink.Link;
                    }
                }
                //B1: Xu ly viec gui thong bao den Owner khi nguoi gui cap cao hon comment
                //Tim levelNumber cua user comment
                var kpilevelIDResult = await _dbContext.KPILevels.FirstOrDefaultAsync(x => x.KPILevelCode == entity.KPILevelCode);

                var userIDResult = await _dbContext.Owners.FirstOrDefaultAsync(x => x.KPILevelID == kpilevelIDResult.ID && x.CategoryID == entity.CategoryID);

                var userModel = await _dbContext.Users.FindAsync(userIDResult.UserID);

                //Lay ra danh sach owner thuoc categoryID va KPILevelCode
                var owners = await _dbContext.Owners.Where(x => x.KPILevelID == kpilevelIDResult.ID && x.CategoryID == entity.CategoryID).ToListAsync();

                //Neu nguoi comment ma la cap cao hon owner thi moi gui thong bao va gui mail cho owner
                if (await CheckLevelNumberOfUser(levelIDOfUserComment, userModel.LevelID))
                {
                    owners.ForEach(userItem =>
                    {
                        //Add Tag gui thong bao den cac owner
                        if (entity.UserID != userItem.ID) //Neu chinh owner do binh luan thi khong gui thong bao
                        {
                            var itemtag       = new Tag();
                            itemtag           = new Tag();
                            itemtag.UserID    = userItem.ID;
                            itemtag.CommentID = comment.ID;
                            listTags.Add(itemtag); //Day la danh sach tag
                            //Add vao list gui mail
                            string[] arrayString = new string[5];
                            arrayString[0]       = user.Find(entity.UserID).Alias; //Bi danh
                            arrayString[1]       = user.Find(entity.UserID).Email;
                            arrayString[2]       = comment.Link;
                            arrayString[3]       = comment.Title;
                            arrayString[4]       = comment.CommentMsg;
                            listEmail.Add(arrayString);
                        }
                    });
                    //B2: Neu ma nguoi cap cao hon owner tag ai do vao comment cua ho thi se gui mail va thong bao den nguoi do
                    if (!entity.Tag.IsNullOrEmpty())
                    {
                        var result = await CreateTag(entity.Tag, entity.UserID, comment);

                        listEmail       = result.Item1;
                        listFullNameTag = result.Item2;
                        listTags        = result.Item3;
                    }
                }
                else //Neu user co level nho hon owner commnent thi gui den owner
                {
                    //B1: Gui thong bao den cac owner
                    owners.ForEach(x =>
                    {
                        //Add vao Tag de gui thong
                        if (entity.UserID != x.UserID)
                        {
                            var itemtag       = new Tag();
                            itemtag           = new Tag();
                            itemtag.UserID    = x.UserID;
                            itemtag.CommentID = comment.ID;
                            listTags.Add(itemtag); //Day la danh sach tag
                        }
                    });

                    //B2: Neu tag ai thi gui thong bao den nguoi do
                    if (!entity.Tag.IsNullOrEmpty())
                    {
                        var result = await CreateTag(entity.Tag, entity.UserID, comment);

                        listEmail       = result.Item1;
                        listFullNameTag = result.Item2;
                        listTags        = result.Item3;
                    }
                }
                //Add vao seencomment
                var seenComment = new SeenComment();
                seenComment.CommentID = comment.ID;
                seenComment.UserID    = entity.UserID;
                seenComment.Status    = true;

                _dbContext.Tags.AddRange(listTags);
                await _dbContext.SaveChangesAsync();
                await CreateSeenComment(seenComment);

                if (listTags.Count > 0)
                {
                    //Add vao Notification
                    var notify = new Notification();
                    notify.CommentID = comment.ID;
                    notify.Content   = comment.CommentMsg;
                    notify.UserID    = entity.UserID; //sender
                    notify.Title     = comment.Title;
                    notify.Link      = comment.Link;
                    notify.Action    = "Comment";
                    notify.Tag       = string.Join(",", listFullNameTag);
                    await _notificationService.Add(notify);
                }



                return(new CommentForReturnViewModel
                {
                    Status = true,
                    ListEmails = listEmail,
                    QueryString = queryString,
                    NotifiUserID = listTags
                });
            }
            catch (Exception ex)
            {
                return(new CommentForReturnViewModel {
                    Status = false
                });
            }
        }
Esempio n. 21
0
        /// <inheritdoc />
        public async Task <IPipelineProcess <Topic> > Process(IPipelineProcess <Topic> input, IMvcForumContext context)
        {
            _notificationService.RefreshContext(context);
            _activityService.RefreshContext(context);
            _localizationService.RefreshContext(context);

            try
            {
                // Get the Current user from ExtendedData
                var username     = input.ExtendedData[Constants.ExtendedDataKeys.Username] as string;
                var loggedOnUser = await context.MembershipUser.FirstOrDefaultAsync(x => x.UserName == username);

                // Are we in an edit mode
                var isEdit = input.ExtendedData[Constants.ExtendedDataKeys.IsEdit] as bool? == true;

                // If the topic has tags then process
                if (input.EntityToProcess.Tags != null && input.EntityToProcess.Tags.Any())
                {
                    // Don't throw if badge fails as it's logged
                    //await _badgeService.ProcessBadge(BadgeType.Tag, input.EntityToProcess.User);
                }

                if (isEdit == false)
                {
                    // Subscribe the user to the topic as they have checked the checkbox
                    if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Subscribe))
                    {
                        var subscribe = input.ExtendedData[Constants.ExtendedDataKeys.Subscribe] as bool?;
                        if (subscribe == true)
                        {
                            var alreadyHasNotification = await context.TopicNotification
                                                         .Include(x => x.Topic)
                                                         .Include(x => x.User)
                                                         .AnyAsync(x =>
                                                                   x.Topic.Id == input.EntityToProcess.Id && x.User.Id == loggedOnUser.Id);

                            if (alreadyHasNotification == false)
                            {
                                // Create the notification
                                var topicNotification = new TopicNotification
                                {
                                    Topic = input.EntityToProcess,
                                    User  = loggedOnUser
                                };

                                //save
                                _notificationService.Add(topicNotification);
                            }
                        }
                    }

                    // Should we add the topic created activity
                    if (input.EntityToProcess.Pending != true)
                    {
                        _activityService.TopicCreated(input.EntityToProcess);
                    }

                    // finally notify
                    _notificationService.Notify(input.EntityToProcess, loggedOnUser, NotificationType.Topic);
                }

                // Was the post successful
                await context.SaveChangesAsync();
            }
            catch (System.Exception ex)
            {
                input.AddError(ex.Message);
                _loggingService.Error(ex);
            }
            return(input);
        }