public async Task <IActionResult> Edit(int id, [Bind("Id,IncidentStatusName")] IncidentStatus incidentStatus)
        {
            if (id != incidentStatus.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(incidentStatus);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!IncidentStatusExists(incidentStatus.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(incidentStatus));
        }
예제 #2
0
        /// <summary>
        /// Get incidents from an Azure Sentinel Workspace
        /// </summary>
        /// <param name="status">The status of the incident</param>
        /// <param name="limit">The amount of incidents to get</param>
        /// <param name="Workspace">The workspace in which the incidents reside</param>
        /// <returns></returns>
        public async Task <List <SentinelIncident> > GetIncidentsAsync(IncidentStatus status, int limit, AzureSentinelWorkspace Workspace)
        {
            var httpClient = await GetAuthenticatedHttpClientAsync(Workspace.AppRegistration.DirectoryId, Workspace.AppRegistration.ClientId, Workspace.AppRegistration.AppSecret);

            string url = String.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights/workspaces/{2}/providers/Microsoft.SecurityInsights/incidents?api-version=2020-01-01&$filter=properties/status eq '{3}'&$top={4}&$orderby=properties/createdTimeUtc desc",
                                       Workspace.SubscriptionId,
                                       Workspace.ResourceGroup,
                                       Workspace.WorkspaceName,
                                       status.ToString(),
                                       limit);

            var response = await httpClient.GetAsync(url);

            if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
            {
                throw new ArgumentException(String.Format("Getting incidents from workspace {0} resulted in: 403 - Forbidden", Workspace.WorkspaceName));
            }

            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                var message = await response.Content.ReadAsStringAsync();

                throw new ArgumentException(String.Format("Something went wrong: '{0}'", message));
            }

            var responseJson = await response.Content.ReadAsStringAsync();

            var incidentsResult = JsonSerializer.Deserialize <SentinelList>(responseJson, GetJsonSerializerOptions());

            return(incidentsResult.Value);
        }
예제 #3
0
        public void AddUpdate(IncidentStatus status, string message, StatusDataContext context = null)
        {
            UpdatedAt = DateTime.UtcNow;

            if (Updates != null)
            {
                Updates.Add(new IncidentUpdate
                {
                    IncidentId = Id,
                    Status     = status,
                    Message    = message
                });
            }
            else if (context == null)
            {
                throw new ArgumentNullException(nameof(context), "You must provide a context if the Updates collection isn't valid.");
            }
            else if (context.Entry(this).IsKeySet)
            {
                context.Add(new IncidentUpdate
                {
                    IncidentId = Id,
                    Status     = status,
                    Message    = message
                });
            }
            else
            {
                throw new InvalidOperationException("Could not add a new Incident");
            }
        }
예제 #4
0
        public int AddIncidentStatus(IncidentStatusDomain incidentStatus)
        {
            var incidentStatusDb = new IncidentStatus().FromDomainModel(incidentStatus);

            _context.IncidentStatus.Add(incidentStatusDb);
            _context.SaveChanges();
            return(incidentStatusDb.IncidentStatusId);
        }
        public async Task<ActionResult> PagerDutyActionIncident(string incident, IncidentStatus newStatus)
        {
            var pdUser = CurrentPagerDutyPerson;
            if (pdUser == null) return ContentNotFound("PagerDuty Person Not Found for " + Current.User.AccountName);

            var newIncident = await PagerDutyApi.Instance.UpdateIncidentStatusAsync(incident, pdUser, newStatus);

            return Json(newIncident?[0]?.Status == newStatus);
        }
예제 #6
0
        public IncidentTO ChangeIncidentStatus(IncidentStatus statusToSubmit, int incidentId)
        {
            var incident = unitOfWork.IncidentRepository.GetById(incidentId);

            incident.Status = statusToSubmit;
            var updatedIncident = unitOfWork.IncidentRepository.Update(incident);

            return(updatedIncident);
        }
예제 #7
0
 public static IncidentStatusDomain ToDomainModel(this IncidentStatus obj)
 {
     return(obj == null ? null : new IncidentStatusDomain()
     {
         IncidentStatusId = obj.IncidentStatusId,
         Name = obj.Name,
         Code = obj.Code,
         IsActive = obj.IsActive
     });
 }
예제 #8
0
 public Task <Response <bool> > UpdateAsync(string details, IncidentStatus status, string[] componentIds, string[] containerIds, string statusPageId = null)
 {
     return(client.PostAsync <Response <bool> >("component/status/update", new
     {
         statuspage_id = client.GetStatusPageId(statusPageId),
         details,
         components = componentIds,
         containers = containerIds,
         current_status = status,
     }));
 }
