public async Task <HttpResponseMessage> UnassignVacancy(HttpRequestMessage request, int candidateId, int vacancyId)
        {
            try
            {
                var userId = ContextParser.GetUserId(request.GetRequestContext());

                var e = await eventService.RegisterCandidateFromVacancyUnassignment(vacancyId, candidateId, userId);

                var updatedCandidate = await candidateService.UnassignVacancy(candidateId, vacancyId, userId);

                unitOfWork.Save();

                var notification = await notificationService.CreateNotification(updatedCandidate.HRM,
                                                                                NotificationTypes.Update, new List <Event> {
                    e
                });

                if (NotificationsHub.IsConnected(updatedCandidate.HRM))
                {
                    await NotificationsHub.PushNotification(notification);
                }

                unitOfWork.Save();

                return(request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                logger.Error(ex, JsonConvert.SerializeObject(new { candidateId, vacancyId }));

                return(request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Exemple #2
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            AppUser appUser = new AppUser()
            {
                FullName = model.FullName, Email = model.Email, BirthDate = model.BirthDate
            };
            var user = new RAIdentityUser()
            {
                UserName = model.Email, Email = model.Email, AppUser = appUser, PasswordHash = RAIdentityUser.HashPassword(model.Password)
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);


            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            UserManager.AddToRole(user.Id, "AppUser");
            NotificationsHub.NotifyAdmin("New User was registered");
            return(Ok());
        }
        public void Ctor_ValidLogger()
        {
            this.SetupBase();
            var hub = new NotificationsHub(this.trackerMock.Object, this.configuration, this.loggerMock.Object);

            Assert.Pass();
        }
 private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
 {
     if (e.Type == SqlNotificationType.Change)
     {
         NotificationsHub.SendMessages();
     }
 }
        public HttpResponseMessage UploadImage()
        {
            //Notify for websocket
            NotificationsHub.NotifyAdmin("New service is added...");

            string imageName   = null;
            var    httpRequest = HttpContext.Current.Request;
            //Upload Image
            var postedFile = httpRequest.Files["Image"];

            //Create custom filename
            imageName = new string(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
            imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
            var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);

            postedFile.SaveAs(filePath);

            Service service = new Service {
                Logo = imageName, Name = httpRequest["Name"], Email = httpRequest["Email"], Description = httpRequest["Description"]
            };

            unitOfWork.Services.Add(service);
            unitOfWork.Complete();

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
 public VersionsController(AppStoreContext context, IHostEnvironment env, NotificationsHub notificationsHub)
 {
     _context          = context;
     _env              = env;
     _notificationsHub = notificationsHub;
     _fileHander       = new FileHandler(_env.ContentRootPath, _context);
 }
        public async Task <HttpResponseMessage> UpdateStatus(HttpRequestMessage request, [FromBody] StatusUpdateInDTO value)
        {
            try
            {
                var userId = ContextParser.GetUserId(request.GetRequestContext());

                var e = await eventService.RegisterCandidateStatusUpdate(value.EntityId, value.Status, userId);

                var candidate = await candidateService.UpdateStatus(value.EntityId, value.Status, userId);

                unitOfWork.Save();

                await candidateElasticService.UpdateStatusElastic(value.EntityId, value.Status).ConfigureAwait(false);

                var notification = await notificationService.CreateNotification(candidate.HRM,
                                                                                NotificationTypes.Update, new List <Event> {
                    e
                });

                if (NotificationsHub.IsConnected(candidate.HRM))
                {
                    await NotificationsHub.PushNotification(notification);
                }

                return(request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                logger.Error(ex, JsonConvert.SerializeObject(value));

                return(request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
        public IHttpActionResult PostService(Service service)
        {
            lock (syncLock)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                if (service.Impressions == null)
                {
                    service.Impressions = new List <Impression>();
                }

                if (service.Branches == null)
                {
                    service.Branches = new List <Branch>();
                }

                if (service.Vehicles == null)
                {
                    service.Vehicles = new List <Vehicle>();
                }

                unitOfWork.Services.Add(service);
                unitOfWork.Complete();

                // notification ----------------------------------------------------------------------------------------
                NotificationsHub.NotifyForService(++ServiceCount);

                return(CreatedAtRoute("DefaultApi", new { id = service.Id }, service));
            }
        }
        public async Task <HttpResponseMessage> SetNotificationListAsReaded(
            [ModelBinder(typeof(ArrayModelBinder))] int[] notificationId)
        {
            HttpResponseMessage responce;

            try
            {
                string receiverLogin = Thread.CurrentPrincipal.Identity.Name.FormatUserName();

                foreach (var id in notificationId)
                {
                    await _notificationDataService.SetNotificationAsReaded(id);
                }

                await NotificationsHub.SetNotificationAsReaded(receiverLogin, notificationId);

                responce = Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                _logger.Error($"NotificationController.SetNotificationListAsReaded", ex);
                responce = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }

            return(responce);
        }
        public async Task <HttpResponseMessage> CreateNotifications(NotificationDTO notify)
        {
            HttpResponseMessage responce;

            try
            {
                notify = await _notificationDataService.CreateNotification(notify);

                _logger.Info($"SendMailController.SendMail [notification.Id: {notify.Id} notification.Protocol: {notify.Protocol}]");

                if (Enum.IsDefined(typeof(Protocol), notify.Protocol))
                {
                    switch ((Protocol)Enum.Parse(typeof(Protocol), notify.Protocol, true))
                    {
                    case Protocol.Email:
                        await _smtpService.SendAsync(notify.Receiver, notify.Body, notify.Channel);

                        break;

                    case Protocol.SignalR:
                        await NotificationsHub.SendNotification(notify.Receiver, notify);

                        break;
                    }
                }
                responce = Request.CreateResponse(HttpStatusCode.OK, notify);
            }
            catch (Exception ex)
            {
                _logger.Error($"SendMailController.SendMail [mail.Id: {notify.Id}]", ex);
                responce = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return(responce);
        }
        public void PostNotification(NotificationsBindingModel m)
        {
            if (!this.ModelState.IsValid)
            {
                return;
            }

            var notification = new Notification
            {
                SenderId   = m.SenderId,
                ReceiverId = m.ReceiverId,
                Content    = m.Content,
                PostedOn   = DateTime.Now
            };

            this.Data.Notifications.Add(notification);

            this.Data.SaveChanges();

            var receiverName = this.Data.Users.FirstOrDefault(u => u.Id == m.ReceiverId).UserName;

            var hub = new NotificationsHub();

            hub.GetNotifications(receiverName);
        }
        /// <summary>
        /// Setups the base.
        /// </summary>
        public void SetupBase()
        {
            var applications = new List <ApplicationAccounts>
            {
                new ApplicationAccounts
                {
                    ApplicationName = "Some Application"
                }
            };
            var jsonRepresentation = JsonSerializer.Serialize(applications);
            Dictionary <string, string> applicationAccounts = new Dictionary <string, string>
            {
                { "ApplicationAccounts", jsonRepresentation }
            };

            this.loggerMock       = new Mock <ILogger <NotificationsHub> >();
            this.clientsMock      = new Mock <IHubCallerClients <INotificationsClient> >();
            this.clientMock       = new Mock <INotificationsClient>();
            this.trackerMock      = new Mock <IUserConnectionTracker>();
            this.configuration    = new ConfigurationBuilder().AddInMemoryCollection(applicationAccounts).Build();
            this.hubContextMock   = new Mock <HubCallerContext>();
            this.notificationsHub = new NotificationsHub(this.trackerMock.Object, this.configuration, this.loggerMock.Object)
            {
                Clients = this.clientsMock.Object
            };
            this.notificationsHub.Context = this.hubContextMock.Object;
            _ = this.hubContextMock.SetupGet(hcm => hcm.ConnectionId).Returns(Guid.NewGuid().ToString());
            _ = this.hubContextMock.SetupGet(hcm => hcm.UserIdentifier).Returns("Some user");
            _ = this.clientsMock.Setup(cls => cls.User(It.IsAny <string>())).Returns(this.clientMock.Object);
            _ = this.clientsMock.SetupGet(cls => cls.All).Returns(this.clientMock.Object);
        }
Exemple #13
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            NotificationsHub.NotifyAdmin("New user is added...");
            var appUser = new AppUser()
            {
                FullName = model.FullName, Email = model.Email, BirthDay = model.DateOfBirth,                          /*CreatingServicesBan = true,*/ /*IsRegistered = false*/
            };

            var user = new RAIdentityUser()
            {
                Id = model.Email, UserName = model.Email, Email = model.Email, AppUser = appUser
            };

            user.PasswordHash = RAIdentityUser.HashPassword(model.Password);
            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            await UserManager.AddToRoleAsync(model.Email, "AppUser");

            if (!result.Succeeded)
            {
                return(Content(System.Net.HttpStatusCode.BadRequest, "User already exists!"));
            }
            return(Ok());
        }
        public async Task <HttpResponseMessage> AssignVacancies(HttpRequestMessage request, CandidatesVacanciesInDTO value)
        {
            try
            {
                var userId = ContextParser.GetUserId(request.GetRequestContext());

                var result = await candidateService.AssignVacancies(value.Vacancies, value.Candidates, userId);

                unitOfWork.Save();

                foreach (var item in result.Events)
                {
                    var notification = await notificationService.CreateNotification(item.Key,
                                                                                    NotificationTypes.Update, item.Value);

                    if (NotificationsHub.IsConnected(item.Key))
                    {
                        await NotificationsHub.PushNotification(notification);
                    }
                }

                unitOfWork.Save();

                return(request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                logger.Error(ex, JsonConvert.SerializeObject(value));

                return(request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
        public IHttpActionResult PostService(Services service)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var list = unitOfWork.Services.GetAll();

            foreach (var item in list)
            {
                if (item.Name == service.Name)
                {
                    return(BadRequest("Already is service with this name: " + service.Name));
                }
            }

            Services ser = new Services()
            {
                Name = service.Name, Email = service.Email, Logo = service.Logo, Owner = service.Owner, Available = false, Description = service.Description, Branches = new List <Branch>(), Vehicles = new List <Vehicle>(), Grade = 0, UsersGrade = new List <string>()
            };

            unitOfWork.Services.Add(ser);
            unitOfWork.Complete();

            NotificationsHub.NotifyAdmin("New service added and requires aproval!");

            return(CreatedAtRoute("DefaultApi", new { id = service.Id }, service));
        }
        public IHttpActionResult PutService(Service service)
        {
            lock (syncLock)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                Service uS = unitOfWork.Services.Get(service.Id);   // bez ovih 6 linija baca exception u Repository na update-u
                uS.Approved    = service.Approved;                  // Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value
                uS.Description = service.Description;
                uS.Email       = service.Email;
                uS.Logo        = service.Logo;
                uS.Name        = service.Name;

                try
                {
                    unitOfWork.Services.Update(uS);
                    unitOfWork.Complete();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ServiceExists(uS.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                if (service.Approved == true)
                {
                    MailMessage mail   = new MailMessage("*****@*****.**", "*****@*****.**"); // drugi parametar service.Creator.Email umesto moje mejl adrese
                    SmtpClient  client = new SmtpClient();
                    client.Port                  = 587;
                    client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new NetworkCredential("*****@*****.**", "mitarsteva.12");
                    client.Host                  = "smtp.gmail.com";
                    client.EnableSsl             = true;
                    mail.Subject                 = "Service approved";
                    mail.Body = "The service that you have made has been approved by our administrators! \n You are now able to add vehicles and branches!";
                    //client.Send(mail);

                    // notification ----------------------------------------------------------------------------------------
                    NotificationsHub.NotifyForService(--ServiceCount);
                }
                else
                {
                    // notification ----------------------------------------------------------------------------------------
                    NotificationsHub.NotifyForService(++ServiceCount);
                }

                return(StatusCode(HttpStatusCode.NoContent));
            }
        }
Exemple #17
0
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            NotificationsHub.NotifyConnected("Jakiś gość wszedł w About :D");

            return(View());
        }
Exemple #18
0
 private void SubscribeToEventNotifications()
 {
     NotificationsHub.Subscribe <SavedInEventStoreEvent>(NotificationHubSubscriptionId,
                                                         evt =>
     {
         return(evt.Source != DeviceId ? Task.CompletedTask : Grid.Reload());
     });
 }
Exemple #19
0
    private void sendRejectMail(string requestNo, string reason, string rejectLevel)
    {
        CommonMail mail = new CommonMail();

        mail.From_address = "*****@*****.**";

        string requestedUser = "";

        requestedUser   = getRequestedUser(requestNo);
        mail.To_address = getEmailOfUser(requestedUser);



        mail.Bcc_address = "*****@*****.**";



        mail.Subject = "Cover Note Book Requested has been Rejected";
        String BodyText;

        BodyText = "<html>" +
                   "<head>" +
                   "<title>Cover Note Book Requested has been Rejected</title>" +
                   " <body> " +
                   "<table>" +
                   "<tr>" +
                   "<td>" +
                   "Cover Note Book request under request no. " + requestNo + " has been rejected from " + rejectLevel + " level." +
                   "</td>" +
                   "</tr>" +
                   "<tr>" +
                   "<td>" +
                   "Reason for Reject - " + reason +
                   "</td>" +
                   "</tr>" +
                   "</table>" +
                   " </body> " +
                   " </html>";


        try
        {
            mail.Body = BodyText;
            mail.sendMail();



            string notificationMsg = "";
            notificationMsg = "Cover Note Book request under request no. " + requestNo + " has been rejected from " + rejectLevel + " level.";

            NotificationsHub nHub = new NotificationsHub();
            nHub.NotifyClientForCoverNoteBookRequests("Cover Note Book Requested has been Rejected", notificationMsg, requestedUser);
        }
        catch (Exception ee)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Error while sending notification e-mail.');", true);
        }
    }
Exemple #20
0
 public void RemoveRelation(long relativeId)
 {
     CitizenBusinessLayer.RemoveRelation(User.Identity.GetUserId <long>(), relativeId, () => {
         if (!CitizenBusinessLayer.IsRelationConfirmed(User.Identity.GetUserId <long>(), relativeId))
         {
             NotificationsHub.NotifyRelative(relativeId, -1);
         }
     });
 }
Exemple #21
0
 public AppsController(AppStoreContext context, ClickHouseDatabase clickDB, UserManager <User> userManager, IHostEnvironment env, NotificationsHub notificationsHub)
 {
     _context          = context;
     _userManager      = userManager;
     _env              = env;
     _fileHandler      = new FileHandler(_env.ContentRootPath, _context);
     _notificationsHub = notificationsHub;
     _logsHandler      = new LogsHandler(clickDB);
 }
Exemple #22
0
        public void NotifyOthers(NotificationType type, string senderId, int postId)
        {
            var sender = GetUserById(senderId);

            if (sender == null)
            {
                throw new ArgumentException("Sender doesn't exist");
            }

            var subscribers = new PostRepository(_context).GetPostSubscriptions(postId).ToList();

            foreach (var subscriber in subscribers)
            {
                if (subscriber.IsOff)
                {
                    continue;
                }

                var notification = _context.Notifications
                                   .FirstOrDefault(n => n.ReceiverId.Equals(subscriber.UserId) && n.SenderId.Equals(sender.Id) && n.NotificationType == type && n.PostId == postId);

                var post = new PostRepository(_context).GetPost(postId);

                if (post == null)
                {
                    throw new ArgumentException("Post doesn't exist");
                }

                if (subscriber.UserId.Equals(sender.Id))
                {
                    continue;
                }

                if (notification == null || type == NotificationType.Comment)
                {
                    var newNotification = new Notification
                    {
                        DateTime         = DateTime.UtcNow,
                        IsRead           = false,
                        PostId           = post.Id,
                        SenderId         = sender.Id,
                        ReceiverId       = subscriber.UserId,
                        NotificationType = type,
                        OwnershipType    = OwnershipType.Other
                    };
                    _context.Notifications.Add(newNotification);

                    NotificationsHub.Notify(subscriber.UserId, sender, newNotification);
                }
            }
        }
Exemple #23
0
        public JsonResult SendSos(SOSViewModel model)
        {
            List <RelationType> relationTypes = citizenBusinessLayer.GetRelationTypes().ToList();
            long     friend         = relationTypes.Single(r => r.Name == "Friend").ID;
            long     parent         = relationTypes.Single(r => r.Name == "Parent").ID;
            long     sibling        = relationTypes.Single(r => r.Name == "Sibling").ID;
            int      numberOfPlaces = 5;
            SOSs     sos            = new SOSs();
            var      user           = User.Identity.GetCitizen();
            var      pointString    = string.Format("POINT({0} {1})", model.Longitude.ToString(), model.Latitude.ToString());
            var      location       = System.Data.Entity.Spatial.DbGeography.FromText(pointString);
            DateTime time           = DateTime.Now;

            sos.Description = model.Description;
            sos.SenderID    = user.Id;
            sos.StatusID    = 1; // Pending
            sos.Time        = time;
            sos.IsAccepted  = false;
            sos.Location    = location;
            List <long> citizens     = new List <long>();
            List <long> contributers = new List <long>();

            if (model.IsMedicalPlace)
            {
                contributers = (sosBusinessLayer.GetContributersOfSOSsServices(pointString, numberOfPlaces)).Where(s => s.Id != user.Id).Select(s => s.Id).ToList();
            }
            if (model.IsFriend)
            {
                citizens = (citizenBusinessLayer.GetCitizenRelatives(user.Id, friend)).Select(c => c.Id).ToList();
            }
            if (model.IsFamily)
            {
                citizens = citizens.Union(citizenBusinessLayer.GetCitizenRelatives(user.Id, parent).Select(c => c.Id)).ToList();
                citizens = citizens.Union(citizenBusinessLayer.GetCitizenRelatives(user.Id, sibling).Select(c => c.Id)).ToList();
            }
            try
            {
                int citizensType     = 2;
                int contributersType = 1;
                sosBusinessLayer.AddSOS(sos);
                NotificationsHub.NotifySOS(sos.ID, citizens, citizensType, model.Description, model.Latitude
                                           , model.Longitude, user.PhoneNumber);
                NotificationsHub.NotifySOS(sos.ID, contributers, contributersType, model.Description, model.Latitude
                                           , model.Longitude, user.PhoneNumber);
                return(Json("Your Request is Successfully Sent"));
            }
            catch (Exception e)
            {
                return(Json(e.Message));
            }
        }
Exemple #24
0
        protected override Task OnInitializedAsync()
        {
            NotificationsHub.Subscribe <SavedInEventStoreEvent>(NotificationHubSubscriptionId, () =>
            {
                if (!AutoUpdateCheckBox)
                {
                    return(Task.CompletedTask);
                }

                _isNewEventComing = true;
                return(Task.CompletedTask);
            });

            return(Task.CompletedTask);
        }
Exemple #25
0
        public IHttpActionResult NotifyAdmin([FromUri] string email)
        {
            Notification notification = new Notification();

            notification.Text = "New user registrated: " + email;
            notification.Date = DateTime.Now;

            if (PostNotification(notification))
            {
                NotificationsHub.Notify(notification);
                return(Ok("Success"));
            }

            NotificationsHub.Notify(null);
            return(Ok("Failure"));
        }
Exemple #26
0
        public IHttpActionResult NotifyAdmin([FromUri] string serviceName, [FromUri] int id)
        {
            Notification notification = new Notification();

            notification.Text = "New service added with name: " + serviceName + " and id: " + id;
            notification.Date = DateTime.Now;

            if (PostNotification(notification))
            {
                NotificationsHub.Notify(notification);
                return(Ok("Success"));
            }

            NotificationsHub.Notify(null);
            return(Ok("Failure"));
        }
        public IHttpActionResult PutUserActivated(PutUserActivatedBindingModel model)
        {
            lock (syncLock)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                AppUser appUser = unitOfWork.AppUsers.Get(model.Email);

                try
                {
                    appUser.Activated = model.Activated;
                    unitOfWork.AppUsers.Update(appUser);
                    unitOfWork.Complete();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (appUser == null)
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                MailMessage mail   = new MailMessage("*****@*****.**", "*****@*****.**"); // drugi parametar model.Email umesto moje adrese
                SmtpClient  client = new SmtpClient();
                client.Port                  = 587;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential("*****@*****.**", "mitarsteva.12");
                client.Host                  = "smtp.gmail.com";
                client.EnableSsl             = true;
                mail.Subject                 = "Document accepted";
                mail.Body = "The document that you have uploaded has been accepted by our administrators! \n You are now able to rent a vehicle that you like!";
                //client.Send(mail);

                // notification --------------------------------------------------------------
                NotificationsHub.NotifyForUser(--AccountCount);

                return(StatusCode(HttpStatusCode.NoContent));
            }
        }
Exemple #28
0
 public JsonResult AcceptSOS(long sosId, long hospitalId)
 {
     try
     {
         List <long> contributers   = new List <long>();
         int         numberOfPlaces = 5;
         string      location       = sosBusinessLayer.GetSOS(sosId).Location.ToString();
         sosBusinessLayer.AcceptSOS(sosId, hospitalId);
         contributers = (sosBusinessLayer.GetContributersOfSOSsServices(location, numberOfPlaces)).Select(s => s.Id).ToList();
         NotificationsHub.HideSOSNotification(contributers);
         return(Json("SOS is Accepted"));
     }
     catch (Exception e)
     {
         return(Json(e.Message));
     }
 }
Exemple #29
0
        public Smtp4devServer(Func <Smtp4devDbContext> dbContextFactory, IOptionsMonitor <ServerOptions> serverOptions,
                              IOptionsMonitor <RelayOptions> relayOptions, NotificationsHub notificationsHub, Func <RelayOptions, SmtpClient> relaySmtpClientFactory)
        {
            this.notificationsHub       = notificationsHub;
            this.serverOptions          = serverOptions;
            this.relayOptions           = relayOptions;
            this.dbContextFactory       = dbContextFactory;
            this.relaySmtpClientFactory = relaySmtpClientFactory;

            DoCleanup();

            IDisposable eventHandler = null;
            var         obs          = Observable.FromEvent <ServerOptions>(e => eventHandler = serverOptions.OnChange(e), e => eventHandler.Dispose());

            obs.Throttle(TimeSpan.FromMilliseconds(100)).Subscribe(OnServerOptionsChanged);

            taskQueue.Start();
        }
        public IHttpActionResult PostService(Service service)
        {
            lock (o)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                service.Owner = User.Identity.Name;

                unitOfWork.Services.Add(service);
                unitOfWork.Complete();

                NotificationsHub.NotifyAdmin("New service added and requires aproval!");

                return(CreatedAtRoute("DefaultApi", new { id = service.Id }, service));
            }
        }