Exemple #1
0
        /// <summary>
        /// Create or Update an Event Cluster
        /// </summary>
        /// <param name="eventObj">EventClusterCreationModel</param>
        /// <returns>EventClusterModel</returns>
        public async Task <EventClusterModel> CreateOrUpdateEventCluster(EventClusterCreationModel eventObj)
        {
            //Look for existing cluster that matches DeviceId + EventType and hasn't ended yet.
            EventClusterDAO eventCluster = await _repoEventClusters.GetItemAsync(eventObj.EventClusterId);

            //Create
            if (eventCluster == null)
            {
                return(await CreateEventCluster(eventObj));
            }

            eventCluster.Events = eventCluster.Events.Append(_mapper.Map <EventDAOObject>(eventObj)).OrderByDescending(p => p.Date).ToArray();
            eventCluster.EventCount++;
            try
            {
                await _repoEventClusters.UpdateItemAsync(eventCluster);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await CreateOrUpdateEventCluster(eventObj));
                }
                throw e;
            }

            var output = _mapper.Map <EventClusterModel>(eventCluster);

            output.Events = output.Events.Take(3);
            return(output);
        }
        public async Task <IActionResult> UpdateCustomGroup([FromBody] CustomGroupModel customGroup)
        {
            logger.LogInformation("Update custom group called");

            //Ensure the current user is allowed to edit this template
            var customGroupItem = await _GroupsRepo.GetItemAsync(customGroup.Id);

            if (customGroupItem == null)
            {
                logger.LogError("Update custom group - Exception: Custom group with id {0} was not found.", customGroup.Id);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            var groupDetails = _DeviceServiceDB.GetDevicesTwinInfoAsync(new DeviceQueryConfiguration()
            {
                ItemsPerPage = 1,
                Where        = customGroup.Where
            });

            customGroup.Count = groupDetails.ItemsCount;

            //Update Custom Group
            bool status = await _GroupsRepo.UpdateItemAsync(customGroup.Id, customGroup);

            if (!status)
            {
                logger.LogError("Update custom group - Exception: There was an error while updating the custom group {0}", customGroup.Id);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(status));
        }
        /// <summary>
        /// Create or update a device
        /// </summary>
        /// <param name="deviceTwinObj">DeviceTwinModel</param>
        /// <returns>DeviceModel</returns>
        public async Task <DeviceModel> CreateOrUpdateDevice(DeviceTwinModel deviceTwinObj)
        {
            if (deviceTwinObj.DeviceId == Guid.Empty)
            {
                throw new Exception($"No device found that matches DeviceId: {deviceTwinObj.DeviceId}");
            }

            DeviceDAO deviceDAO = await _repoDevices.GetItemAsync(deviceTwinObj.DeviceId);

            //Create
            if (deviceDAO == null)
            {
                return(await CreateDevice(deviceTwinObj));
            }

            //Update
            deviceDAO.IoTDevice = true;
            if (deviceTwinObj.Properties?.Desired != null)
            {
                deviceDAO.Desired = deviceTwinObj.Properties.Desired;
            }
            if (deviceTwinObj.Properties?.Reported != null)
            {
                deviceDAO.Reported = deviceTwinObj.Properties.Reported;
            }
            if (deviceTwinObj.Tags != null)
            {
                deviceDAO.DeviceType  = deviceTwinObj.Tags.DeviceType;
                deviceDAO.Enabled     = deviceTwinObj.Tags.Enabled;
                deviceDAO.Custom      = deviceTwinObj.Tags.Custom;
                deviceDAO.Name        = deviceTwinObj.Tags.Name;
                deviceDAO.Location1   = deviceTwinObj.Tags.Location1;
                deviceDAO.Location2   = deviceTwinObj.Tags.Location2;
                deviceDAO.Location3   = deviceTwinObj.Tags.Location3;
                deviceDAO.SSID        = deviceTwinObj.Tags.SSID;
                deviceDAO.Sensor      = deviceTwinObj.Tags.Sensor;
                deviceDAO.Geolocation = _mapper.Map <GeolocationDAOObject>(deviceTwinObj.Tags.Geolocation);
            }

            try
            {
                await _repoDevices.UpdateItemAsync(deviceDAO);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await CreateOrUpdateDevice(deviceTwinObj));
                }
                throw e;
            }

            return(_mapper.Map <DeviceModel>(deviceDAO));
        }