예제 #9
0
 public Task<Response<bool>> UpdateAsync(string details, IncidentStatus status, string[] componentIds, string[] containerIds, string statusPageId = null)
 {
     return client.PostAsync<Response<bool>>("component/status/update", new
     {
         statuspage_id = client.GetStatusPageId(statusPageId),
         details,
         components = componentIds,
         containers = containerIds,
         current_status = status,
     });
 }
        public async Task <IActionResult> Create([Bind("Id,IncidentStatusName")] IncidentStatus incidentStatus)
        {
            if (ModelState.IsValid)
            {
                _context.Add(incidentStatus);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(incidentStatus));
        }
        public Incident(IncidentStatus status, IncidentSeverity severity, IncidentFeedbackFrequency freq, IncidentCommunicationType comType)
        {
            info = new IncidentInfo();

            info.Status            = EnumUtils.stringValueOf(status);
            info.Severity          = EnumUtils.stringValueOf(severity);
            info.FeedbackFrequency = EnumUtils.stringValueOf(freq);
            info.CommunicationType = EnumUtils.stringValueOf(comType);
            info.Opened            = new DateEpoch(DateTime.UtcNow);
            info.Resources         = null;
            info.Comments          = null;
        }
        public static async void AddResource(string id, IncidentStatus stage, string engineer, DateTime st, DateTime end)
        {
            using (Incident inc = new Incident())
            {
                await Task.Run(
                    async() =>
                {
                    IncidentInfo ic = await inc.AddResource(id, stage, engineer, st, end);

                    OutputCaseDetails(ic);
                });
            }
        }
        public async Task <ActionResult> PagerDutyActionIncident(string incident, IncidentStatus newStatus)
        {
            var pdUser = CurrentPagerDutyPerson;

            if (pdUser == null)
            {
                return(ContentNotFound("PagerDuty Person Not Found for " + Current.User.AccountName));
            }

            var newIncident = await PagerDutyAPI.Instance.UpdateIncidentStatusAsync(incident, pdUser, newStatus).ConfigureAwait(false);

            return(Json(newIncident?.Status == newStatus));
        }
예제 #14
0
        public static IncidentStatus FromDomainModel(this IncidentStatus obj, IncidentStatusDomain domain)
        {
            if (obj == null)
            {
                obj = new IncidentStatus();
            }

            obj.IncidentStatusId = domain.IncidentStatusId;
            obj.Name             = domain.Name;
            obj.Code             = domain.Code;
            obj.IsActive         = domain.IsActive;

            return(obj);
        }
예제 #15
0
        public void StopAzureProcess(int incidentId, IncidentStatus incidentStatus)
        {
            try
            {
                using (var _dbContext = new ZetronContext(options.Options))
                {
                    //Trigger Media Summary Q
                    if (incidentStatus == IncidentStatus.Stopped)
                    {
                        var media = _dbContext.ZetronTrnMediaDetails.FirstOrDefault(i => i.IncidentId == incidentId);
                        if (media != null)
                        {
                            var queue = _queueClient.GetQueueReference("zetron-media-summary");
                            queue.CreateIfNotExistsAsync();
                            var queueMessage = new JObject
                            {
                                ["mediaId"]   = media.MediaId,
                                ["mediaUrl"]  = media.MediaUrl,
                                ["mediaName"] = media.Name
                            };

                            var message = new CloudQueueMessage(queueMessage.ToString());
                            queue.AddMessageAsync(message);
                        }
                        else
                        {
                            Log("MediaContext - StopAzureProcess - No matching media details found!");
                        }
                    }

                    var         livePrograms = _channel.Programs.ToList();
                    List <Task> tasks        = new List <Task>();
                    foreach (var program in livePrograms)
                    {
                        if (program.State == ProgramState.Running)
                        {
                            tasks.Add(program.StopAsync());
                        }
                    }
                    Task.WaitAll(tasks.ToArray());
                    livePrograms.ForEach(p => p.DeleteAsync());
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
                throw;
            }
        }
        public static string GetIncidentStatus(IncidentStatus status)
        {
            var statusText = status switch
            {
                IncidentStatus.Investigating => "Investigating",
                IncidentStatus.Identified => "Identified",
                IncidentStatus.Monitoring => "Monitoring",
                IncidentStatus.Update => "Update",
                IncidentStatus.Resolved => "Resolved",
                _ => "Unknown"
            };

            return(statusText);
        }
    }
        protected override void ExecuteWorkflowLogic()
        {
            var incidentCloseRequest = new CloseIncidentRequest()
            {
                Status             = IncidentStatus.Get(Context.ExecutionContext),
                IncidentResolution = new Entity("incidentresolution")
                {
                    ["subject"]     = Subject.Get(Context.ExecutionContext),
                    ["incidentid"]  = Incident.Get(Context.ExecutionContext),
                    ["description"] = Description.Get(Context.ExecutionContext),
                    ["timespent"]   = TimeSpent.Get(Context.ExecutionContext)
                }
            };

            Context.UserService.Execute(incidentCloseRequest);
        }
