protected virtual async Task <List <UserNotificationDto> > SaveUserNotifications(long[] userIds, NotificationScheme notificationScheme)
        {
            var userNotificationDtos = new List <UserNotificationDto>();
            var notificationDetail   = new NotificationDetail(notificationScheme);
            await _notificationRepository.InsertNotificationDetailAsync(notificationDetail);

            await _notificationRepository.SaveChangesAsync(); //To get notificationDetail.Id.

            var notificationDetailDto = notificationDetail.ToNotificationDetailDto();

            foreach (var userId in userIds)
            {
                var userNotification = new UserNotification()
                {
                    UserId = userId,
                    NotificationDetailId = notificationDetail.Id
                };

                await _notificationRepository.InsertUserNotificationAsync(userNotification);

                userNotificationDtos.Add(userNotification.ToUserNotificationDto(notificationDetailDto));
            }
            await _notificationRepository.SaveChangesAsync();

            return(userNotificationDtos);
        }
Esempio n. 2
0
 public bool AddNotificationWorkplace(Notification entity)
 {
     try
     {
         entity.CreateTime = DateTime.Now;
         _dbContext.Notifications.Add(entity);
         _dbContext.SaveChanges();
         var listDetails = new List <NotificationDetail>();
         var kpiLevel    = _dbContext.KPILevels.FirstOrDefault(x => x.KPILevelCode == entity.KPILevelCode);
         var listID      = new List <int> {
             entity.UserID, kpiLevel.Owner, kpiLevel.OwnerManagerment
         };
         foreach (var item in listID)
         {
             var detail = new NotificationDetail();
             detail.UserID         = item;
             detail.Seen           = false;
             detail.NotificationID = entity.ID;
             listDetails.Add(detail);
         }
         _dbContext.NotificationDetails.AddRange(listDetails);
         _dbContext.SaveChanges();
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 3
0
        // Update
        public bool Update(NotificationDetail entity)
        {
            try
            {
                var param = db.TM_Notification.Find(entity.Id);
                if (!string.IsNullOrEmpty(entity.Title))
                {
                    param.Title = entity.Title;
                }
                if (!string.IsNullOrEmpty(entity.Contents))
                {
                    param.Contents = entity.Contents;
                }
                if (entity.ReceiverId != null)
                {
                    param.ReceiverId = entity.ReceiverId;
                }
                if (entity.Type != null)
                {
                    param.Type = entity.Type;
                }
                if (entity.Link != null)
                {
                    param.Link = entity.Link;
                }
                param.Status = entity.Status;

                db.SaveChanges();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 4
0
 public bool UpdateNotificationDetail(NotificationDetail notificationDetail)
 {
     logger.EnterMethod();
     try
     {
         var notificationDetailGet = this._notificationDetailRepositories.Get(_ => _.Id == notificationDetail.Id);
         if (notificationDetailGet != null)
         {
             notificationDetailGet.Details = notificationDetail.Details;
             using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
             {
                 this._notificationDetailRepositories.Update(notificationDetailGet);
                 transactionScope.Complete();
             }
             this._iUnitOfWork.Save();
             logger.Info("Found NotificationDetail with Id: [" + notificationDetail.Id + "], update and save all changes success");
             return(true);
         }
         else
         {
             logger.Info("Can't find any NotificationDetail with Id: [" + notificationDetail.Id + "]");
             return(false);
         }
     }
     catch (Exception e)
     {
         logger.Error("Error: [" + e.Message + "]");
         return(false);
     }
     finally
     {
         logger.LeaveMethod();
     }
 }
Esempio n. 5
0
        public JsonResult Update(NotificationDetail entity)
        {
            bool ok = new NotificationDao().Update(entity);

            if (ok)
            {
                return(Json(new
                {
                    isNewRecord = false,
                    Id = entity.Id,
                    Title = entity.Title,
                    Contents = entity.Contents,
                    Type = entity.Type,
                    TypeName = entity.TypeName,
                    ReceiverId = entity.ReceiverId,
                    Receiver = entity.Receiver,
                    Link = entity.Link,
                    Status = entity.Status
                }));
            }
            else
            {
                return(NotifyError("Cập nhật"));;
            }
        }
Esempio n. 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructSuboptimalIndexDetails()
        internal virtual void ShouldConstructSuboptimalIndexDetails()
        {
            NotificationDetail detail = NotificationDetail_Factory.SuboptimalIndex("Person", "name");

            assertThat(detail.Name(), equalTo("index"));
            assertThat(detail.Value(), equalTo("index on :Person(name)"));
            assertThat(detail.ToString(), equalTo("index is: index on :Person(name)"));
        }
Esempio n. 7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructNotificationsFor_DEPRECATED_PROCEDURE()
        internal virtual void ShouldConstructNotificationsForDEPRECATEDPROCEDURE()
        {
            NotificationDetail identifierDetail = NotificationDetail_Factory.DeprecatedName("oldName", "newName");
            Notification       notification     = DEPRECATED_PROCEDURE.notification(InputPosition.empty, identifierDetail);

            assertThat(notification.Title, equalTo("This feature is deprecated and will be removed in future versions."));
            assertThat(notification.Severity, equalTo(SeverityLevel.WARNING));
            assertThat(notification.Code, equalTo("Neo.ClientNotification.Statement.FeatureDeprecationWarning"));
            assertThat(notification.Position, equalTo(InputPosition.empty));
            assertThat(notification.Description, equalTo("The query used a deprecated procedure. ('oldName' has been replaced by 'newName')"));
        }
Esempio n. 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructCartesianProductDetailsSingular()
        internal virtual void ShouldConstructCartesianProductDetailsSingular()
        {
            ISet <string> idents = new HashSet <string>();

            idents.Add("n");
            NotificationDetail detail = NotificationDetail_Factory.CartesianProduct(idents);

            assertThat(detail.Name(), equalTo("identifier"));
            assertThat(detail.Value(), equalTo("(n)"));
            assertThat(detail.ToString(), equalTo("identifier is: (n)"));
        }
Esempio n. 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructNotificationFor_INDEX_HINT_UNFULFILLABLE()
        internal virtual void ShouldConstructNotificationForINDEXHINTUNFULFILLABLE()
        {
            NotificationDetail indexDetail  = NotificationDetail_Factory.Index("Person", "name");
            Notification       notification = INDEX_HINT_UNFULFILLABLE.notification(InputPosition.empty, indexDetail);

            assertThat(notification.Title, equalTo("The request (directly or indirectly) referred to an index that does not exist."));
            assertThat(notification.Severity, equalTo(SeverityLevel.WARNING));
            assertThat(notification.Code, equalTo("Neo.ClientError.Schema.IndexNotFound"));
            assertThat(notification.Position, equalTo(InputPosition.empty));
            assertThat(notification.Description, equalTo("The hinted index does not exist, please check the schema (hinted index is: index on :Person(name))"));
        }
Esempio n. 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructJoinHintDetailsSingular()
        internal virtual void ShouldConstructJoinHintDetailsSingular()
        {
            IList <string> idents = new List <string>();

            idents.Add("n");
            NotificationDetail detail = NotificationDetail_Factory.JoinKey(idents);

            assertThat(detail.Name(), equalTo("hinted join key identifier"));
            assertThat(detail.Value(), equalTo("n"));
            assertThat(detail.ToString(), equalTo("hinted join key identifier is: n"));
        }
Esempio n. 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructCartesianProductDetails()
        internal virtual void ShouldConstructCartesianProductDetails()
        {
            ISet <string> idents = new SortedSet <string>();

            idents.Add("n");
            idents.Add("node2");
            NotificationDetail detail = NotificationDetail_Factory.CartesianProduct(idents);

            assertThat(detail.Name(), equalTo("identifiers"));
            assertThat(detail.Value(), equalTo("(n, node2)"));
            assertThat(detail.ToString(), equalTo("identifiers are: (n, node2)"));
        }
Esempio n. 12
0
 public bool AddNotificationDetail(NotificationDetail entity)
 {
     try
     {
         _dbContext.NotificationDetails.Add(entity);
         _dbContext.SaveChanges();
         return(true);
     }
     catch (Exception ex)
     {
         var message = ex.Message;
         return(false);
     }
 }
Esempio n. 13
0
        public bool Add(Notification entity)
        {
            try
            {
                entity.CreateTime = DateTime.Now;
                _dbContext.Notifications.Add(entity);

                _dbContext.SaveChanges();



                var listUserID  = new List <int>();
                var listDetails = new List <NotificationDetail>();
                var user        = _dbContext.Users;
                var tag         = _dbContext.Tags;
                //Neu thong bao cua comment thi vao bang tag lay tat ca user dc tag ra
                if (entity.CommentID > 0)
                {
                    listUserID.AddRange(tag.Where(x => x.CommentID == entity.CommentID).Select(x => x.UserID).ToArray());
                }

                if (entity.ActionplanID > 0)
                {
                    listUserID.AddRange(tag.Where(x => x.ActionPlanID == entity.ActionplanID).Select(x => x.UserID).ToArray());
                }
                var detail2 = new NotificationDetail();
                detail2.UserID         = entity.UserID;
                detail2.Seen           = false;
                detail2.NotificationID = entity.ID;
                listDetails.Add(detail2);

                foreach (var item in listUserID)
                {
                    var detail = new NotificationDetail();
                    detail.UserID         = item;
                    detail.Seen           = false;
                    detail.NotificationID = entity.ID;
                    listDetails.Add(detail);
                }


                _dbContext.NotificationDetails.AddRange(listDetails);
                _dbContext.SaveChanges();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public Notification MapFrom(DomainObjects.Notification source)
        {
            var destination =
                new Notification
                {
                    DateAdded = _dateTimeResolver.UtcNow,
                    Payload = _payloadXmlSerializer.Serialize(source.Payload),
                    Type = source.Payload.GetPayloadType().ToString()
                };

            var providerName = source.Payload.GetProvider();
            if (!string.IsNullOrEmpty(providerName))
            {
                var provider =
                    new Provider
                    {
                        Name = providerName
                    };

                destination.AssignProvider(provider);
            }

            if (source.Details != null)
            {
                foreach (var metadata in source.Details)
                {
                    var details =
                        new NotificationDetail
                        {
                            Uri = string.Format("{0}:{1}", metadata.Key, metadata.Value)
                        };

                    destination.AddDetail(details);
                }
            }

            var recipients = source.Payload.GetRecipients().ToList();
            foreach (var r in recipients)
            {
                var recipient = new Recipient
                {
                    Token = r,
                    Status = Status.Pending
                };

                destination.AddRecipient(recipient);
            }

            return destination;
        }
Esempio n. 15
0
        public static NotificationDetail NotificationEdit(string id)
        {
            var callDataNotification = new NotificationDetail();
            var dsDataNotification   = new DataSet();

            try
            {
                using (SqlConnection conn = new SqlConnection(SPlanetUtil.GetConnectionString()))
                {
                    List <SqlParameter> arrParm = new List <SqlParameter>
                    {
                        new SqlParameter("@id", SqlDbType.Int)
                        {
                            Value = Convert.ToInt32(id)
                        },
                        new SqlParameter("@customer_id", SqlDbType.Int)
                        {
                            Value = 0
                        },
                        new SqlParameter("@user_id", SqlDbType.Int)
                        {
                            Value = ConstantClass.SESSION_USER_ID
                        }
                    };
                    conn.Open();
                    dsDataNotification = SqlHelper.ExecuteDataset(conn, "sp_notification_list", arrParm.ToArray());
                    conn.Close();
                }
                if (dsDataNotification.Tables.Count > 0)
                {
                    var row = dsDataNotification.Tables[0].Rows[0];
                    callDataNotification.id                  = Convert.IsDBNull(row["id"]) ? 0 : Convert.ToInt32(row["id"]);
                    callDataNotification.notice_type         = Convert.IsDBNull(row["notice_type"]) ? null : Convert.ToString(row["notice_type"]);
                    callDataNotification.date                = Convert.ToString(row["notice_date"]);
                    callDataNotification.is_enable           = Convert.ToInt32(row["is_enable"]);
                    callDataNotification.customer_id         = Convert.IsDBNull(row["customer_id"]) ? 0 : Convert.ToInt32(row["customer_id"]);
                    callDataNotification.subject             = Convert.IsDBNull(row["subject"]) ? null : Convert.ToString(row["subject"]);
                    callDataNotification.description         = Convert.IsDBNull(row["description"]) ? null : Convert.ToString(row["description"]);
                    callDataNotification.company_name_tha    = Convert.IsDBNull(row["company_name_tha"]) ? null : Convert.ToString(row["company_name_tha"]);
                    callDataNotification.display_notice_date = Convert.IsDBNull(row["notice_date"]) ? null :
                                                               Convert.ToDateTime(row["notice_date"]).ToString("dd/MM/yyyy HH:mm");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(callDataNotification);
        }
Esempio n. 16
0
        public async Task <bool> Add(Notification entity)
        {
            try
            {
                //Add thong bao
                _dbContext.Notifications.Add(entity);
                await _dbContext.SaveChangesAsync();

                var listUserID  = new List <int>();
                var listDetails = new List <NotificationDetail>();

                var user = _dbContext.Users;
                var tag  = _dbContext.Tags;

                //Neu thong bao cua comment thi vao bang tag lay tat ca user dc tag ra
                if (entity.CommentID > 0)
                {
                    listUserID.AddRange(await tag.Where(x => x.CommentID == entity.CommentID).Select(x => x.UserID).ToArrayAsync());
                }
                var itemActionPlan = await _dbContext.Notifications.FirstOrDefaultAsync(x => x.UserID == entity.UserID && x.Action == entity.Action && x.ActionplanID == entity.ActionplanID);

                //Neu thong bao cua actioPlan thi vao bang tag lay tat ca user dc tag ra
                if (entity.ActionplanID > 0)
                {
                    listUserID.AddRange(await tag.Where(x => x.ActionPlanID == entity.ActionplanID).Select(x => x.UserID).ToArrayAsync());
                }

                //Neu co tag thi them vao bang NotificationDetail
                if (listUserID.Count > 0)
                {
                    foreach (var item in listUserID)
                    {
                        var detail = new NotificationDetail();
                        detail.UserID         = item;
                        detail.Seen           = false;
                        detail.URL            = entity.Link;
                        detail.NotificationID = entity.ID;
                        listDetails.Add(detail);
                    }
                    _dbContext.NotificationDetails.AddRange(listDetails);
                    await _dbContext.SaveChangesAsync();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 17
0
        public async Task <bool> Update(NotificationDetail entity)
        {
            var item = await _context.NotificationDetails.FindAsync(entity.ID);

            try
            {
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructNotificationFor_CARTESIAN_PRODUCT()
        internal virtual void ShouldConstructNotificationForCARTESIANPRODUCT()
        {
            ISet <string> idents = new SortedSet <string>();

            idents.Add("n");
            idents.Add("node2");
            NotificationDetail identifierDetail = NotificationDetail_Factory.CartesianProduct(idents);
            Notification       notification     = CARTESIAN_PRODUCT.notification(InputPosition.empty, identifierDetail);

            assertThat(notification.Title, equalTo("This query builds a cartesian product between disconnected patterns."));
            assertThat(notification.Severity, equalTo(SeverityLevel.WARNING));
            assertThat(notification.Code, equalTo("Neo.ClientNotification.Statement.CartesianProductWarning"));
            assertThat(notification.Position, equalTo(InputPosition.empty));
            assertThat(notification.Description, equalTo("If a part of a query contains multiple disconnected patterns, this will build a cartesian product " + "between all those parts. This may produce a large amount of data and slow down query processing. While " + "occasionally intended, it may often be possible to reformulate the query that avoids the use of this cross " + "product, perhaps by adding a relationship between the different parts or by using OPTIONAL MATCH " + "(identifiers are: (n, node2))"));
        }
Esempio n. 19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldConstructNotificationsFor_JOIN_HINT_UNFULFILLABLE()
        internal virtual void ShouldConstructNotificationsForJOINHINTUNFULFILLABLE()
        {
            IList <string> idents = new List <string>();

            idents.Add("n");
            idents.Add("node2");
            NotificationDetail identifierDetail = NotificationDetail_Factory.JoinKey(idents);
            Notification       notification     = JOIN_HINT_UNFULFILLABLE.notification(InputPosition.empty, identifierDetail);

            assertThat(notification.Title, equalTo("The database was unable to plan a hinted join."));
            assertThat(notification.Severity, equalTo(SeverityLevel.WARNING));
            assertThat(notification.Code, equalTo("Neo.ClientNotification.Statement.JoinHintUnfulfillableWarning"));
            assertThat(notification.Position, equalTo(InputPosition.empty));
            assertThat(notification.Description, equalTo("The hinted join was not planned. This could happen because no generated plan contained the join key, " + "please try using a different join key or restructure your query. " + "(hinted join key identifiers are: n, node2)"));
        }
Esempio n. 20
0
        public async Task <bool> Create(NotificationDetail entity)
        {
            await _context.NotificationDetails.AddAsync(entity);

            try
            {
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 21
0
        public static Page ItemTapped(object sender, ItemTappedEventArgs e)
        {
            FeedItem feedItem = (FeedItem)((ListView)sender).SelectedItem;

            if (feedItem.GetType() == typeof(Notification))
            {
                Notification tappedNotification = (Notification)feedItem;
                var          newPage            = new NotificationDetail(tappedNotification);
                return(newPage);
            }
            else if (feedItem.GetType() == typeof(Question))
            {
                Question tappedQuestion = (Question)feedItem;
                var      newPage        = new QuestionDetail(tappedQuestion);
                return(newPage);
            }
            return(new Page());
        }
Esempio n. 22
0
        public JsonResult EditRange(string listID, int StatusID)
        {
            try
            {
                //Cat chuoi, lay danh sach ToList hoac lay mang ToArray
                var list    = listID.Split(',').Select(Int32.Parse).ToArray();
                var records = db.Records.Where(f => list.Contains(f.RecordID)).ToList(); //7 cai tai lieu ma dc duyet
                records.ForEach(a => a.StatusID = StatusID);
                db.SaveChanges();

                //Khi add record xong thi add vao bang thong bao
                //b1 tao 1 doi tuong ten la Notifications o trong model
                foreach (var item in records)
                {
                    var notification = new Notifications();
                    notification.UserID   = 1;             // admin
                    notification.Action   = "Update";      //UpdateStatus
                    notification.RecordID = item.RecordID; //Lan 1:co RecordID la 21/ Lan 2: RecordID la 22/ Lan 2: RecordID la 23


                    //b2 goi class Dao co chua ham add notificationdetail
                    new NotificationsDao().Add(notification);

                    var notificationdetail = new NotificationDetail();
                    notificationdetail.NotificationID = notification.NotificationID;
                    notificationdetail.UserID         = item.UserID;//Lan 1:cua userID la thang id = 4 ,/ Lan 2: id = 2 truc/ Lan 3:thang id = 4
                    //b2 goi class Dao co chua ham add notificationdetail
                    new NotificationsDao().AddNotificationDetail(notificationdetail);
                }


                return(Json(new
                {
                    status = true
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(Json(new
                {
                    status = false
                }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 23
0
 public bool CreateNewNotificationDetail(NotificationDetail notificationDetail)
 {
     logger.EnterMethod();
     try
     {
         using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
         {
             this._notificationDetailRepositories.Add(notificationDetail);
             transactionScope.Complete();
         }
         this._iUnitOfWork.Save();
         logger.Info("Insert NotificationDetail to database and save all changes success");
         return(true);
     }
     catch (Exception e)
     {
         logger.Error("Error: [" + e.Message + "]");
         return(false);
     }
     finally
     {
         logger.LeaveMethod();
     }
 }
Esempio n. 24
0
        public string GetNotifList()
        {
            this.notificationStatus.NotifDetailsList = new List <NotificationDetail>();


            if (conn == null)
            {
                conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=1;Database=wfs_db;MaxPoolSize=1000;Pooling=true;Timeout=500;SyncNotification=true;preload reader=true;");
            }

            try
            {
                sqlCmd = new NpgsqlCommand();

                sqlCmd.Connection = conn;
                if (sqlCmd.Connection.State == ConnectionState.Closed)
                {
                    sqlCmd.Connection.Open();
                }

                if (command == null)
                {
                    command = new NpgsqlCommand("listen notifytickets;", conn);
                    command.ExecuteNonQuery();
                }

                if (userid == null)
                {
                    userid = web.Session.SessionUser.User.User.UserId.ToString();
                }


                sqlCmd.CommandType = CommandType.Text;
                sqlCmd.CommandText = "SELECT * FROM dbo.notifyview WHERE userid = " + userid + " ORDER BY createdate DESC";

                if (notificationflg == false)
                {
                    conn.Notification += new NotificationEventHandler(OnNotification);
                    notificationflg    = true;
                }

                #region oldcode
                //using (cfgContext db = new cfgContext())
                //{
                //    var currentUserId = WFS.web.Session.SessionUser.User.User.UserId;
                //    var notifList = db.User.Include("Notifications").FirstOrDefault(r => r.UserId == currentUserId).Notifications.ToList();

                //    foreach (var item in notifList)
                //    {
                //        NotificationDetail notif = new NotificationDetail()
                //        {
                //            NotificationId = item.notificationid,
                //            Title = item.title,
                //            Message = item.message,
                //            CreateDate = item.createdate.ToString(),
                //            State = item.state,
                //            IsSeen = item.isseen,
                //            Status = item.status,
                //            NotifStatus = item.notifstatus
                //        };
                //        notificationStatus.NotifDetailsList.Add(notif);
                //    }
                //}
                #endregion

                reader = sqlCmd.ExecuteReader();

                while (reader.Read())
                {
                    if (!reader.GetBoolean(5))
                    {
                        NotificationDetail notif = new NotificationDetail();

                        notif.NotificationId      = reader.GetInt64(0);
                        notif.Title               = reader.GetString(1);
                        notif.Message             = reader.GetString(2);
                        notif.CreateDate          = reader.GetDateTime(3).ToString();
                        notif.State               = reader.GetString(4);
                        notif.IsSeen              = reader.GetBoolean(5);
                        notif.Status              = reader.GetBoolean(6);
                        notif.NotifStatus         = reader.GetBoolean(7);
                        notificationStatus.userId = Convert.ToInt64(userid);

                        notificationStatus.NotifDetailsList.Add(notif);
                    }
                }
            }

            catch (Exception ex)
            {
                throw;
            }

            lock (threadSafeCode)
            {
                HttpRuntime.Cache["Notification" + userid] = SerializeObjectToJson(this.notificationStatus);
            }

            return(HttpRuntime.Cache["Notification" + userid] as string);
        }
        private IList<NotificationDetail> GetListDetails(string user)
        {
            var notifs = NotificationDao.GetAllNotification(user).OrderByDescending(a=>a.LastUpdatedDate);
            
            var result = new List<NotificationDetail>();

            foreach (var notification in notifs)
            {
                switch (notification.ModuleName)
                {
                    case "BusinessUpdates":
                    {
                        var buObject =
                            BusinessUpdatesDao.GetBusinessUpdates(new BusinessUpdates { Id = notification.RecordId });

                        var notifDetail = new NotificationDetail()
                        {
                            Id = notification.Id,
                            SenderName = notification.SenderName,
                            ReciverName = notification.ReciverName,
                            RecordId = notification.RecordId,
                            CreatedBy = notification.CreatedBy,
                            CreatedDate = notification.CreatedDate,
                            Details = buObject.Title,
                            IsApproved = notification.IsApproved,
                            LastUpdatedBy = notification.LastUpdatedBy,
                            LastUpdatedDate = notification.LastUpdatedDate,
                            ModuleName = notification.ModuleName,
                            UpdatePeriod = Common.Extentions.ExtentionHelpers.TimeAgo(notification.LastUpdatedDate),
                            StartDate = buObject.StartDate.ToShortDateString()
                        };
                        result.Add(notifDetail);
                        break;
                    }
                    case "Event":
                    {
                         var eventDet =
                            UpcomingEventsDao.GetUpcomingEvents(new UpcomingEvents() { Id = notification.RecordId });
                        var notifDetail = new NotificationDetail()
                        {
                            Id = notification.Id,
                            SenderName = notification.SenderName,
                            ReciverName = notification.ReciverName,
                            RecordId = notification.RecordId,
                            CreatedBy = notification.CreatedBy,
                            CreatedDate = notification.CreatedDate,
                            Details = eventDet.Title,
                            IsApproved = notification.IsApproved,
                            LastUpdatedBy = notification.LastUpdatedBy,
                            LastUpdatedDate = notification.LastUpdatedDate,
                            ModuleName = notification.ModuleName,
                            UpdatePeriod = Common.Extentions.ExtentionHelpers.TimeAgo(notification.LastUpdatedDate),
                            StartDate = eventDet.StartDate.ToShortDateString()
                        };
                        result.Add(notifDetail);
                        break;
                    }
                        case "NewJoinee":
                    {
                        var nj = NewJoineeDao.GetNewJoinee(new NewJoinees(){Id = notification.RecordId });
                         var notifDetail = new NotificationDetail()
                        {
                            Id = notification.Id,
                            SenderName = notification.SenderName,
                            ReciverName = notification.ReciverName,
                            RecordId = notification.RecordId,
                            CreatedBy = notification.CreatedBy,
                            CreatedDate = notification.CreatedDate,
                            Details = nj.FirstName,
                            IsApproved = notification.IsApproved,
                            LastUpdatedBy = notification.LastUpdatedBy,
                            LastUpdatedDate = notification.LastUpdatedDate,
                            ModuleName = notification.ModuleName,
                            UpdatePeriod = Common.Extentions.ExtentionHelpers.TimeAgo(notification.LastUpdatedDate),
                            StartDate = nj.StartDate.ToShortDateString()
                        };
                        result.Add(notifDetail);
                        break;
                    }
                        case "Vacancies":
                    {
                         var vac = VacancyDao.GetVacancy(new Vacancy(){Id = notification.RecordId });
                         var notifDetail = new NotificationDetail()
                        {
                            Id = notification.Id,
                            SenderName = notification.SenderName,
                            ReciverName = notification.ReciverName,
                            RecordId = notification.RecordId,
                            CreatedBy = notification.CreatedBy,
                            CreatedDate = notification.CreatedDate,
                            Details = vac.Location,
                            IsApproved = notification.IsApproved,
                            LastUpdatedBy = notification.LastUpdatedBy,
                            LastUpdatedDate = notification.LastUpdatedDate,
                            ModuleName = notification.ModuleName,
                            UpdatePeriod = Common.Extentions.ExtentionHelpers.TimeAgo(notification.LastUpdatedDate),
                            
                        };
                        result.Add(notifDetail);
                        break;
                    }
                        case "Announcement":
                    {   var ann = HomePageAnnouncementDao.GetHomePageAnnouncement(new HomePageAnnouncement(){Id = notification.RecordId});
                         var notifDetail = new NotificationDetail()
                        {
                            Id = notification.Id,
                            SenderName = notification.SenderName,
                            ReciverName = notification.ReciverName,
                            RecordId = notification.RecordId,
                            CreatedBy = notification.CreatedBy,
                            CreatedDate = notification.CreatedDate,
                            Details = ann.AnnouncementContent,
                            IsApproved = notification.IsApproved,
                            LastUpdatedBy = notification.LastUpdatedBy,
                            LastUpdatedDate = notification.LastUpdatedDate,
                            ModuleName = notification.ModuleName,
                            UpdatePeriod = Common.Extentions.ExtentionHelpers.TimeAgo(notification.LastUpdatedDate),
                            StartDate = ann.StartDate.ToShortDateString()
                        };
                        result.Add(notifDetail);
                        break;
                    }
                       
                }
                
            }

            return result;
        }
 /// <summary>
 /// Determines whether the specified
 /// <see cref="NotificationDetail"/> is equal to the current
 /// <see cref="NotificationDetail"/>.
 /// </summary>
 /// <param name="other">
 /// The <see cref="NotificationDetail"/> to compare with the
 /// current <see cref="NotificationDetail"/>.
 /// </param>
 /// <returns>
 /// <c>true</c> if the specified <see cref="NotificationDetail"/>
 /// is equal to the current <see cref="NotificationDetail"/>;
 /// otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(NotificationDetail other)
 {
     return(other != null &&
            this.Type.Equals(other.Type) &&
            object.Equals(this.ChangesSince, other.ChangesSince));
 }
Esempio n. 27
0
        public async Task PushNotifyDetail(string clientGroupName, NotificationDetail notificationDetail)
        {
            FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

            User currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

            foreach (string receiverId in clientGroup.UserIds)
            {
                var existNotificationDetailBuilder = Builders <NotificationDetail> .Filter;
                var existNotificationDetailFilter  =
                    existNotificationDetailBuilder.Eq("creator_id", notificationDetail.CreatorId)
                    & existNotificationDetailBuilder.Eq("receiver_id", receiverId)
                    & existNotificationDetailBuilder.Eq("notification_object_id",
                                                        notificationDetail.NotificationObjectId);

                var existNotificationDetail =
                    await notificationDetailRepository.FindAsync(existNotificationDetailFilter);

                var finalNotificationDetail = new NotificationDetail();

                if (existNotificationDetail != null)
                {
                    finalNotificationDetail = existNotificationDetail;
                    finalNotificationDetail.ModifiedDate = DateTime.Now;
                    finalNotificationDetail.IsDeleted    = false;
                    await notificationDetailRepository.UpdateAsync(finalNotificationDetail, finalNotificationDetail.Id);
                }
                else
                {
                    finalNotificationDetail.CreatorId            = notificationDetail.CreatorId;
                    finalNotificationDetail.ReceiverId           = receiverId;
                    finalNotificationDetail.NotificationObjectId = notificationDetail.NotificationObjectId;
                    await notificationDetailRepository.AddAsync(finalNotificationDetail);
                }

                ;

                var notificationObject =
                    await notificationObjectRepository.GetByIdAsync(
                        ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                var owner = await userRepository.GetByIdAsync(ObjectId.Parse(notificationObject.OwnerId));

                var receiver = await userRepository.GetByIdAsync(ObjectId.Parse(receiverId));

                var creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                var notificationTypeFilter =
                    Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                var notificationType = await notificationTypeRepository.FindAsync(notificationTypeFilter);

                string notifyContent = string.Empty;

                if (owner.OId == creator.OId)
                {
                    if (receiver.OId == owner.OId)
                    {
                        notifyContent = $"Bạn {notificationType.ContentTemplate} chính mình";
                    }
                    else if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} họ";
                    }
                }
                else if (owner.OId != creator.OId)
                {
                    if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} {owner.LastName}";
                    }
                    else if (receiver.OId != creator.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} bạn";
                    }
                }


                var notificationToPush = new PushedNotificationViewModel()
                {
                    AuthorName   = $"{creator.FirstName} {creator.LastName}",
                    AuthorAvatar = creator.AvatarHash,
                    AuthorId     = creator.OId,
                    Content      = notifyContent,
                    CreatedDate  = DateTime.Now,
                    IsRead       = false,
                    ModifiedDate = DateTime.Now,
                    ObjectId     = notificationObject.ObjectId,
                    OId          = notificationObject.OId,
                    OwnerId      = owner.OId,
                    Status       = ItemStatus.Active
                };

                switch (notificationType.Code)
                {
                case "ADD_POST_NOTIFY":
                case "UPVOTE_POST_NOTIFY":
                case "DOWNVOTE_POST_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Post;
                    break;

                case "UPVOTE_COMMENT_NOTIFY":
                case "DOWNVOTE_COMMENT_NOTIFY":
                case "COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Comment;
                    break;

                case "UPVOTE_REPLY_NOTIFY":
                case "DOWNVOTE_REPLY_NOTIFY":
                case "REPLY_COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Reply;
                    break;

                case "FOLLOW_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.User;
                    break;

                default:
                    notificationToPush.NotificationType = PushedNotificationType.Other;
                    break;
                }

                try
                {
                    if (!(owner.OId == creator.OId && receiver.OId == owner.OId))
                    {
                        var userFilter = Builders <FcmInfo> .Filter.Eq("user_id", receiverId);

                        string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "notification", JsonConvert.SerializeObject(notificationToPush) }
                            },
                            Notification = new Notification()
                            {
                                Title    = creator.LastName,
                                Body     = notifyContent,
                                ImageUrl = creator.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
        }
Esempio n. 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserNotificationWithNotificationDetail"/> class.
 /// </summary>
 public UserNotificationWithNotificationDetail(UserNotification userNotification, NotificationDetail notificationDetail)
 {
     UserNotification   = userNotification;
     NotificationDetail = notificationDetail;
 }
 /// <summary>
 /// Determines whether the specified
 /// <see cref="NotificationDetail"/> is equal to the current
 /// <see cref="NotificationDetail"/>.
 /// </summary>
 /// <param name="other">
 /// The <see cref="NotificationDetail"/> to compare with the
 /// current <see cref="NotificationDetail"/>.
 /// </param>
 /// <returns>
 /// <c>true</c> if the specified <see cref="NotificationDetail"/>
 /// is equal to the current <see cref="NotificationDetail"/>;
 /// otherwise, <c>false</c>.
 /// </returns>
 public bool Equals(NotificationDetail other)
 {
     return other != null
         && this.Type.Equals(other.Type)
         && object.Equals(this.ChangesSince, other.ChangesSince);
 }
Esempio n. 30
0
 private void NotificationDetailHandler(ref NotificationDetail nd)
 {
     DebugLogger.WriteLine("event " + nd.ToString());
 }
Esempio n. 31
0
 public NotificationsViewModel()
 {
     selectedNotification    = new NotificationDetail();
     notificationsCollection = new ObservableCollection <NotificationDetail>();
     Init();
 }
Esempio n. 32
0
        public async Task PushNotifyPostMatch(string userId, NotificationDetail notificationDetail)
        {
            var currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

            await AddToGroup(
                new AddUserToGroupRequest
            {
                GroupName = userId,
                Type      = Feature.GetTypeName(currentUser),
                UserIds   = new List <string> {
                    userId
                }
            }
                );

            var finder = Builders <ClientGroup> .Filter.Eq("name", userId);

            var clientGroup = await clientGroupRepository.FindAsync(finder);

            foreach (string id in clientGroup.UserIds)
            {
                NotificationDetail finalNotificationDetail = new NotificationDetail()
                {
                    CreatorId            = notificationDetail.CreatorId,
                    ReceiverId           = userId,
                    NotificationObjectId = notificationDetail.NotificationObjectId
                };
                await notificationDetailRepository.AddAsync(finalNotificationDetail);

                NotificationObject notificationObject =
                    await notificationObjectRepository.GetByIdAsync(
                        ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                FilterDefinition <NotificationType> notificationTypeFilter =
                    Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                NotificationType notificationType = await notificationTypeRepository.FindAsync(notificationTypeFilter);

                User creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                PushedNotificationViewModel notificationToPush = new PushedNotificationViewModel()
                {
                    AuthorName   = $"{creator.FirstName} {creator.LastName}",
                    AuthorAvatar = creator.AvatarHash,
                    AuthorId     = creator.OId,
                    Content      = $"{notificationType.ContentTemplate}.",
                    CreatedDate  = DateTime.Now,
                    IsRead       = false,
                    ModifiedDate = DateTime.Now,
                    ObjectId     = notificationObject.ObjectId,
                    OId          = notificationObject.OId,
                    OwnerId      = userId,
                    Status       = ItemStatus.Active
                };
                //Push notification
                try
                {
                    FilterDefinition <FcmInfo> userFilter = Builders <FcmInfo> .Filter.Eq("user_id", userId);

                    string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                    FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                    {
                        Token = token,
                        Data  = new Dictionary <string, string>()
                        {
                            { "notification", JsonConvert.SerializeObject(notificationToPush) }
                        },
                        Notification = new Notification()
                        {
                            Title    = creator.LastName,
                            Body     = notificationToPush.Content,
                            ImageUrl = creator.AvatarHash
                        }
                    };
                    string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
        }
Esempio n. 33
0
        public JsonResult Adduser(Record record)
        {
            try
            {
                var user       = (DemoDoan.ViewModel.UserVM)Session["ACCOUNT"];
                var LangID     = Session[UserVM.CurrentCulture].ToString();
                var TrackingID = string.Empty;
                //Neu user thuoc department thi render ra trackingID
                if (user.DepartmentID > 0)
                {
                    TrackingID          = RenderTrackingID(user.DepartmentID);
                    record.LanguageID   = LangID;
                    record.TrackingID   = TrackingID;
                    record.CreatedDate  = DateTime.Now;
                    record.Modifieddate = DateTime.Now;
                    record.UserID       = user.UserID;
                    record.DepartmentID = user.DepartmentID;
                    record.LocationID   = user.LocationID;
                    record.StatusID     = 4; //set gia tri mac dinh la 4 = Wait For Document trong db
                }
                //Nguoc lai thi fai di tim departmentID cua team do
                else
                {
                    var departmentID = db.Teams.Find(user.TeamID).DepartmentID;
                    record.LanguageID   = LangID;
                    TrackingID          = RenderTrackingID(departmentID);
                    record.TrackingID   = TrackingID;
                    record.CreatedDate  = DateTime.Now;
                    record.Modifieddate = DateTime.Now;
                    record.UserID       = user.UserID;
                    record.TeamID       = user.TeamID;
                    record.LocationID   = user.LocationID;
                    record.StatusID     = 4; //set gia tri mac dinh la 4 = Wait For Document trong db
                }

                db.Records.Add(record);
                db.SaveChanges();

                //Khi add record xong thi add vao bang thong bao
                //b1 tao 1 doi tuong ten la Notifications o trong model

                var notification = new Notifications();
                notification.UserID   = user.UserID;     // thang
                notification.Action   = "Add";
                notification.RecordID = record.RecordID; //todolist

                //b2 goi class Dao co chua ham add notificationdetail
                new NotificationsDao().Add(notification);

                var listUserID = new List <int>();
                listUserID.Add(user.UserID); //session
                listUserID.Add(1);           //admin

                foreach (var userid in listUserID)
                {
                    //b1 tao 1 doi tuong ten la notificationdetail o trong model

                    var notificationdetail = new NotificationDetail();
                    notificationdetail.NotificationID = notification.NotificationID;
                    notificationdetail.UserID         = userid;

                    //b2 goi class Dao co chua ham add notificationdetail
                    new NotificationsDao().AddNotificationDetail(notificationdetail);
                }

                return(Json(new
                {
                    status = true
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(Json(new
                {
                    status = false
                }, JsonRequestBehavior.AllowGet));
            }
        }