Exemple #4
0
        public async Task <IActionResult> EditUserTemplate([FromBody] Template template)
        {
            Domain.Model.User currentUser = await EnsureCurrentUser();

            string userId = currentUser.Id.ToLower();

            //Ensure user values and unique ID are set server side.
            template.DocType      = TemplateDocumentType.User;
            template.UserId       = userId;
            template.ModifiedDate = DateTime.Now;

            //Ensure the current user is allowed to edit this template
            Template userTemplate = await _templateRepo.GetItemAsync(template.Id);

            if (userTemplate == null || userTemplate.UserId == null || userTemplate.UserId.ToLower() != userId)
            {
                logger.LogError("API EditUserTemplate error: Template with id {TemplateId} was found but the user {UserId} does not match.", template.Id, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            if (userTemplate.DocType != TemplateDocumentType.User)
            {
                logger.LogError("API EditUserTemplate error: Template with id {TemplateId} is not a user template.", template.Id, userId);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            //Create new user template
            bool status = await _templateRepo.UpdateItemAsync(template.Id, template);

            if (!status)
            {
                Log.Error("API EditUserTemplate error: There was an error while creating the template {TemplateId}", template.Id);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(Ok(status));
        }
        /// <summary>
        /// Update an action plan
        /// </summary>
        /// <param name="actionPlanObj">ActionPlanUpdateModel</param>
        /// <returns>ActionPlanModel</returns>
        public async Task <ActionPlanModel> UpdateActionPlan(ActionPlanUpdateModel actionPlanObj)
        {
            ActionPlanDAO plan = await _repoActionPlans.GetItemAsync(actionPlanObj.ActionPlanId);

            if (plan == null)
            {
                throw new Exception($"No action plan found that matches responseid: {actionPlanObj.ActionPlanId}");
            }

            string   etag         = plan.ETag;
            DateTime creationDate = plan.CreationDate;

            plan              = _mapper.Map <ActionPlanDAO>(actionPlanObj);
            plan.ETag         = etag;
            plan.CreationDate = creationDate;

            try
            {
                await _repoActionPlans.UpdateItemAsync(plan);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await UpdateActionPlan(actionPlanObj));
                }
                throw e;
            }

            var output = _mapper.Map <ActionPlanModel>(plan);

            return(output);
        }
        public async Task UpdateEvent(EventModel eventObj)
        {
            await _repoEvents.UpdateItemAsync(eventObj.Id, eventObj);

            if (_config.UseCache)
            {
                await GetEvent(eventObj.Id, true);
            }
        }
Exemple #7
0
        public async Task <DeliveryModel> UpdateDeliveryForEvent(string eventId, DeliveryModel delivery)
        {
            await _repoDeliveries.UpdateItemAsync(delivery.Id, delivery);

            if (_config.UseCache)
            {
                await GetDeliveryForEvent(eventId, delivery.DeliveryId, true);
            }

            return(await GetDeliveryForEvent(eventId, delivery.DeliveryId));
        }
Exemple #8
0
        public async Task <ActionResult> EditAsync([Bind("Id,Name,Description,Completed")] Item item)
        {
            if (ModelState.IsValid)
            {
                await _cosmosDBRepository.UpdateItemAsync(item.Id, item);

                return(RedirectToAction("Index"));
            }

            return(View(item));
        }
Exemple #9
0
        private async Task <bool> UpdateRegistrationUserInfo(string eventId, string locationId, string firstName, string lastName, string zipCode, RegistrationModel registration)
        {
            try
            {
                if (registration.Events.Find(p => p.EventId == eventId && p.LocationId == locationId) != null &&
                    string.Equals(registration.FirstName, firstName) &&
                    string.Equals(registration.LastName, lastName) &&
                    string.Equals(registration.ZipCode, zipCode))
                {
                    // no change to the registration
                    return(true);
                }

                if (registration.Events.Find(p => p.EventId == eventId && p.LocationId == locationId) == null)
                {
                    registration.Events.Add(CreateNewRegistrationEvent(eventId, locationId));
                }

                registration.FirstName = firstName;
                registration.LastName  = lastName;
                registration.ZipCode   = zipCode;

                return(await _repoRegistrations.UpdateItemAsync(registration.Id, registration));
            }
            catch (DocumentClientException dCE)
            {
                if (dCE.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    registration = await _repoRegistrations.GetItemAsync(registration.Id);

                    return(await UpdateRegistrationUserInfo(eventId, locationId, firstName, lastName, zipCode, registration));
                }
                throw new Exception(dCE.Message, dCE);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }
        private async Task SaveUpdatedRoute(RouteModel route)
        {
            RouteModel prev = await _repoRoutes.GetItemAsync(p => p.RouteId == route.RouteId);

            if (prev == null)
            {
                await _repoRoutes.CreateItemAsync(route);
            }
            else
            {
                route.Id = prev.Id;
                await _repoRoutes.UpdateItemAsync(prev.Id, route);
            }
        }
        public async Task <bool> AddConversationReference(ConversationReference conversationReference)
        {
            ChatUserSessionDAO newDAO = Mapper.Map <ChatUserSessionDAO>(conversationReference);

            ChatUserSessionDAO oldDAO = await _repoChatUserSessions.GetItemAsync(newDAO.Id);

            if (oldDAO == null)
            {
                string id = await _repoChatUserSessions.CreateItemAsync(newDAO);

                return(!string.IsNullOrEmpty(id));
            }
            else
            {
                oldDAO.BotId          = newDAO.BotId;
                oldDAO.BotName        = newDAO.BotName;
                oldDAO.ChannelId      = newDAO.ChannelId;
                oldDAO.ConversationId = newDAO.ConversationId;
                oldDAO.ServiceUrl     = newDAO.ServiceUrl;
                oldDAO.Name           = newDAO.Name;
                oldDAO.Role           = newDAO.Role;

                try
                {
                    return(await _repoChatUserSessions.UpdateItemAsync(oldDAO));
                }
                catch (DocumentClientException e)
                {
                    //Update concurrency issue, retrying
                    if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                    {
                        return(await AddConversationReference(conversationReference));
                    }
                    throw e;
                }
            }
        }
        public async Task <ChatReportModel> CreateOrUpdateChatReport(ChatReportLogCreationModel reportLogObj)
        {
            if (string.IsNullOrEmpty(reportLogObj.User?.Id))
            {
                throw new Exception($"No userId found.");
            }

            ChatReportDAO reportDAO = await _repoChatReports.GetItemAsync(p => p.User.Id == reportLogObj.User.Id && p.EndDate.Value == null);

            //Create
            if (reportDAO == null)
            {
                return(await CreateChatReport(reportLogObj));
            }

            //Update
            ReportLogDAOObject reportLogDAO = Mapper.Map <ReportLogDAOObject>(reportLogObj.Message);

            reportDAO.ReportLogs.Add(reportLogDAO);

            try
            {
                await _repoChatReports.UpdateItemAsync(reportDAO);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await CreateOrUpdateChatReport(reportLogObj));
                }
                throw e;
            }

            return(Mapper.Map <ChatReportModel>(reportDAO));
        }
        /// <summary>
        /// Set the safe status of a user
        /// </summary>
        /// <param name="response">ResponseDAO</param>
        /// <param name="userId">User Id</param>
        /// <param name="isSafe">True if the user is safe</param>
        /// <returns>true if the call succeeded</returns>
        public async Task <bool> SetSafeStatus(ResponseDAO response, string userId, bool isSafe)
        {
            try
            {
                if (response.SafeUsers == null)
                {
                    response.SafeUsers = new List <string>();
                }

                if (isSafe && !response.SafeUsers.Contains(userId))
                {
                    response.SafeUsers.Add(userId);
                }
                else if (!isSafe && response.SafeUsers.Contains(userId))
                {
                    response.SafeUsers.Remove(userId);
                }
                else
                {
                    return(true); //no reason to update
                }
                await _repoResponses.UpdateItemAsync(response);

                return(true);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    response = await _repoResponses.GetItemAsync(response.Id);
                }
                return(await SetSafeStatus(response, userId, isSafe));

                throw e;
            }
        }
Exemple #14
0
        public async Task <Patient> UpdateAsync(string id, Patient updatedpatient)
        {
            var item = await Respository.UpdateItemAsync(id, updatedpatient);

            return((Patient)(dynamic)item);
        }
Exemple #15
0
        public async Task <Doctor> UpdateAsync(string id, Doctor updateddoctor)
        {
            var item = await Respository.UpdateItemAsync(id, updateddoctor);

            return((Doctor)(dynamic)item);
        }
Exemple #16
0
        public async Task <Appointment> UpdateAsync(Guid id, Appointment updatedappointment)
        {
            var item = await Respository.UpdateItemAsync(id.ToString(), updatedappointment);

            return((Appointment)(dynamic)item);
        }