예제 #18
0
        protected override void ExecuteWorkflowLogic(CodeActivityContext executionContext, IWorkflowContext context, IOrganizationService service)
        {
            var incidentCloseRequest = new CloseIncidentRequest()
            {
                Status             = IncidentStatus.Get(executionContext),
                IncidentResolution = new Entity("incidentresolution")
                {
                    ["subject"]     = Subject.Get(executionContext),
                    ["incidentid"]  = Incident.Get(executionContext),
                    ["actualend"]   = CloseDate.Get(executionContext),
                    ["description"] = Description.Get(executionContext)
                }
            };

            service.Execute(incidentCloseRequest);
        }
        public IEnumerable <IncidentInfo> FindByStatus(IncidentStatus status)
        {
            if (client == null)
            {
                Connect2DocDb();
            }

            if (info != null && client != null)
            {
                var cases =
                    from c in client.CreateDocumentQuery <IncidentInfo>(docDbUrl)
                    where c.Status == status.ToString()
                    select c;

                return(cases);
            }
            else
            {
                return(null);
            }
        }
예제 #20
0
        public async Task<List<Incident>> UpdateIncidentStatusAsync(string incidentId, PagerDutyPerson person, IncidentStatus newStatus)
        {
            if (person == null) throw new ArgumentNullException(nameof(person));

            var data = new PagerDutyIncidentPut
            {
                Incidents = new List<Incident>
                {
                    new Incident {Id = incidentId, Status = newStatus}
                },
                RequesterId = person.Id
            };

            var result = await Instance.GetFromPagerDutyAsync("incidents",
                response => JSON.Deserialize<IncidentResponse>(response.ToString(), JilOptions),
                httpMethod: "PUT",
                data: data);

            Incidents.Poll(true);

            return result?.Incidents ?? new List<Incident>();
        }
        public IncidentItem(string Region, string Suburb, string Location, DateTime LastUpdate,
            IncidentType Type, IncidentStatus Status, int ApplianceCount, string Size,
            string ID, string Latitude, string Longitude, string AgencyResponsible, CFAIncidentSource parent, CFAIncidentSourceOptions options)
        {
            mRegion = Region;
            Region_GENERIC = Region.ToString();

            mSuburb = Suburb;
            Suburb_GENERIC = Suburb;

            mLocation = Location;
            Location_GENERIC = Location;

            mLatitude = Latitude;
            mLongitude = Longitude;

            mLastUpdate = LastUpdate;
            LastUpdate_GENERIC = LastUpdate;

            mResponsible = AgencyResponsible;

            mIncidentType = Type;
            Type_GENERIC = IncidentItem.IncidentTypeToString(Type);

            mIncidentStatus = Status;
            Status_GENERIC = IncidentItem.IncidentStatusToString(Status);

            mApplianceCount = ApplianceCount;
            ApplianceCount_GENERIC = ApplianceCount;

            mIncidentSize = Size;
            Size_GENERIC = Size;

            mIncidentID = ID;
            ID_GENERIC = SourceConstants.ID_PREFIX + ID;

            mParent = parent;
            mOptions = options;
        }
        public static async Task <string> OpenCase(string description, IncidentStatus st, IncidentSeverity sv,
                                                   IncidentFeedbackFrequency ff, IncidentCommunicationType ct)
        {
            string id = string.Empty;

            using (Incident inc = new Incident(st, sv, ff, ct))
            {
                var issue = await inc.Open(description);

                if (issue != null)
                {
                    var i = JsonConvert.DeserializeObject <IncidentInfo>(issue.ToString());

                    Console.WriteLine(cStrCaseCreated);
                    Console.WriteLine(issue.ToString());

                    id = issue.Id;
                }
            }

            return(id);
        }
        public static void FindByStatus(IncidentStatus status)
        {
            using (Incident inc = new Incident())
            {
                IEnumerable <IncidentInfo> issues = inc.FindByStatus(status);

                Console.WriteLine("FindByStatus: " + EnumUtils.stringValueOf(status));

                if (issues.Count() > 0)
                {
                    Console.Write(Environment.NewLine);

                    foreach (var issue in issues)
                    {
                        OutputCaseDetails(issue);
                        Console.Write(Environment.NewLine);
                    }
                }

                Console.WriteLine(cStrTotalResults + issues.Count().ToString());
            }
        }
예제 #24
0
        public IncidentObject NewIncident(
            string name,
            string message,
            IncidentStatus status,
            bool visible,
            int component_id = 0,
            ComponentStatus?component_status = null,
            bool notifySubscribers           = false,
            DateTime?created_at = null,
            string template     = "",
            string[] vars       = null
            )
        {
            var Request = new RestRequest("incidents").AddJsonBody(new
            {
                name             = name,
                message          = message,
                status           = (int)status,
                visible          = visible ? 1 : 0,
                component_id     = component_id,
                component_status = ((int?)component_status) ?? 0,
                notify           = notifySubscribers,
                created_at       = created_at ?? DateTime.Now,
                template         = template ?? "",
                vars             = vars ?? new string[] { }
            });
            var Response = this.Rest.Post <IncidentResponse>(Request);

            if (Response.ResponseStatus == ResponseStatus.Completed)
            {
                var resp = Response.Data;

                if (resp != null)
                {
                    return(resp?.Data);
                }
            }
            return(null);
        }
예제 #25
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            //Interface should be declared in Contracts
            PropertySetting.IEntitySettingsAppService _entitySettingsService = (PropertySetting.IEntitySettingsAppService)validationContext.GetService(typeof(PropertySetting.IEntitySettingsAppService));

            Dictionary <string, PropertySetting.PropertySettingValue> settingConfig = AsyncHelper.RunSync(() => _entitySettingsService.GetAsync());

            if (settingConfig != null && settingConfig.Count > 0)
            {
                PropertySetting.PropertySettingValue checkIncidentStatus = settingConfig[PropertySetting.PropertySettingNames.Incidents.Reviews.IncidentStatus];

                if (checkIncidentStatus.Visible)
                {
                    if (IncidentStatus.IsNullOrEmpty())
                    {
                        yield return(new ValidationResult(string.Format("The {0} field is required.", "IncidentStatus"), new[] { "IncidentStatus" }));
                    }

                    if (checkIncidentStatus.RequiredRegEx)
                    {
                        if (!string.IsNullOrEmpty(checkIncidentStatus.RegExRule) && new Regex(checkIncidentStatus.RegExRule).IsMatch(IncidentStatus) == false)
                        {
                            yield return(new ValidationResult(string.Format("The field {0} is invalid.", "IncidentStatus"), new[] { "IncidentStatus" }));
                        }
                    }
                }

                PropertySetting.PropertySettingValue checkEndDate = settingConfig[PropertySetting.PropertySettingNames.Incidents.Reviews.EndDate];

                if (checkEndDate.Visible)
                {
                    if (EndDate == null)
                    {
                        yield return(new ValidationResult(string.Format("The {0} field is required.", "EndDate"), new[] { "EndDate" }));
                    }
                }
            }
        }
예제 #26
0
        public bool AddIncidentUpdate(
            int incidentId,
            string message,
            IncidentStatus status
            )
        {
            var Request = new RestRequest("incidents/{id}/updates")
                          .AddUrlSegment("id", incidentId)
                          .AddJsonBody(new
            {
                message = message,
                status  = (int)status,
            });
            var Response = this.Rest.Post <IncidentResponse>(Request);

            if (Response.ResponseStatus == ResponseStatus.Completed)
            {
                var resp = Response.Data;

                return(resp != null);
            }
            return(false);
        }
예제 #27
0
 /// <summary>
 /// Check the status of the live streaming
 /// </summary>
 /// <returns>streaming status</returns>
 public bool CheckStreamingStatus()
 {
     try
     {
         _log.Info($"Streaming Url: {strStreamingUrl}");
         IncidentStatus status = IncidentStatus.Initiated;
         using (var vc = new VideoCapture(strStreamingUrl))
         {
             if (vc.IsOpened())
             {
                 _log.Info($"Video Opened...");
                 return(true);
             }
             else
             {
                 _log.Info($"Video not open. Checking db for streaming status...");
                 status = _dbContext.CheckEventState((int)_mediaObject["mediaId"]);
             }
         }
         if (status == IncidentStatus.Processing)
         {
             _log.Info($"Streaming in-progress...");
             Thread.Sleep(3000);
             return(CheckStreamingStatus());
         }
         else if (status == IncidentStatus.Stopped || status == IncidentStatus.Deactivated)
         {
             _log.Info($"Streaming stopped...");
             return(false);
         }
     }
     catch (Exception e)
     {
         _log.Error($"Video processing exception.: ", e);
     }
     return(false);
 }
예제 #28
0
        public async Task <Incident> UpdateIncidentStatusAsync(string incidentId, PagerDutyPerson person, IncidentStatus newStatus)
        {
            if (person == null)
            {
                throw new ArgumentNullException(nameof(person));
            }
            var data = new
            {
                incident = new
                {
                    type   = "incident_reference",
                    status = newStatus.ToString()
                }
            };

            var headers = new Dictionary <string, string>
            {
                ["From"] = person.Email
            };

            try
            {
                var result = await GetFromPagerDutyAsync($"incidents/{incidentId}",
                                                         response => JSON.Deserialize <PagerDutyIncidentUpdateResp>(response, JilOptions),
                                                         httpMethod : "PUT",
                                                         data : data,
                                                         extraHeaders : headers);

                await Incidents.PollAsync(true);

                return(result?.Response ?? new Incident());
            }
            catch (DeserializationException de)
            {
                de.AddLoggedData("Message", de.Message)
                .AddLoggedData("Snippet After", de.SnippetAfterError)
                .Log();
                return(null);
            }
        }
예제 #29
0
        public async Task <List <Incident> > UpdateIncidentStatusAsync(string incidentId, PagerDutyPerson person, IncidentStatus newStatus)
        {
            if (person == null)
            {
                throw new ArgumentNullException(nameof(person));
            }

            var data = new PagerDutyIncidentPut
            {
                Incidents = new List <Incident>
                {
                    new Incident {
                        Id = incidentId, Status = newStatus
                    }
                },
                RequesterId = person.Id
            };

            var result = await Instance.GetFromPagerDutyAsync("incidents",
                                                              response => JSON.Deserialize <IncidentResponse>(response.ToString(), JilOptions),
                                                              httpMethod : "PUT",
                                                              data : data);

            Incidents.Poll(true);

            return(result?.Incidents ?? new List <Incident>());
        }
        public async Task <IncidentInfo> AddResource(string id, IncidentStatus stage, string engineer, DateTime st, DateTime end)
        {
            if (client == null)
            {
                Connect2DocDb();
            }

            if (info != null && client != null)
            {
                var cases =
                    from c in client.CreateDocumentQuery(docDbUrl)
                    where c.Id.ToUpper().Contains(id.ToUpper())
                    select c;

                IncidentInfo issue = null;
                Document     oDoc  = null;

                foreach (var cs in cases)
                {
                    var it = await client.ReadDocumentAsync(cs.AltLink);

                    oDoc  = it;
                    issue = (IncidentInfo)(dynamic)it.Resource;

                    break;
                }

                if (oDoc != null)
                {
                    AllocatedResource rc = new AllocatedResource();

                    rc.End      = new DateEpoch((end != null) ? end.ToUniversalTime() : DateTime.UtcNow);
                    rc.Engineer = engineer;
                    rc.Stage    = EnumUtils.stringValueOf(stage);
                    rc.Start    = new DateEpoch((st != null) ? st.ToUniversalTime() : DateTime.UtcNow);

                    List <AllocatedResource> rRsc = new List <AllocatedResource>();

                    if (issue?.Resources?.Length > 0)
                    {
                        rRsc.AddRange(issue.Resources);
                        rRsc.Add(rc);

                        oDoc.SetPropertyValue(cStrResources, rRsc.ToArray());
                    }
                    else
                    {
                        rRsc.Add(rc);
                        oDoc.SetPropertyValue(cStrResources, rRsc.ToArray());
                    }

                    var updated = await client.ReplaceDocumentAsync(oDoc);

                    issue = (IncidentInfo)(dynamic)updated.Resource;
                }

                return(issue);
            }
            else
            {
                return(null);
            }
        }
 /// <summary>
 /// Update the incident status.
 /// </summary>
 /// <param name="status">The incident status.</param>
 public void UpdateIncidentStatus(IncidentStatus status)
 {
     this.IncidentStatus = status;
 }
예제 #32
0
        public async Task Run(string[] args)
        {
            while (true)
            {
                PrintMenu();

                Console.Write("Option: ");
                var option = Console.ReadLine();

                var valid = int.TryParse(option, out var index);
                valid = valid && index > 0 && index < 29;
                if (!valid)
                {
                    Console.WriteLine("Invalid option... please, press enter to continue...");
                    Console.ReadLine();
                    continue;
                }

                var response = "";
                var input    = "";
                try
                {
                    switch (index)
                    {
                    case 1:
                    {
                        Console.WriteLine("Enter Alert rule name");
                        input    = Console.ReadLine();
                        response = await _actionsController.CreateAction(input);

                        break;
                    }

                    case 2:
                    {
                        Console.WriteLine("Enter Alert rule name");
                        input    = Console.ReadLine();
                        response = await _actionsController.DeleteAction(input);

                        break;
                    }

                    case 3:
                    {
                        Console.WriteLine("Enter Alert rule name");
                        input    = Console.ReadLine();
                        response = await _actionsController.GetActionById(input);

                        break;
                    }

                    case 4:
                    {
                        Console.WriteLine("Enter Alert rule name");
                        input    = Console.ReadLine();
                        response = await _actionsController.GetActionsByRule(input);

                        break;
                    }

                    case 5:
                    {
                        Console.WriteLine("Enter template name");
                        input    = Console.ReadLine();
                        response = await _alertRuleTemplatesController.GetAlertRuleTemplateById(input);

                        break;
                    }

                    case 6:
                    {
                        response = await _alertRuleTemplatesController.GetAlertRuleTemplates();

                        break;
                    }

                    case 7:
                    {
                        Console.WriteLine("Enter alert rule template name");
                        input    = Console.ReadLine();
                        response = await _alertRulesController.CreateFusionAlertRule(input);

                        break;
                    }

                    case 8:
                    {
                        Console.WriteLine("Enter rule name");
                        input    = Console.ReadLine();
                        response = await _alertRulesController.CreateMicrosoftSecurityIncidentCreationAlertRule(input);

                        break;
                    }

                    case 9:
                    {
                        response = await _alertRulesController.CreateScheduledAlertRule();

                        break;
                    }

                    case 10:
                    {
                        response = await _alertRulesController.DeleteAlertRule();

                        break;
                    }

                    case 11:
                    {
                        response = await _alertRulesController.GetAlertRules();

                        break;
                    }

                    case 12:
                    {
                        response = await _alertRulesController.GetFusionAlertRule();

                        break;
                    }

                    case 13:
                    {
                        response = await _alertRulesController.GetMicrosoftSecurityIdentityCreationAlertRule();

                        break;
                    }

                    case 14:
                    {
                        response = await _alertRulesController.GetScheduledAlertRule();

                        break;
                    }

                    case 15:
                    {
                        response = await _bookmarksController.CreateBookmark();

                        break;
                    }

                    case 16:
                    {
                        response = await _bookmarksController.DeleteBookmark();

                        break;
                    }

                    case 17:
                    {
                        response = await _bookmarksController.GetBookmarkById();

                        break;
                    }

                    case 18:
                    {
                        response = await _bookmarksController.GetBookmarks();

                        break;
                    }

                    case 19:
                    {
                        response = await _dataConnectorsController.GetDataConnectors();

                        break;
                    }

                    case 20:
                    {
                        response = await _dataConnectorsController.DeleteDataConnector();

                        break;
                    }

                    case 21:
                    {
                        response = await _dataConnectorsController.CreateDataConnector();

                        break;
                    }

                    case 22:
                    {
                        Console.WriteLine("Enter Severity option \n 0 High \n 1 Medium \n 2 Low \n 3 Informational");
                        input = Console.ReadLine();
                        Severity severity = (Severity)Convert.ToInt32(input);

                        Console.WriteLine("Enter Incident status \n 0 New \n 1 Active \n 2 Close");
                        input = Console.ReadLine();
                        IncidentStatus status = (IncidentStatus)Convert.ToInt32(input);

                        Console.WriteLine("Enter Incident name");
                        var title = Console.ReadLine();

                        var payload = new IncidentPayload
                        {
                            PropertiesPayload = new IncidentPropertiesPayload
                            {
                                Severity = severity,
                                Status   = status,
                                Title    = title
                            }
                        };

                        response = await _incidentsController.CreateIncident(payload, title);

                        break;
                    }

                    case 23:
                    {
                        response = await _incidentsController.DeleteIncident();

                        break;
                    }

                    case 24:
                    {
                        response = await _incidentsController.GetIncidentById();

                        break;
                    }

                    case 25:
                    {
                        response = await _incidentsController.GetIncidents();

                        break;
                    }

                    case 26:
                    {
                        response = await _incidentsController.CreateIncidentComment();

                        break;
                    }

                    case 27:
                    {
                        response = await _incidentsController.GetAllIncidentComments();

                        break;
                    }

                    case 28:
                    {
                        response = await _incidentsController.GetIncidentCommentById();

                        break;
                    }
                    }

                    Console.WriteLine(JToken.Parse(response).ToString(Formatting.Indented));
                }
                catch (JsonReaderException exception)
                {
                    if (string.IsNullOrEmpty(response))
                    {
                        Console.WriteLine("Deleted");
                        Console.WriteLine("Enter to continue");
                        Console.ReadLine();
                        continue;
                    }

                    Console.WriteLine(response);
                }

                catch (Exception exception)
                {
                    var currentColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    await Console.Error.WriteLineAsync(exception.Message);

                    Console.ForegroundColor = currentColor;
                }

                Console.WriteLine();
                Console.WriteLine("Enter to continue");
                Console.ReadLine();
            }
        }
        public static void EnsureSeedData(this ApplicationDbContext context, IHostingEnvironment env)
        {
            var adminRole = new IdentityRole <int> {
                Name = "Admin"
            };
            var citizenRole = new IdentityRole <int> {
                Name = "Citizen"
            };

            context.Roles.Add(adminRole);
            context.Roles.Add(citizenRole);
            context.SaveChanges();

            var roman = new ApplicationUser
            {
                ConcurrencyStamp     = "6b3b9b11-8f97-4dc2-bfa0-b80b40ae890d",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                PasswordHash         = "AQAAAAEAACcQAAAAEH8NJi0ZOAkATkqABxRdwrALqMd10IW35NNnRlvVddLMC3eLb35Hu4v+KDMO0/M9gQ==",
                SecurityStamp        = "73a61f09-5ad8-4cd8-bc3a-7ad9d21eb0f3",
                AccessFailedCount    = 0,
                EmailConfirmed       = true,
                LockoutEnabled       = true,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled     = false,
                PhoneNumber          = "0953393611",
            };

            var yurii = new ApplicationUser
            {
                ConcurrencyStamp     = "6b3b9b11-8f97-4dc2-bfa0-b80b40ae890d",
                Email                = "*****@*****.**",
                NormalizedEmail      = "*****@*****.**",
                UserName             = "******",
                NormalizedUserName   = "******",
                PasswordHash         = "AQAAAAEAACcQAAAAEH8NJi0ZOAkATkqABxRdwrALqMd10IW35NNnRlvVddLMC3eLb35Hu4v+KDMO0/M9gQ==",
                SecurityStamp        = "73a61f09-5ad8-4cd8-bc3a-7ad9d21eb0f3",
                AccessFailedCount    = 0,
                EmailConfirmed       = true,
                LockoutEnabled       = true,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled     = false,
                PhoneNumber          = "0953393612"
            };

            context.Users.Add(roman);
            context.Users.Add(yurii);
            context.SaveChanges();

            var romanAdminRole = new IdentityUserRole <int>()
            {
                RoleId = adminRole.Id, UserId = roman.Id
            };
            var yuriiCitizenRole = new IdentityUserRole <int>()
            {
                RoleId = citizenRole.Id, UserId = yurii.Id
            };


            var @new = new IncidentStatus {
                Name = "New"
            };
            var progress = new IncidentStatus {
                Name = "In Progress"
            };
            var closed = new IncidentStatus {
                Name = "Closed"
            };


            context.IncidentStatuses.Add(@new);
            context.IncidentStatuses.Add(progress);
            context.IncidentStatuses.Add(closed);

            context.SaveChanges();


            var _priorities = new List <Priority> {
                new Priority {
                    Name = "Zero"
                },
                new Priority {
                    Name = "Low"
                },
                new Priority {
                    Name = "Medium"
                },
                new Priority {
                    Name = "High"
                },
            };

            foreach (var pr in _priorities)
            {
                context.Priorities.Add(pr);
            }

            context.SaveChanges();


            var incidents = new List <Incident>
            {
                new Incident
                {
                    Title            = "Упало дерево",
                    Description      = "Затрудняє рух громадського транспорту",
                    IncidentStatusId = @new.Id,
                    Latitude         = 48.462592,
                    Longitude        = 35.049769,
                    UserId           = yurii.Id,
                    Adress           = "проспект Дмитра Яворницького, 42-44, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = true,
                    //FilePath="/images/incidents/tree.png",
                    PriorityId    = _priorities[0].Id,
                    DateOfApprove = DateTime.Now,
                    Estimate      = 3
                },
                new Incident
                {
                    Title            = "Прорвана труба",
                    Description      = "Прохід громадян неможливий",
                    IncidentStatusId = progress.Id,
                    Latitude         = 48.466126,
                    Longitude        = 35.049526,
                    UserId           = yurii.Id,
                    Adress           = "вулиця Глінки, 11, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = true,
                    //FilePath="/images/incidents/water.png",
                    PriorityId    = _priorities[1].Id,
                    DateOfApprove = DateTime.Now.AddDays(-1),
                    Estimate      = 15
                },
                new Incident
                {
                    Title            = "Прорвана труба3",
                    Description      = "Прохід громадян неможливий",
                    IncidentStatusId = progress.Id,
                    Latitude         = 48.466126,
                    Longitude        = 35.049526,
                    UserId           = yurii.Id,
                    Adress           = "вулиця Глінки, 11, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = true,
                    //FilePath="/images/incidents/water.png",
                    PriorityId    = _priorities[1].Id,
                    DateOfApprove = DateTime.Now.AddDays(-1),
                    Estimate      = 15
                },
                new Incident
                {
                    Title            = "Прорвана труба2",
                    Description      = "Прохід громадян неможливий",
                    IncidentStatusId = progress.Id,
                    Latitude         = 48.466126,
                    Longitude        = 35.049526,
                    UserId           = yurii.Id,
                    Adress           = "вулиця Глінки, 11, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = true,
                    //FilePath="/images/incidents/water.png",
                    PriorityId    = _priorities[1].Id,
                    DateOfApprove = DateTime.Now.AddDays(-1),
                    Estimate      = 15
                },
                new Incident
                {
                    Title            = "ДТП",
                    Description      = "Тролебус виїхав на обочину",
                    IncidentStatusId = @new.Id,
                    Latitude         = 48.469868,
                    Longitude        = 35.054096,
                    UserId           = yurii.Id,
                    Adress           = "вулиця Січеславська Набережна, 35А, Дніпро́, Дніпропетровська область, Украина, 49000",
                    Approved         = true,
                    //FilePath="/images/incidents/dtp.png",
                    PriorityId    = _priorities[2].Id,
                    DateOfApprove = DateTime.Now.AddDays(-2),
                    Estimate      = 4
                },
                new Incident
                {
                    Title            = "ДТП",
                    Description      = "Тролебус виїхав на обочину",
                    IncidentStatusId = @new.Id,
                    Latitude         = 48.469868,
                    Longitude        = 35.054096,
                    UserId           = yurii.Id,
                    Adress           = "вулиця Січеславська Набережна, 35А, Дніпро́, Дніпропетровська область, Украина, 49000",
                    Approved         = true,
                    //FilePath="/images/incidents/dtp.png",
                    PriorityId    = _priorities[2].Id,
                    DateOfApprove = DateTime.Now.AddDays(-2),
                    Estimate      = 4
                },
                new Incident
                {
                    Title            = "Воронка в дорожньому полотні2",
                    Description      = "Прорив водної магістралі. Машина провалилась.",
                    IncidentStatusId = @new.Id,
                    Latitude         = 48.467271,
                    Longitude        = 35.040321,
                    UserId           = yurii.Id,
                    Adress           = "проспект Дмитра Яворницького, 75-77, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = false,
                    //FilePath="/images/incidents/hole.png",
                    PriorityId    = _priorities[0].Id,
                    DateOfApprove = DateTime.Now,
                    Estimate      = 10
                },
                new Incident
                {
                    Title            = "Пошкоджена лінія електропередач",
                    Description      = "Кабель висить над тротуарною доріжкою",
                    IncidentStatusId = closed.Id,
                    Latitude         = 48.467271,
                    Longitude        = 35.040321,
                    UserId           = yurii.Id,
                    Adress           = "проспект Дмитра Яворницького, 75-77, Дніпро́, Дніпропетровська область, Украина",
                    Approved         = true,
                    //FilePath="/images/incidents/electricity.png",
                    PriorityId    = _priorities[3].Id,
                    DateOfApprove = DateTime.Now,
                    Estimate      = 16
                }
            };

            foreach (Incident incident in incidents)
            {
                context.Incidents.Add(incident);
            }
            context.SaveChanges();
        }
        internal static string IncidentStatusToString(IncidentStatus incidentStatus)
        {
            if (incidentStatus == IncidentStatus.Going)
                return "Going";
            if (incidentStatus == IncidentStatus.Safe)
                return "Safe";
            if (incidentStatus == IncidentStatus.Controlled)
                return "Controlled";
            if (incidentStatus == IncidentStatus.Contained)
                return "Contained";
            if (incidentStatus == IncidentStatus.Completed)
                return "Completed";

            return "Unknown";
        }
예제 #35
0
 public bool ChangeIncidentStatus(int IncidentId, IncidentStatus status)
 {
     return(false);
 }