Exemplo n.º 1
0
    protected void btnGetIncidents_Click(object sender, EventArgs e)
    {
        lstIncidents.Items.Clear();
        myView = (DataView)dsIncidents.Select(DataSourceSelectArguments.Empty);
        myView.RowFilter = "CustomerID='" + txtCustomerID.Text + "' AND  DateClosed IS NOT NULL";

        lstIncidents.Items.Add("--Select an incident--");
        lstIncidents.Items[0].Value = "None";

        if (myView.Count == 0)
        {
            Deny();
            lstIncidents.Items.Clear();
            lstIncidents.Items.Add("There are no incidents linked to this account");
        }

        else
        {
            custid = Convert.ToInt32(txtCustomerID.Text);
            int i = 1;
            foreach (DataRowView v in myView)
            {
                DataRowView rowResult = v;
                inc = new Incident(rowResult);
                lstIncidents.Items.Add(inc.CustomerIncidentDisplay());
                lstIncidents.Items[i].Value = Convert.ToString(inc.IncidentID);
                i++;
            }
            lstIncidents.Focus();
            Allow();
        }
    }
Exemplo n.º 2
0
        /// <summary>
        /// Adds an incident to the Incidents database using a DB connection and Validating the information.
        /// </summary>
        /// <param name="incident"></param>
        /// <returns></returns>
        public static int AddIncident(Incident incident)
        {
            SqlConnection connection = TechSupportDBConnection.GetConnection();
            string insertStatement = "INSERT Incidents " +
                "(CustomerID, ProductCode, DateOpened, Title, Description) " +
                "VALUES (@CustomerID, @ProductCode, @DateOpened, @Title, @Description)";

            SqlCommand insertCommand = new SqlCommand(insertStatement, connection);
            insertCommand.Parameters.AddWithValue("@CustomerID", incident.CustomerID);
            insertCommand.Parameters.AddWithValue("@ProductCode", incident.ProductCode);
            insertCommand.Parameters.AddWithValue("@DateOpened", DateTime.Now);
            insertCommand.Parameters.AddWithValue("@Title", incident.Title);
            insertCommand.Parameters.AddWithValue("@Description", incident.Description);

            try
            {
                connection.Open();
                insertCommand.ExecuteNonQuery();
                string selectStatement = "SELECT IDENT_CURRENT('Incidents') FROM Incidents";
                SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
                int incidentID = Convert.ToInt32(selectCommand.ExecuteScalar());
                return incidentID;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }
        }
        protected override void MockServiceProviders()
        {
            base.MockServiceProviders();

            m_incident = new Incident
            {
                Id = Guid.NewGuid()
            };
            ExecutorContextMock.Setup(x => x.GetTargetEntity<Incident>()).Returns(m_incident);
        }
        public void Execute_ShouldCallGetPreEntityImageOfPluginContext_WhenCustomerIdOfTargetEntityIsNotSpecified()
        {
            var incident = new Incident
            {
                Id = Guid.NewGuid(), CustomerId = new CrmEntityReference("", TEST_ID)
            };
            ExecutorContextMock.Setup(x => x.GetPreEntityImage<Incident>()).Returns(incident);

            BusinessAgent.Execute(ExecutorContextMock.Object);

            ExecutorContextMock.Verify(x => x.GetPreEntityImage<Incident>(), Times.Once);
        }
Exemplo n.º 5
0
        public void Sys_IncidentCreation_ShouldValidateResponsibleContact_WhenResponsibleContactIsDefined()
        {
            var invalidIncident = new Incident
            {
                Id = m_incidentId,
                Title = IncidentTitle,
                CustomerId = new CrmEntityReference(Account.EntityLogicalName, AccountId),
                ResponsibleContactId = new CrmEntityReference(Contact.EntityLogicalName, Guid.NewGuid())
            };

            Assert.That(() => ServiceContext.Create(invalidIncident),
                                Throws.InstanceOf<Exception>().With.Message.EqualTo("Invalid Responsible Contact"));
        }
        protected override void InitializaMocks()
        {
            base.InitializaMocks();

            m_incident = new Incident
            {
                Id = Guid.NewGuid(),
                CustomerId = new CrmEntityReference("", Guid.NewGuid())
            };
            ExecutorContextMock.Setup(x => x.GetTargetEntity<Incident>()).Returns(m_incident);

            MockAccountQuery();
        }
Exemplo n.º 7
0
        public LogWrapper(Log log)
        {
            m_log = log;

            incident = new Incident();
            ID incId = new ID();
            incId.id = 0;
            incident.ID = incId;

            contact = new RightNowServiceReference.Contact();
            ID contactId = new ID();
            contactId.id = 0;
            contact.ID = contactId;
        }
Exemplo n.º 8
0
        public static void Add(ulong serverId, ulong channelId, string text)
        {
            var def = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"INCIDENT: {text}");
            Console.ForegroundColor = def;
            var incident = new Incident
            {
                ChannelId = (long)channelId,
                ServerId = (long)serverId,
                Text = text,
                Read = false
            };

            DbHandler.Instance.Connection.Insert(incident, typeof(Incident));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Closes the incident by setting the DateClosed DateTime to the current date
        /// </summary>
        /// <param name="theInc">The Incident to close</param>
        /// <returns></returns>
        public static bool CloseIncident(Incident theInc)
        {
            SqlConnection connection = TechSupportDBConnection.GetConnection();
            string updateStatement = "UPDATE Incidents SET " +
                "DateClosed = @NewDateClosed" +
                " WHERE IncidentID = " + theInc.IncidentID;
            SqlCommand updateCommand = new SqlCommand(updateStatement, connection);

            updateCommand.Parameters.AddWithValue("@NewDateClosed", DateTime.Now);

            try
            {
                connection.Open();
                int count = updateCommand.ExecuteNonQuery();
                if (count > 0)
                    return true;
                else return false;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (InvalidOperationException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                connection.Close();
            }
        }
Exemplo n.º 10
0
 public async Task UpdateAsync(Incident incident)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText =
             @"UPDATE Incidents SET 
                 ApplicationId = @ApplicationId,
                 UpdatedAtUtc = @UpdatedAtUtc,
                 Description = @Description,
                 Solution = @Solution,
                 SolvedAtUtc = @solvedAt,
                 IsSolutionShared = @IsSolutionShared,
                 AssignedToId = @AssignedTo,
                 AssignedAtUtc = @AssignedAtUtc,
                 State = @state,
                 IgnoringReportsSinceUtc = @IgnoringReportsSinceUtc,
                 IgnoringRequestedBy = @IgnoringRequestedBy,
                 IgnoredUntilVersion = @IgnoredUntilVersion
                 WHERE Id = @id";
         cmd.AddParameter("Id", incident.Id);
         cmd.AddParameter("ApplicationId", incident.ApplicationId);
         cmd.AddParameter("UpdatedAtUtc", incident.UpdatedAtUtc);
         cmd.AddParameter("Description", incident.Description);
         cmd.AddParameter("State", (int)incident.State);
         cmd.AddParameter("AssignedTo", incident.AssignedToId);
         cmd.AddParameter("AssignedAtUtc", (object)incident.AssignedAtUtc ?? DBNull.Value);
         cmd.AddParameter("solvedAt", incident.SolvedAtUtc.ToDbNullable());
         cmd.AddParameter("IgnoringReportsSinceUtc", incident.IgnoringReportsSinceUtc.ToDbNullable());
         cmd.AddParameter("IgnoringRequestedBy", incident.IgnoringRequestedBy);
         cmd.AddParameter("Solution",
                          incident.Solution == null ? null : EntitySerializer.Serialize(incident.Solution));
         cmd.AddParameter("IsSolutionShared", incident.IsSolutionShared);
         cmd.AddParameter("IgnoredUntilVersion", incident.IgnoredUntilVersion);
         await cmd.ExecuteNonQueryAsync();
     }
 }
Exemplo n.º 11
0
        public void TestCloseIncidentRequestFailsWhenStateOfStatusWrong()
        {
            var incident = new Incident();

            incident.Id = orgAdminUIService.Create(incident);

#if (XRM_MOCKUP_TEST_2011 || XRM_MOCKUP_TEST_2013)
            incident.SetState(orgAdminService, IncidentState.Active, Incident_StatusCode.InProgress);
#else
            incident.StateCode  = IncidentState.Active;
            incident.StatusCode = Incident_StatusCode.InProgress;
            orgAdminUIService.Update(incident);
#endif

            var incidentResolution = new IncidentResolution
            {
                IncidentId = incident.ToEntityReference(),
                Subject    = "Resolved Incident"
            };

            var request = new CloseIncidentRequest()
            {
                IncidentResolution = incidentResolution,
                Status             = new OptionSetValue((int)Incident_StatusCode.InProgress)
            };

            try
            {
                orgAdminUIService.Execute(request);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsInstanceOfType(e, typeof(FaultException));
            }
        }
Exemplo n.º 12
0
    public List<Incident> GetCustomerIncidents()
    {
        incidentList = new List<Incident>();//should clear the list
        int custID = Int32.Parse(tbEnterCustID.Text);
        //this line keeps throwing an exception due the database???
        DataView incidentTable = (DataView)dsCustIncidents.Select(DataSourceSelectArguments.Empty);
        incidentTable.RowFilter = string.Format("DateClosed is not NULL and CustomerID = {0}", Int32.Parse(tbEnterCustID.Text));

        //iterate through the rows of the DataView
        foreach (DataRowView row in incidentTable)
        {
            Incident rowIncident = new Incident();
            rowIncident.IncidentID = (int)row["IncidentID"];
            rowIncident.CustomerID = (int)row["CustomerID"];
            rowIncident.ProductCode = row["ProductCode"].ToString();
            rowIncident.TechID = (int)row["TechID"];
            rowIncident.DateOpened = (DateTime)row["DateOpened"];
            rowIncident.DateClosed = (DateTime)row["DateClosed"];
            rowIncident.Title = row["Title"].ToString();

            incidentList.Add(rowIncident);
        }
        return incidentList;
    }
Exemplo n.º 13
0
        public void TestCloseIncidentRequestFailsWhenLogicalNameWrong()
        {
            var incident = new Incident();

            incident.Id = orgAdminUIService.Create(incident);

#if (XRM_MOCKUP_TEST_2011 || XRM_MOCKUP_TEST_2013)
            incident.SetState(orgAdminService, IncidentState.Active, Incident_StatusCode.InProgress);
#else
            incident.StateCode  = IncidentState.Active;
            incident.StatusCode = Incident_StatusCode.InProgress;
            orgAdminUIService.Update(incident);
#endif

            var incidentResolution = new Account
            {
                Id = Guid.NewGuid()
            };
            incidentResolution.Attributes["incidentid"] = incident.ToEntityReference();

            var request = new CloseIncidentRequest()
            {
                IncidentResolution = incidentResolution,
                Status             = new OptionSetValue((int)Incident_StatusCode.ProblemSolved)
            };

            try
            {
                orgAdminUIService.Execute(request);
                Assert.Fail();
            }
            catch (Exception e)
            {
                Assert.IsInstanceOfType(e, typeof(FaultException));
            }
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,CaseNumber,DailyLogId,DailyLogNumber,OpenedDate,Occurred,Closed,PropertyId,Property,ReportTypeId,ReportSpecificId,Specific,SpecificId,CaseStatusId,LocationId,Location,SublocationId,Sublocation,DepartmentId,Department,Summary,Details,Resolution,Reference,SecondaryOperatorId,SecondaryOperator,Custodial,UseForce,Medical,RiskManagement,Active,Priority,AgentName,SupervisorName,ManagerName,DirectorName,AgentSignature,SupervisorSignature,ManagerSignature,DirectorSignature,AgentTime,SupervisorTime,ManagerTime,DirectorTime,CaseTypeId,InvestigatorId,ShiftId,ImmediateSupervisorId,GamingClassId,SurveillanceNotified,SurveillanceObserverId,InitialContact,InspectorSig,DeputyDirectorSig,DirectorSig,SupervisorSig,CompletionDate,TgaforwardDate,TgoreturnDate,Citation,ViolationNature,Variance,Employee,ManagerId,TapeIdentification,ActionTaken,SuspectPhoto,ExclusionInfo,Notification,PoliceContacted,PoliceContact,InvestigatorSigTs,SupervisorSigTs,DeputyDirectorSigTs,DirectorSigTs,Tgoresponse,CreatedBy,ClosedBy,ModifiedBy,ModifiedDate,DispatchCallId,AuditId,SavingsOrLosses,DirectorOnly,CaseType,Status,Agent,AgentSigFile,SupervisorSigFile,ManagerSigFile,DirectorSigFile,AgentImage,SupervisorImage,ManagerImage,DirectorImage,RemarksTitle1,RemarksMemos1,RemarksTitle2,RemarksMemos2,RemarksTitle3,RemarksMemos3,RemarksTitle4,RemarksMemos4,RemarksTitle5,RemarksMemos5")] Incident incident)
        {
            if (id != incident.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(incident);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!IncidentExists(incident.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CaseStatusId"]     = new SelectList(_context.CaseStatuses, "Id", "Id", incident.CaseStatusId);
            ViewData["DepartmentId"]     = new SelectList(_context.Departments, "Id", "Id", incident.DepartmentId);
            ViewData["LocationId"]       = new SelectList(_context.Locations, "Id", "Id", incident.LocationId);
            ViewData["PropertyId"]       = new SelectList(_context.Properties, "Id", "Id", incident.PropertyId);
            ViewData["ReportSpecificId"] = new SelectList(_context.ReportSpecifics, "Id", "Id", incident.ReportSpecificId);
            ViewData["ReportTypeId"]     = new SelectList(_context.ReportTypes, "Id", "Id", incident.ReportTypeId);
            ViewData["SublocationId"]    = new SelectList(_context.Sublocations, "Id", "Id", incident.SublocationId);
            return(View(incident));
        }
Exemplo n.º 15
0
        protected override void Run(Prediction prediction)
        {
            List <PostGIS.Point> predictionPoints = new List <PostGIS.Point>();
            Area   predictionArea = prediction.PredictionArea;
            double areaMinX       = predictionArea.BoundingBox.MinX;
            double areaMaxX       = predictionArea.BoundingBox.MaxX;
            double areaMinY       = predictionArea.BoundingBox.MinY;
            double areaMaxY       = predictionArea.BoundingBox.MaxY;

            for (double x = areaMinX + prediction.PredictionPointSpacing / 2d; x <= areaMaxX; x += prediction.PredictionPointSpacing)  // place points in the middle of the square boxes that cover the region - we get display errors from pixel rounding if the points are exactly on the boundaries
            {
                for (double y = areaMinY + prediction.PredictionPointSpacing / 2d; y <= areaMaxY; y += prediction.PredictionPointSpacing)
                {
                    predictionPoints.Add(new PostGIS.Point(x, y, predictionArea.Shapefile.SRID));
                }
            }

            List <PostGIS.Point> incidentPoints = new List <PostGIS.Point>(Incident.Get(TrainingStart, TrainingEnd, predictionArea, IncidentTypes.ToArray()).Select(i => i.Location));

            predictionPoints.AddRange(incidentPoints);

            Console.Out.WriteLine("Filtering prediction points to prediction area");
            predictionPoints = predictionArea.Intersects(predictionPoints, prediction.PredictionPointSpacing / 2f).Select(i => predictionPoints[i]).ToList();

            NpgsqlConnection connection = DB.Connection.OpenConnection;

            try
            {
                Console.Out.WriteLine("Inserting points into prediction");
                Point.CreateTable(prediction, predictionArea.Shapefile.SRID);
                List <int> predictionPointIds = Point.Insert(connection, predictionPoints.Select(p => new Tuple <PostGIS.Point, string, DateTime>(p, PointPrediction.NullLabel, DateTime.MinValue)), prediction, predictionArea, false);

                Console.Out.WriteLine("Running overall KDE for " + IncidentTypes.Count + " incident type(s)");
                List <float>            density = GetDensityEstimate(incidentPoints, _trainingSampleSize, false, 0, 0, predictionPoints, _normalize);
                Dictionary <int, float> pointIdOverallDensity = new Dictionary <int, float>(predictionPointIds.Count);
                int pointNum = 0;
                foreach (int predictionPointId in predictionPointIds)
                {
                    pointIdOverallDensity.Add(predictionPointId, density[pointNum++]);
                }

                Dictionary <int, Dictionary <string, double> > pointIdIncidentDensity = new Dictionary <int, Dictionary <string, double> >(pointIdOverallDensity.Count);
                if (IncidentTypes.Count == 1)
                {
                    string incident = IncidentTypes.First();
                    foreach (int pointId in pointIdOverallDensity.Keys)
                    {
                        Dictionary <string, double> incidentDensity = new Dictionary <string, double>();
                        incidentDensity.Add(incident, pointIdOverallDensity[pointId]);
                        pointIdIncidentDensity.Add(pointId, incidentDensity);
                    }
                }
                else
                {
                    foreach (string incidentType in IncidentTypes)
                    {
                        Console.Out.WriteLine("Running KDE for incident \"" + incidentType + "\"");
                        incidentPoints = new List <PostGIS.Point>(Incident.Get(TrainingStart, TrainingEnd, predictionArea, incidentType).Select(i => i.Location));
                        density        = GetDensityEstimate(incidentPoints, _trainingSampleSize, false, 0, 0, predictionPoints, _normalize);
                        if (density.Count > 0)
                        {
                            pointNum = 0;
                            foreach (int predictionPointId in predictionPointIds)
                            {
                                pointIdIncidentDensity.EnsureContainsKey(predictionPointId, typeof(Dictionary <string, double>));
                                pointIdIncidentDensity[predictionPointId].Add(incidentType, density[pointNum++]);
                            }
                        }
                    }
                }

                PointPrediction.CreateTable(prediction);
                PointPrediction.Insert(GetPointPredictionValues(pointIdOverallDensity, pointIdIncidentDensity), prediction, false);

                Smooth(prediction);
            }
            finally
            {
                DB.Connection.Return(connection);
            }
        }
Exemplo n.º 16
0
    /// <summary>
    /// Creates a new Incident report object (using the form fields) and returns that report.
    /// Does not save the report into the database.
    /// Returns the new Incident report on success, null on failure.
    /// </summary>
    /// <returns>the newly created Incident report</returns>
    private Incident createReport()
    {
        // Check page
        Page.Validate("vgpEmpName");
        Page.Validate("vgpPanelA");
        Page.Validate("vgpFCorrective");
        Page.Validate("vgpGRelevant");
        Page.Validate("vgpHManagers");
        if (!Page.IsValid)
        {
            PopUpErrorMsg = "Invalid input.";
            return null;
        }

        Employee emp = getEmployee(tbxFirstName.Text, tbxLastName.Text);
        if (emp == null)
        {
            PopUpErrorMsg = "Unable to find employee. Try clicking the 'Get Employee' button.";
            return null;
        }

        loadEmployee(emp);

        // Create the report
        Incident report = new Incident
        {

            #region A_IncidentInfo
            empNo = emp.empNo,
            p1_incidentDesc = convertTextBox(tbx_p1_incidentDesc),
            p1_witnessName1 = convertTextBox(tbx_p1_witnessName1),
            p1_witnessPhone1 = convertTextBox(tbx_p1_witnessPhone1),
            p1_witnessName2 = convertTextBox(tbx_p1_witnessName2),
            p1_witnessPhone2 = convertTextBox(tbx_p1_witnessPhone2),
            p1_action_report = convertCheckBox(cbx_p1_action_report),
            p1_action_firstAid = convertCheckBox(cbx_p1_action_firstAid),
            p1_action_medicalGP = convertCheckBox(cbx_p1_action_medicalGP),
            p1_action_lostTime = convertCheckBox(cbx_p1_action_lostTime),
            p1_action_medicalER = convertCheckBox(cbx_p1_action_medicalER),
            #endregion A_IncidentInfo

            #region B_NatureOfInjury
            p1_nature_no = convertCheckBox(cbx_p1_nature_no),
            p1_nature_musculoskeletal = convertCheckBox(cbx_p1_nature_musculoskeletal),
            p1_nature_bruise = convertCheckBox(cbx_p1_nature_bruise),
            p1_nature_burn = convertCheckBox(cbx_p1_nature_burn),
            p1_nature_cut = convertCheckBox(cbx_p1_nature_cut),
            p1_nature_puncture = convertCheckBox(cbx_p1_nature_puncture),
            p1_nature_skinIrritation = convertCheckBox(cbx_p1_nature_skinIrritation),
            p1_nature_skinMucous = convertCheckBox(cbx_p1_nature_skinMucous),
            p1_nature_eye = convertCheckBox(cbx_p1_nature_eye),
            p1_nature_allergic = convertCheckBox(cbx_p1_nature_allergic),
            p1_nature_psychological = convertCheckBox(cbx_p1_nature_psychological),
            p1_nature_respiratory = convertCheckBox(cbx_p1_nature_respiratory),
            #endregion B_NatureOfInjury

            #region C_AccidentInvestigation
            p2_activity_no = convertCheckBox(cbx_p2_activity_no),
            p2_activity_repositioning = convertCheckBox(cbx_p2_activity_repositioning),
            p2_activity_transferring = convertCheckBox(cbx_p2_activity_transferring),
            p2_activity_assistedWalking = convertCheckBox(cbx_p2_activity_assistedWalking),
            p2_activity_assistedFloor = convertCheckBox(cbx_p2_activity_assistedFloor),
            p2_activity_fall = convertCheckBox(cbx_p2_activity_fall),
            p2_activity_holding = convertCheckBox(cbx_p2_activity_holding),
            p2_activity_toileting = convertCheckBox(cbx_p2_activity_toileting),

            p2_patient_ceilingLift = convertCheckBox(cbx_p2_patient_ceilingLift),
            p2_patient_sitStandLift = convertCheckBox(cbx_p2_patient_sitStandLift),
            p2_patient_floorLift = convertCheckBox(cbx_p2_patient_floorLift),
            p2_patient_manualLift = convertCheckBox(cbx_p2_patient_manualLift),
            p2_patient_otherSpecify = convertTextBox(tbx_p2_patient_otherSpecify),
            p2_patient_adequateAssist = convertRadioButtonList(rbl_p2_patient_adequateAssist),

            p2_activity_washing = convertCheckBox(cbx_p2_activity_washing),
            p2_activity_dressing = convertCheckBox(cbx_p2_activity_dressing),
            p2_activity_changing = convertCheckBox(cbx_p2_activity_changing),
            p2_activity_feeding = convertCheckBox(cbx_p2_activity_feeding),
            p2_activity_prep = convertCheckBox(cbx_p2_activity_prep),
            p2_activity_dressingChanges = convertCheckBox(cbx_p2_activity_dressingChanges),
            p2_activity_otherPatientCare = convertTextBox(tbx_p2_activity_otherPatientCare),

            p2_activity_recapping = convertCheckBox(cbx_p2_activity_recapping),
            p2_activity_puncture = convertCheckBox(cbx_p2_activity_puncture),
            p2_activity_sharpsDisposal = convertCheckBox(cbx_p2_activity_sharpsDisposal),
            p2_activity_otherSharps = convertCheckBox(cbx_p2_activity_otherSharps),

            p2_activity_material = convertTextBox(tbx_p2_activity_material),
            p2_activity_lift = convertCheckBox(cbx_p2_activity_lift),
            p2_activity_push = convertCheckBox(cbx_p2_activity_push),
            p2_activity_carry = convertCheckBox(cbx_p2_activity_carry),
            p2_activity_otherMat = convertTextBox(tbx_p2_activity_otherMat),
            p2_activity_driving = convertCheckBox(cbx_p2_activity_driving),
            p2_activity_otherEquip = convertTextBox(tbx_p2_activity_otherEquip),
            p2_activity_otherEquipDesc = convertTextBox(tbx_p2_activity_otherEquipDesc),
            p2_activity_equipMain = convertCheckBox(cbx_p2_activity_equipMain),
            p2_activity_comp = convertCheckBox(cbx_p2_activity_comp),
            p2_activity_nonComp = convertCheckBox(cbx_p2_activity_nonComp),

            p2_activity_walking = convertCheckBox(cbx_p2_activity_walking),
            p2_activity_bending = convertCheckBox(cbx_p2_activity_bending),
            p2_activity_reading = convertCheckBox(cbx_p2_activity_reading),
            p2_activity_spill = convertCheckBox(cbx_p2_activity_spill),
            p2_activity_cleaning = convertCheckBox(cbx_p2_activity_cleaning),
            p2_activity_other = convertTextBox(tbx_p2_activity_other),
            #endregion C_AccidentInvestigation

            #region D_Cause
            p2_cause_human = convertCheckBox(cbx_p2_cause_human),
            p2_cause_animal = convertCheckBox(cbx_p2_cause_animal),

            p2_cause_needle = convertCheckBox(cbx_p2_cause_needle),
            p2_cause_otherSharps = convertCheckBox(cbx_p2_cause_otherSharps),
            p2_cause_skin = convertCheckBox(cbx_p2_cause_skin),

            p2_cause_awkwardPosture = convertCheckBox(cbx_p2_cause_awkwardPosture),
            p2_cause_staticPosture = convertCheckBox(cbx_p2_cause_staticPosture),
            p2_cause_contactStress = convertCheckBox(cbx_p2_cause_contactStress),
            p2_cause_force = convertCheckBox(cbx_p2_cause_force),
            p2_cause_rep = convertCheckBox(cbx_p2_cause_rep),

            p2_cause_motor = convertCheckBox(cbx_p2_cause_motor),
            p2_cause_slip = convertCheckBox(cbx_p2_cause_slip),
            p2_cause_aggression = convertCheckBox(cbx_p2_cause_aggression),
            p2_cause_undetermined = convertCheckBox(cbx_p2_cause_undetermined),
            p2_cause_event = convertCheckBox(cbx_p2_cause_event),
            p2_cause_underEquip = convertCheckBox(cbx_p2_cause_underEquip),
            p2_cause_hit = convertCheckBox(cbx_p2_cause_hit),
            p2_cause_other = convertTextBox(tbx_p2_cause_other),

            p2_aggression_verbal = convertCheckBox(cbx_p2_cause_aggression_verbal),
            p2_aggression_biting = convertCheckBox(cbx_p2_cause_aggression_biting),
            p2_aggression_hitting = convertCheckBox(cbx_p2_cause_aggression_hitting),
            p2_aggression_squeezing = convertCheckBox(cbx_p2_cause_aggression_squeezing),
            p2_aggression_assault = convertCheckBox(cbx_p2_cause_aggression_assault),
            p2_aggression_patient = convertCheckBox(cbx_p2_cause_aggression_patient),
            p2_aggression_family = convertCheckBox(cbx_p2_cause_aggression_family),
            p2_aggression_public = convertCheckBox(cbx_p2_cause_aggression_public),
            p2_aggression_worker = convertCheckBox(cbx_p2_cause_aggression_worker),
            p2_aggression_other = convertTextBox(tbx_p2_cause_aggression_other),
            p2_cause_exposure_chemName = convertTextBox(tbx_p2_cause_exposure_chemName),
            p2_cause_chemInhalation = convertCheckBox(cbx_p2_cause_chemInhalation),
            p2_cause_chemIngest = convertCheckBox(cbx_p2_cause_chemIngest),
            p2_cause_chemContact = convertCheckBox(cbx_p2_cause_chemContact),
            p2_cause_latex = convertCheckBox(cbx_p2_cause_latex),
            p2_cause_dust = convertCheckBox(cbx_p2_cause_dust),
            p2_cause_disease = convertCheckBox(cbx_p2_cause_disease),
            p2_cause_temp = convertCheckBox(cbx_p2_cause_temp),
            p2_cause_noise = convertCheckBox(cbx_p2_cause_noise),
            p2_cause_radiation = convertCheckBox(cbx_p2_cause_radiation),
            p2_cause_elec = convertCheckBox(cbx_p2_cause_elec),
            p2_cause_air = convertCheckBox(cbx_p2_cause_air),
            #endregion D_Cause

            #region E_ContributingFactors
            p2_factors_malfunction = convertCheckBox(cbx_p2_factors_malfunction),
            p2_factors_improperUse = convertCheckBox(cbx_p2_factors_improperUse),
            p2_factors_signage = convertCheckBox(cbx_p2_factors_signage),
            p2_factors_notAvailable = convertCheckBox(cbx_p2_factors_notAvailable),
            p2_factors_poorDesign = convertCheckBox(cbx_p2_factors_poorDesign),
            p2_factors_otherEquip = convertTextBox(tbx_p2_factors_otherEquip),

            p2_factors_temp = convertCheckBox(cbx_p2_factors_temp),
            p2_factors_workplace = convertCheckBox(cbx_p2_factors_workplace),
            p2_factors_layout = convertCheckBox(cbx_p2_factors_layout),
            p2_factors_limitedWorkspace = convertCheckBox(cbx_p2_factors_limitedWorkspace),
            p2_factors_slippery = convertCheckBox(cbx_p2_factors_slippery),
            p2_factors_lighting = convertCheckBox(cbx_p2_factors_lighting),
            p2_factors_noise = convertCheckBox(cbx_p2_factors_noise),
            p2_factors_vent = convertCheckBox(cbx_p2_factors_vent),
            p2_factors_storage = convertCheckBox(cbx_p2_factors_storage),
            p2_factors_otherEnv = convertTextBox(tbx_p2_factors_otherEnv),

            p2_factors_assessment = convertCheckBox(cbx_p2_factors_assessment),
            p2_factors_procedure = convertCheckBox(cbx_p2_factors_procedure),
            p2_factors_appropriateEquip = convertCheckBox(cbx_p2_factors_appropriateEquip),
            p2_factors_conduct = convertCheckBox(cbx_p2_factors_conduct),
            p2_factors_extended = convertCheckBox(cbx_p2_factors_extended),
            p2_factors_comm = convertCheckBox(cbx_p2_factors_comm),
            p2_factors_unaccustomed = convertCheckBox(cbx_p2_factors_unaccustomed),
            p2_factors_otherWorkPractice = convertTextBox(tbx_p2_factors_otherWorkPractice),

            p2_factors_directions = convertCheckBox(cbx_p2_factors_directions),
            p2_factors_weight = convertCheckBox(cbx_p2_factors_weight),
            p2_factors_aggressive = convertCheckBox(cbx_p2_factors_aggressive),
            p2_factors_patientResistive = convertCheckBox(cbx_p2_factors_patientResistive),
            p2_factors_movement = convertCheckBox(cbx_p2_factors_movement),
            p2_factors_confused = convertCheckBox(cbx_p2_factors_confused),
            p2_factors_influence = convertCheckBox(cbx_p2_factors_influence),
            p2_factors_lang = convertCheckBox(cbx_p2_factors_lang),
            p2_factors_otherPatient = convertTextBox(tbx_p2_factors_otherPatient),

            p2_factors_alone = convertCheckBox(cbx_p2_factors_alone),
            p2_factors_info = convertCheckBox(cbx_p2_factors_info),
            p2_factors_scheduling = convertCheckBox(cbx_p2_factors_scheduling),
            p2_factors_training = convertCheckBox(cbx_p2_factors_training),
            p2_factors_equip = convertCheckBox(cbx_p2_factors_equip),
            p2_factors_personal = convertCheckBox(cbx_p2_factors_personal),
            p2_factors_safe = convertCheckBox(cbx_p2_factors_safe),
            p2_factors_perceived = convertCheckBox(cbx_p2_factors_perceived),
            p2_factors_otherOrganizational = convertTextBox(tbx_p2_factors_otherOrganizational),

            p2_factors_inexperienced = convertCheckBox(cbx_p2_factors_inexperienced),
            p2_factors_communication = convertCheckBox(cbx_p2_factors_communication),
            p2_factors_fatigued = convertCheckBox(cbx_p2_factors_fatigued),
            p2_factors_distracted = convertCheckBox(cbx_p2_factors_distracted),
            p2_factors_preexisting = convertCheckBox(cbx_p2_factors_preexisting),
            p2_factors_sick = convertCheckBox(cbx_p2_factors_sick),
            p2_factors_otherWorker = convertTextBox(tbx_p2_factors_otherWorker),
            #endregion E_ContributingFactors

            followUpStatus = "0",
            reportSubmitter = Session["AuthenticatedUser"].ToString(),

        };

        // Continue creating the report
        if ((Session["DeptNo"] == null) || Session["DeptNo"].Equals(String.Empty))
        {    // for admin account
            report.submitterDeptNo = null;
        }
        else
        {
            report.submitterDeptNo = Convert.ToInt32(Session["DeptNo"]);
        }

        #region Report Info Dates and Department
        #region Dates
        String strDateOfIncident = tbx_p1_dateOfIncident.Text;
        String strTimeOfIncident = tbx_p1_timeOfIncident.Text;
        String strDateReported = tbx_p1_dateReported.Text;
        String strTimeReported = tbx_p1_timeReported.Text;

        if (!(strDateOfIncident.Equals(String.Empty) && strTimeOfIncident.Equals(String.Empty)))
        {
            String timeFormat = getTimeFormat(strTimeOfIncident);
            if (timeFormat == null)
            {
                PopUpErrorMsg = "Time of incident is invalid.";
                return null; // Error
            }
            report.p1_dateOfIncident = DateTime.ParseExact(strDateOfIncident + " " + strTimeOfIncident,
                DateFormat + " " + timeFormat, Locale);
        }
        else
        {
            PopUpErrorMsg = "Date/time reported is required.";
            return null;
        }

        if (!(strDateReported.Equals(String.Empty) && strTimeReported.Equals(String.Empty)))
        {
            String timeFormat = getTimeFormat(strTimeReported);
            if (timeFormat == null)
            {
                PopUpErrorMsg = "Time reported is invalid.";
                return null; // Error
            }
            report.p1_dateReported = DateTime.ParseExact(strDateReported + " " + strTimeReported,
                DateFormat + " " + timeFormat, Locale);
        }
        else
        {
            PopUpErrorMsg = "Date/time of incident is required.";
            return null;
        }
        #endregion Dates

        #region Department
        if (ddlReportDepts.SelectedValue.Equals("Other"))
        {
            report.deptNo = null;
        }
        else
        {
            int deptNo = Convert.ToInt32(ddlReportDepts.SelectedValue);
            report.deptNo = deptNo;
        }
        #endregion Department
        #endregion Report Info Dates and Department

        #region A_IncidentInfo_Dates
        if (cbx_p1_action_medicalER.Checked) {
            if (!tbx_p1_action_medicalER_date.Text.Equals(String.Empty)) {
                DateTime dateMedicalER = DateTime.ParseExact(tbx_p1_action_medicalER_date.Text, DateFormat, Locale);
                report.p1_action_medicalER_date = dateMedicalER;
            }
        }

        if (cbx_p1_action_medicalGP.Checked) {
            if (!tbx_p1_action_medicalGP_date.Text.Equals(String.Empty)) {
                DateTime dateMedicalGP = DateTime.ParseExact(tbx_p1_action_medicalGP_date.Text, DateFormat, Locale);
                report.p1_action_medicalGP_date = dateMedicalGP;
            }
        }
        #endregion A_IncidentInfo_Dates

        #region C_AccidentInvestigation_PatientHandling
        if (!tbx_p1_numEmployeesInvolved.Text.Equals(String.Empty))
        {
            report.p1_numEmployeesInvolved = Convert.ToInt32(tbx_p1_numEmployeesInvolved.Text);
        }
        #endregion C_AccidentInvestigation_PatientHandling

        return report;
    }
Exemplo n.º 17
0
        /// <param name='incidentId'>
        /// The id of the incident to retrieve.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Incident operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.IncidentGetResponse> GetAsync(string incidentId, CancellationToken cancellationToken)
        {
            // Validate
            if (incidentId == null)
            {
                throw new ArgumentNullException("incidentId");
            }

            // Tracing
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("incidentId", incidentId);
                Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = new Uri(this.Client.BaseUri, "/").ToString() + this.Client.Credentials.SubscriptionId + "/services/monitoring/alertincidents/" + incidentId;

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2013-10-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        Tracing.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        Tracing.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    IncidentGetResponse result = null;
                    // Deserialize Response
                    cancellationToken.ThrowIfCancellationRequested();
                    string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    result = new IncidentGetResponse();
                    JToken responseDoc = JToken.Parse(responseContent);

                    if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                    {
                        Incident incidentInstance = new Incident();
                        result.Incident = incidentInstance;

                        JToken idValue = responseDoc["Id"];
                        if (idValue != null && idValue.Type != JTokenType.Null)
                        {
                            string idInstance = (string)idValue;
                            incidentInstance.Id = idInstance;
                        }

                        JToken ruleIdValue = responseDoc["RuleId"];
                        if (ruleIdValue != null && ruleIdValue.Type != JTokenType.Null)
                        {
                            string ruleIdInstance = (string)ruleIdValue;
                            incidentInstance.RuleId = ruleIdInstance;
                        }

                        JToken isActiveValue = responseDoc["IsActive"];
                        if (isActiveValue != null && isActiveValue.Type != JTokenType.Null)
                        {
                            bool isActiveInstance = (bool)isActiveValue;
                            incidentInstance.IsActive = isActiveInstance;
                        }

                        JToken activatedTimeValue = responseDoc["ActivatedTime"];
                        if (activatedTimeValue != null && activatedTimeValue.Type != JTokenType.Null)
                        {
                            DateTime activatedTimeInstance = (DateTime)activatedTimeValue;
                            incidentInstance.ActivatedTime = activatedTimeInstance;
                        }

                        JToken resolvedTimeValue = responseDoc["ResolvedTime"];
                        if (resolvedTimeValue != null && resolvedTimeValue.Type != JTokenType.Null)
                        {
                            DateTime resolvedTimeInstance = (DateTime)resolvedTimeValue;
                            incidentInstance.ResolvedTime = resolvedTimeInstance;
                        }
                    }

                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        Tracing.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// This method gets called by SS1, when an incident has been detected.
 /// It forwards the information to SS3 and SS4.
 /// </summary>
 /// <param name="e"></param>
 #region Request/Send
 public static void SendIncident(Incident e)
 {
     //SS3.CallReceiveIncident(e);
     //SS4.CallReceiveIncident(e);
 }
	/// 
	/// <param name="type"></param>
	/// <param name="riskDegree"></param>
	/// <param name="incidentID"></param>
	/// <param name="city"></param>
	/// <param name="dateTime"></param>
	/// <param name="description"></param>
	/// <param name="incidentLocation"></param>
	public void InsertIncidentData(Incident incident){

        Complainant.db.Store(incident);
    }
Exemplo n.º 20
0
 public IncidentViewModel(Incident incident)
 {
     Title    = "Incident Reporter";
     Incident = incident;
 }
Exemplo n.º 21
0
 public ActionResult Edit(Incident Incident)
 {
     _db.Entry(Incident).State = EntityState.Modified;
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Exemplo n.º 22
0
 public void NoticeLog(Incident incident = null, RightNowServiceReference.Contact contact = null, string LogMessage = null, string LogNote = null, string source = null, int timeElapsed = 0)
 {
 }
Exemplo n.º 23
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a customer for a new incident
            Contact caseCustomer = new Contact();

            // Set the contact properties
            caseCustomer.FirstName = "Christen";
            caseCustomer.LastName = "Anderson";

            // Create the contact in CRM
            _caseCustomerId = _serviceProxy.Create(caseCustomer);
            NotifyEntityCreated(Contact.EntityLogicalName, _caseCustomerId);

            // Retrieve the default subject for a new incident\case
            var query = new QueryExpression()
            {
                EntityName = Subject.EntityLogicalName,
                ColumnSet = new ColumnSet(allColumns: true),
                Criteria = new FilterExpression()
            };
            query.Criteria.AddCondition("title", ConditionOperator.Equal, 
                "Default Subject");

            var subjectRecords = _serviceProxy.RetrieveMultiple(query);
            Entity defaultSubject = subjectRecords[0];
            NotifyEntityRetrieved(Subject.EntityLogicalName, defaultSubject.Id);

            // Create a new incident
            Incident newCase = new Incident();

            // Set the incident properties
            newCase.SubjectId = new EntityReference();
            newCase.SubjectId.LogicalName = Subject.EntityLogicalName;
            newCase.SubjectId.Id = defaultSubject.Id;
            newCase.CustomerId = new EntityReference();
            newCase.CustomerId.LogicalName = Contact.EntityLogicalName;
            newCase.CustomerId.Id = _caseCustomerId;
            newCase.Title = "New Case from SDK";

            _caseIncidentId = _serviceProxy.Create(newCase);
            NotifyEntityCreated(Incident.EntityLogicalName, _caseIncidentId);

        }
Exemplo n.º 24
0
        public bool ExecuteAction(string action, Incident incident)
        {
            var result = true;

            if (!string.IsNullOrEmpty(action))
            {
                var methodInfo = GetType().GetMethod(action);

                var transitionAction = (Action)Delegate.CreateDelegate(typeof(Action), this, methodInfo);

                result = transitionAction.Invoke(incident);
            }

            return result;
        }
Exemplo n.º 25
0
    public InstantiatedIncident(Incident abstractIncident, List<Character> charactersById, List<ShipEquipment> shipEquipmentById)
    {
        this.abstractPrompt = abstractIncident.abstractPrompt;
        this.beliefs = abstractIncident.beliefs;
        this.controls = abstractIncident.controls;

        this.charactersByInternalId = charactersById;
        this.shipEquipmentById = shipEquipmentById;
    }
 public static Incident CreateIncident(long nodeId, string status, string priority, long completion, global::System.DateTimeOffset due, long ID, global::System.Guid tid, string name, long createdById, long modifiedById, global::System.DateTimeOffset created, global::System.DateTimeOffset modified)
 {
     Incident incident = new Incident();
     incident.NodeId = nodeId;
     incident.Status = status;
     incident.Priority = priority;
     incident.Completion = completion;
     incident.Due = due;
     incident.Id = ID;
     incident.Tid = tid;
     incident.Name = name;
     incident.CreatedById = createdById;
     incident.ModifiedById = modifiedById;
     incident.Created = created;
     incident.Modified = modified;
     return incident;
 }
Exemplo n.º 27
0
        public async Task <String> UpdatePayment(IncidentPaymentRequest paymentRequest)
        {
            Services.Log.Info("Incident Payment Update Request [API]");
            string responseText;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await(from r in context.Incidents where (r.Id == paymentRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                string guidnew = Guid.NewGuid().ToString();
                //Check for Submitted Payment Amount
                Payment newPayment = new Payment
                {
                    Id = guidnew,
                    PaymentPlatform   = paymentRequest.PaymentMethod,
                    PlatformPaymentID = guidnew,
                    Amount            = paymentRequest.PaymentAmount,
                    Fees               = -1,
                    ProviderUserID     = IncidentInfo.GetProviderID(paymentRequest.IncidentGUID),
                    Status             = "Admin-Entered",
                    BuyerName          = "NONE",
                    BuyerEmail         = "NONE",
                    BuyerPhone         = "NONE",
                    Currency           = "INR",
                    AuthenticationCode = "NONE",
                    IncidentGUID       = paymentRequest.IncidentGUID
                };

                if (paymentRequest.PaymentMethod == "PAYMENT-CASH")
                {
                    newPayment.PaymentPlatform = "Cash Payment (Admin)";
                    newPayment.Status          = "PAYMENT-CASH";
                }

                if (paymentRequest.PaymentMethod == "PAYMENT-FAIL")
                {
                    newPayment.PaymentPlatform = "Payment Failure (Admin)";
                    newPayment.Status          = "PAYMENT-FAIL";
                }

                if (paymentRequest.PaymentAmount == 0)
                {
                    newPayment.Amount = -1;
                }

                //Save record
                context.Payments.Add(newPayment);
                await context.SaveChangesAsync();

                responseText = "Incident [" + updateIncident.Id + "] Payment Status Updated";
                Services.Log.Info(responseText);

                //Notify Particular Connected User through SignalR
                IHubContext hubContext = Services.GetRealtime <IncidentHub>();
                hubContext.Clients.Group(updateIncident.ProviderUserID).updateMobileClientStatus(newPayment.GetCustomerPushObject());
                Services.Log.Info("Mobile Client [" + updateIncident.ProviderUserID + "] Status Update Payload Sent");

                //Web Client Notifications
                hubContext.Clients.All.saveNewPayment(newPayment);
                Services.Log.Info("Connected Clients Updated");

                //Return Successful Response
                return(responseText);
            }
            else
            {
                // Return Failed Response
                responseText = "Incident [" + paymentRequest.IncidentGUID + "] is not found in the system";
                Services.Log.Warn(responseText);
                return(responseText);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates any entity records that this sample requires.
        /// </summary>
        public void CreateRequiredRecords()
        {
            #region create kb articles

            Console.WriteLine("  Creating KB Articles");

            _subjectId = (
                          from subject in _context.SubjectSet
                          where subject.Title == "Default Subject"
                          select subject.Id
                         ).First();

            var kbArticleTemplateId = (               
                                       from articleTemplate in _context.KbArticleTemplateSet
                                       where articleTemplate.Title == "Standard KB Article"
                                       select articleTemplate.Id
                                      ).FirstOrDefault();

            if (kbArticleTemplateId != Guid.Empty)
            {
                // create a KB article
                _articles[0] = new KbArticle()
                {
                    // set the article properties
                    Title = "Searching the knowledge base",
                    ArticleXml = @"
                <articledata>
                    <section id='0'>
                        <content><![CDATA[This is a sample article about searching the knowledge base.]]></content>
                    </section>
                    <section id='1'>
                        <content><![CDATA[Knowledge bases contain information useful for various people.]]></content>
                    </section>
                </articledata>",
                    // use the built-in "Standard KB Article" template
                    KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName,
                        kbArticleTemplateId),
                    // use the default subject
                    SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId),
                    KeyWords = "Searching Knowledge base"
                };
                _context.AddObject(_articles[0]);

                _articles[1] = new KbArticle()
                {
                    Title = "What's in a knowledge base",
                    ArticleXml = @"
                            <articledata>
                                <section id='0'>
                                    <content><![CDATA[This is a sample article about what would be in a knowledge base.]]></content>
                                </section>
                                <section id='1'>
                                    <content><![CDATA[This section contains more information.]]></content>
                                </section>
                            </articledata>",
                    KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName,
                       kbArticleTemplateId),
                    SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId),
                    KeyWords = "Knowledge base"
                };
                _context.AddObject(_articles[1]);

                _articles[2] = new KbArticle()
                {
                    Title = "Searching the knowledge base from code",
                    ArticleXml = @"
                            <articledata>
                                <section id='0'>
                                    <content><![CDATA[This article covers searching the knowledge base from code.]]></content>
                                </section>
                                <section id='1'>
                                    <content><![CDATA[This section contains more information.]]></content>
                                </section>
                            </articledata>",
                    KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName,
                       kbArticleTemplateId),
                    SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId),
                    KeyWords = "Knowledge base code"
                };
                _context.AddObject(_articles[2]);
                _context.SaveChanges();
            }
            else
            {
                throw new ArgumentException("Standard Article Templates are missing");
            }
            #endregion

            #region Submit the articles

            Console.WriteLine("  Submitting the articles");

            foreach (var article in _articles)
            {
                _context.Execute(new SetStateRequest
                {
                    EntityMoniker = article.ToEntityReference(),
                    State = new OptionSetValue((int)KbArticleState.Unapproved),
                    Status = new OptionSetValue((int)kbarticle_statuscode.Unapproved)
                });
            }

            #endregion

            #region Approve and Publish the article

            Console.WriteLine("  Publishing articles");

            foreach (var article in _articles)
            {
                _context.Execute(new SetStateRequest
                {
                    EntityMoniker = article.ToEntityReference(),
                    State = new OptionSetValue((int)KbArticleState.Published),
                    Status = new OptionSetValue((int)kbarticle_statuscode.Published)
                });
            }

            #endregion

            #region Waiting for publishing to finish

            // Wait 20 seconds to ensure that data will be available
            // Full-text indexing
            Console.WriteLine("  Waiting 20 seconds to ensure indexing has completed on the new records.");
            System.Threading.Thread.Sleep(20000);
            Console.WriteLine();

            #endregion

            #region Add cases to KbArticles

            // Create UoM
            _uomSchedule = new UoMSchedule()
            {
                Name = "Sample unit group",
                BaseUoMName = "Sample base unit"
            };
            _context.AddObject(_uomSchedule);
            _context.SaveChanges();

            _uom = (from uom in _context.UoMSet
                    where uom.Name == _uomSchedule.BaseUoMName
                    select uom).First();

            Console.WriteLine("  Creating an account and incidents for the KB articles");
            var whoami = (WhoAmIResponse)_context.Execute(new WhoAmIRequest());

            _account = new Account()
            {
                Name = "Coho Winery",
            };
            _context.AddObject(_account);
            _context.SaveChanges();

            _product = new Product()
            {
                Name = "Sample Product",
                ProductNumber = "0",
                ProductStructure = new OptionSetValue(1),
                DefaultUoMScheduleId = _uomSchedule.ToEntityReference(),
                DefaultUoMId = _uom.ToEntityReference()
            };
            
            _context.AddObject(_product);
            _context.SaveChanges();

            // Publish Product
            SetStateRequest publishRequest = new SetStateRequest
            {
                EntityMoniker = new EntityReference(Product.EntityLogicalName, _product.Id),
                State = new OptionSetValue((int)ProductState.Active),
                Status = new OptionSetValue(1)
            };
            _context.Execute(publishRequest);

            _incident = new Incident()
            {
                Title = "A sample incident",
                OwnerId = new EntityReference(SystemUser.EntityLogicalName, whoami.UserId),
                KbArticleId = _articles[0].ToEntityReference(),
                CustomerId = _account.ToEntityReference(),
                SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId),
                ProductId = _product.ToEntityReference()
            };
            _context.AddObject(_incident);
            _context.SaveChanges();

            #endregion
        }
Exemplo n.º 29
0
 public async Task <int> UpdateAsync(Incident entity)
 {
     throw await Task.Run(() => new NotImplementedException());
 }
Exemplo n.º 30
0
    /// <summary>
    /// Creates a new Incident report object (using the form fields) and returns that report.
    /// Does not save the report into the database.
    /// Returns the new Incident report on success, null on failure.
    /// </summary>
    /// <returns>the newly created Incident report</returns>
    private Incident createReport()
    {
        getEmployeeData();
        int empId = Convert.ToInt32(tbxId.Text);

        DateTime dateOfIncident = Convert.ToDateTime(tbx_p1_dateOfIncident.Text + " " + tbx_p1_timeOfIncident.Text);
        DateTime dateReported = Convert.ToDateTime(tbx_p1_dateReported.Text + " " + tbx_p1_timeReported.Text);

        Incident report = new Incident
        {

            #region A_IncidentInfo
            empNo = empId,
            p1_dateOfIncident = dateOfIncident,
            p1_dateReported = dateReported,
            p1_incidentDesc = convertTextBox(tbx_p1_incidentDesc),
            p1_witnessName1 = convertTextBox(tbx_p1_witnessName1),
            p1_witnessPhone1 = convertTextBox(tbx_p1_witnessPhone1),
            p1_witnessName2 = convertTextBox(tbx_p1_witnessName2),
            p1_witnessPhone2 = convertTextBox(tbx_p1_witnessPhone2),
            p1_action_report = convertCheckBox(cbx_p1_action_report),
            p1_action_firstAid = convertCheckBox(cbx_p1_action_firstAid),
            p1_action_medicalGP = convertCheckBox(cbx_p1_action_medicalGP),
            p1_action_lostTime = convertCheckBox(cbx_p1_action_lostTime),
            p1_action_medicalER = convertCheckBox(cbx_p1_action_medicalER),
            #endregion A_IncidentInfo

            #region B_NatureOfInjury
            p1_nature_no = convertCheckBox(cbx_p1_nature_no),
            p1_nature_musculoskeletal = convertCheckBox(cbx_p1_nature_musculoskeletal),
            p1_nature_bruise = convertCheckBox(cbx_p1_nature_bruise),
            p1_nature_burn = convertCheckBox(cbx_p1_nature_burn),
            p1_nature_cut = convertCheckBox(cbx_p1_nature_cut),
            p1_nature_puncture = convertCheckBox(cbx_p1_nature_puncture),
            p1_nature_skinIrritation = convertCheckBox(cbx_p1_nature_skinIrritation),
            p1_nature_skinMucous = convertCheckBox(cbx_p1_nature_skinMucous),
            p1_nature_eye = convertCheckBox(cbx_p1_nature_eye),
            p1_nature_allergic = convertCheckBox(cbx_p1_nature_allergic),
            p1_nature_psychological = convertCheckBox(cbx_p1_nature_psychological),
            p1_nature_respiratory = convertCheckBox(cbx_p1_nature_respiratory),
            #endregion B_NatureOfInjury

            #region C_AccidentInvestigation
            p2_activity_no = convertCheckBox(cbx_p2_activity_no),
            p2_activity_repositioning = convertCheckBox(cbx_p2_activity_repositioning),
            p2_activity_transferring = convertCheckBox(cbx_p2_activity_transferring),
            p2_activity_assistedWalking = convertCheckBox(cbx_p2_activity_assistedWalking),
            p2_activity_assistedFloor = convertCheckBox(cbx_p2_activity_assistedFloor),
            p2_activity_fall = convertCheckBox(cbx_p2_activity_fall),
            p2_activity_holding = convertCheckBox(cbx_p2_activity_holding),
            p2_activity_toileting = convertCheckBox(cbx_p2_activity_toileting),

            p2_patient_ceilingLift = convertCheckBox(cbx_p2_patient_ceilingLift),
            p2_patient_sitStandLift = convertCheckBox(cbx_p2_patient_sitStandLift),
            p2_patient_floorLift = convertCheckBox(cbx_p2_patient_floorLift),
            p2_patient_manualLift = convertCheckBox(cbx_p2_patient_manualLift),
            p2_patient_otherSpecify = convertTextBox(tbx_p2_patient_otherSpecify),
            p2_patient_adequateAssist = convertRadioButtonList(rbl_p2_patient_adequateAssist),

            p2_activity_washing = convertCheckBox(cbx_p2_activity_washing),
            p2_activity_dressing = convertCheckBox(cbx_p2_activity_dressing),
            p2_activity_changing = convertCheckBox(cbx_p2_activity_changing),
            p2_activity_feeding = convertCheckBox(cbx_p2_activity_feeding),
            p2_activity_prep = convertCheckBox(cbx_p2_activity_prep),
            p2_activity_dressingChanges = convertCheckBox(cbx_p2_activity_dressingChanges),
            p2_activity_otherPatientCare = convertTextBox(tbx_p2_activity_otherPatientCare),

            p2_activity_recapping = convertCheckBox(cbx_p2_activity_recapping),
            p2_activity_puncture = convertCheckBox(cbx_p2_activity_puncture),
            p2_activity_sharpsDisposal = convertCheckBox(cbx_p2_activity_sharpsDisposal),
            p2_activity_otherSharps = convertCheckBox(cbx_p2_activity_otherSharps),

            p2_activity_material = convertTextBox(tbx_p2_activity_material),
            p2_activity_lift = convertCheckBox(cbx_p2_activity_lift),
            p2_activity_push = convertCheckBox(cbx_p2_activity_push),
            p2_activity_carry = convertCheckBox(cbx_p2_activity_carry),
            p2_activity_otherMat = convertTextBox(tbx_p2_activity_otherMat),
            p2_activity_driving = convertCheckBox(cbx_p2_activity_driving),
            p2_activity_otherEquip = convertTextBox(tbx_p2_activity_otherEquip),
            p2_activity_otherEquipDesc = convertTextBox(tbx_p2_activity_otherEquipDesc),
            p2_activity_equipMain = convertCheckBox(cbx_p2_activity_equipMain),
            p2_activity_comp = convertCheckBox(cbx_p2_activity_comp),
            p2_activity_nonComp = convertCheckBox(cbx_p2_activity_nonComp),

            p2_activity_walking = convertCheckBox(cbx_p2_activity_walking),
            p2_activity_bending = convertCheckBox(cbx_p2_activity_bending),
            p2_activity_reading = convertCheckBox(cbx_p2_activity_reading),
            p2_activity_spill = convertCheckBox(cbx_p2_activity_spill),
            p2_activity_cleaning = convertCheckBox(cbx_p2_activity_cleaning),
            p2_activity_other = convertTextBox(tbx_p2_activity_other),
            #endregion C_AccidentInvestigation

            #region D_Cause
            p2_cause_human = convertCheckBox(cbx_p2_cause_human),
            p2_cause_animal = convertCheckBox(cbx_p2_cause_animal),

            p2_cause_needle = convertCheckBox(cbx_p2_cause_needle),
            p2_cause_otherSharps = convertCheckBox(cbx_p2_cause_otherSharps),
            p2_cause_skin = convertCheckBox(cbx_p2_cause_skin),

            p2_cause_awkwardPosture = convertCheckBox(cbx_p2_cause_awkwardPosture),
            p2_cause_staticPosture = convertCheckBox(cbx_p2_cause_staticPosture),
            p2_cause_contactStress = convertCheckBox(cbx_p2_cause_contactStress),
            p2_cause_force = convertCheckBox(cbx_p2_cause_force),
            p2_cause_rep = convertCheckBox(cbx_p2_cause_rep),

            p2_cause_motor = convertCheckBox(cbx_p2_cause_motor),
            p2_cause_slip = convertCheckBox(cbx_p2_cause_slip),
            p2_cause_aggression = convertCheckBox(cbx_p2_cause_aggression),
            p2_cause_undetermined = convertCheckBox(cbx_p2_cause_undetermined),
            p2_cause_event = convertCheckBox(cbx_p2_cause_event),
            p2_cause_underEquip = convertCheckBox(cbx_p2_cause_underEquip),
            p2_cause_hit = convertCheckBox(cbx_p2_cause_hit),
            p2_cause_other = convertTextBox(tbx_p2_cause_other),

            p2_aggression_verbal = convertCheckBox(cbx_p2_cause_aggression_verbal),
            p2_aggression_biting = convertCheckBox(cbx_p2_cause_aggression_biting),
            p2_aggression_hitting = convertCheckBox(cbx_p2_cause_aggression_hitting),
            p2_aggression_squeezing = convertCheckBox(cbx_p2_cause_aggression_squeezing),
            p2_aggression_assault = convertCheckBox(cbx_p2_cause_aggression_assault),
            p2_aggression_patient = convertCheckBox(cbx_p2_cause_aggression_patient),
            p2_aggression_family = convertCheckBox(cbx_p2_cause_aggression_family),
            p2_aggression_public = convertCheckBox(cbx_p2_cause_aggression_public),
            p2_aggression_worker = convertCheckBox(cbx_p2_cause_aggression_worker),
            p2_aggression_other = convertTextBox(tbx_p2_cause_aggression_other),
            p2_cause_exposure_chemName = convertTextBox(tbx_p2_cause_exposure_chemName),
            p2_cause_chemInhalation = convertCheckBox(cbx_p2_cause_chemInhalation),
            p2_cause_chemIngest = convertCheckBox(cbx_p2_cause_chemIngest),
            p2_cause_chemContact = convertCheckBox(cbx_p2_cause_chemContact),
            p2_cause_latex = convertCheckBox(cbx_p2_cause_latex),
            p2_cause_dust = convertCheckBox(cbx_p2_cause_dust),
            p2_cause_disease = convertCheckBox(cbx_p2_cause_disease),
            p2_cause_temp = convertCheckBox(cbx_p2_cause_temp),
            p2_cause_noise = convertCheckBox(cbx_p2_cause_noise),
            p2_cause_radiation = convertCheckBox(cbx_p2_cause_radiation),
            p2_cause_elec = convertCheckBox(cbx_p2_cause_elec),
            p2_cause_air = convertCheckBox(cbx_p2_cause_air),
            #endregion D_Cause

            #region E_ContributingFactors
            p2_factors_malfunction = convertCheckBox(cbx_p2_factors_malfunction),
            p2_factors_improperUse = convertCheckBox(cbx_p2_factors_improperUse),
            p2_factors_signage = convertCheckBox(cbx_p2_factors_signage),
            p2_factors_notAvailable = convertCheckBox(cbx_p2_factors_notAvailable),
            p2_factors_poorDesign = convertCheckBox(cbx_p2_factors_poorDesign),
            p2_factors_otherEquip = convertTextBox(tbx_p2_factors_otherEquip),

            p2_factors_temp = convertCheckBox(cbx_p2_factors_temp),
            p2_factors_workplace = convertCheckBox(cbx_p2_factors_workplace),
            p2_factors_layout = convertCheckBox(cbx_p2_factors_layout),
            p2_factors_limitedWorkspace = convertCheckBox(cbx_p2_factors_limitedWorkspace),
            p2_factors_slippery = convertCheckBox(cbx_p2_factors_slippery),
            p2_factors_lighting = convertCheckBox(cbx_p2_factors_lighting),
            p2_factors_noise = convertCheckBox(cbx_p2_factors_noise),
            p2_factors_vent = convertCheckBox(cbx_p2_factors_vent),
            p2_factors_storage = convertCheckBox(cbx_p2_factors_storage),
            p2_factors_otherEnv = convertTextBox(tbx_p2_factors_otherEnv),

            p2_factors_assessment = convertCheckBox(cbx_p2_factors_assessment),
            p2_factors_procedure = convertCheckBox(cbx_p2_factors_procedure),
            p2_factors_appropriateEquip = convertCheckBox(cbx_p2_factors_appropriateEquip),
            p2_factors_conduct = convertCheckBox(cbx_p2_factors_conduct),
            p2_factors_extended = convertCheckBox(cbx_p2_factors_extended),
            p2_factors_comm = convertCheckBox(cbx_p2_factors_comm),
            p2_factors_unaccustomed = convertCheckBox(cbx_p2_factors_unaccustomed),
            p2_factors_otherWorkPractice = convertTextBox(tbx_p2_factors_otherWorkPractice),

            p2_factors_directions = convertCheckBox(cbx_p2_factors_directions),
            p2_factors_weight = convertCheckBox(cbx_p2_factors_weight),
            p2_factors_aggressive = convertCheckBox(cbx_p2_factors_aggressive),
            p2_factors_patientResistive = convertCheckBox(cbx_p2_factors_patientResistive),
            p2_factors_movement = convertCheckBox(cbx_p2_factors_movement),
            p2_factors_confused = convertCheckBox(cbx_p2_factors_confused),
            p2_factors_influence = convertCheckBox(cbx_p2_factors_influence),
            p2_factors_lang = convertCheckBox(cbx_p2_factors_lang),
            p2_factors_otherPatient = convertTextBox(tbx_p2_factors_otherPatient),

            p2_factors_alone = convertCheckBox(cbx_p2_factors_alone),
            p2_factors_info = convertCheckBox(cbx_p2_factors_info),
            p2_factors_scheduling = convertCheckBox(cbx_p2_factors_scheduling),
            p2_factors_training = convertCheckBox(cbx_p2_factors_training),
            p2_factors_equip = convertCheckBox(cbx_p2_factors_equip),
            p2_factors_personal = convertCheckBox(cbx_p2_factors_personal),
            p2_factors_safe = convertCheckBox(cbx_p2_factors_safe),
            p2_factors_perceived = convertCheckBox(cbx_p2_factors_perceived),
            p2_factors_otherOrganizational = convertTextBox(tbx_p2_factors_otherOrganizational),

            p2_factors_inexperienced = convertCheckBox(cbx_p2_factors_inexperienced),
            p2_factors_communication = convertCheckBox(cbx_p2_factors_communication),
            p2_factors_fatigued = convertCheckBox(cbx_p2_factors_fatigued),
            p2_factors_distracted = convertCheckBox(cbx_p2_factors_distracted),
            p2_factors_preexisting = convertCheckBox(cbx_p2_factors_preexisting),
            p2_factors_sick = convertCheckBox(cbx_p2_factors_sick),
            p2_factors_otherWorker = convertTextBox(tbx_p2_factors_otherWorker),
            #endregion E_ContributingFactors

            #region F_CorrectiveAction
            p2_corrective_person = convertTextBox(tbx_p2_corrective_person),
            p2_corrective_maintenance = convertRadioButtonList(rbl_p2_corrective_maintenance),
            p2_corrective_communicated = convertRadioButtonList(rbl_p2_corrective_communicated),
            p2_corrective_time = convertRadioButtonList(rbl_p2_corrective_time),
            #endregion F_CorrectiveAction

            #region G_FollowUp
            p2_corrective_written = convertTextBox(tbx_p2_corrective_written),
            p2_corrective_education = convertTextBox(tbx_p2_corrective_education),
            p2_corrective_equipment = convertTextBox(tbx_p2_corrective_equipment),
            p2_corrective_environment = convertTextBox(tbx_p2_corrective_environment),
            p2_corrective_patient = convertTextBox(tbx_p2_corrective_patient),
            #endregion G_FollowUp

            #region G_ManagersReport
            p2_manager_previous = convertTextBox(tbx_p2_manager_previous),
            p2_manager_objections = convertTextBox(tbx_p2_manager_objections),
            p2_manager_alternative = convertTextBox(tbx_p2_manager_alternative),
            #endregion G_ManagersReport

            followUpStatus = "0",
        };

        #region A_IncidentInfo_Dates
        if (!tbx_p1_action_medicalER_date.Text.Equals(String.Empty))
        {
            DateTime dateMedicalER = Convert.ToDateTime(tbx_p1_action_medicalER_date.Text);
            report.p1_action_medicalER_date = dateMedicalER;
        }

        if (!tbx_p1_action_medicalGP_date.Text.Equals(String.Empty))
        {
            DateTime dateMedicalGP = Convert.ToDateTime(tbx_p1_action_medicalGP_date.Text);
            report.p1_action_medicalGP_date = dateMedicalGP;
        }
        #endregion A_IncidentInfo_Dates

        #region C_AccidentInvestigation_PatientHandling
        if (!tbx_p1_numEmployeesInvolved.Text.Equals(String.Empty))
        {
            try
            {
                report.p1_numEmployeesInvolved = Convert.ToInt32(tbx_p1_numEmployeesInvolved.Text);
            }
            catch (FormatException)
            {
                Popup_Overlay("Report not created. The number of employees involved (in Patient Handling of Section C) must be a number.", FailColour);
                return null;
            }
        }
        #endregion C_AccidentInvestigation_PatientHandling

        #region F_CorrectiveAction_Dates
        if (!tbx_p2_corrective_personDate.Text.Equals(String.Empty))
        {
            DateTime dateCorrectivePerson = Convert.ToDateTime(tbx_p2_corrective_personDate.Text);
            report.p2_corrective_personDate = dateCorrectivePerson;
        }

        if (!tbx_p2_corrective_maintenanceDate.Text.Equals(String.Empty))
        {
            DateTime dateMaintenance = Convert.ToDateTime(tbx_p2_corrective_maintenanceDate.Text);
            report.p2_corrective_maintenanceDate = dateMaintenance;
        }

        if (!tbx_p2_corrective_communicatedDate.Text.Equals(String.Empty))
        {
            DateTime dateCommunicated = Convert.ToDateTime(tbx_p2_corrective_communicatedDate.Text);
            report.p2_corrective_communicatedDate = dateCommunicated;
        }

        if (!tbx_p2_corrective_timeDate.Text.Equals(String.Empty))
        {
            DateTime dateTimeLoss = Convert.ToDateTime(tbx_p2_corrective_timeDate.Text);
            report.p2_corrective_timeDate = dateTimeLoss;
        }
        #endregion F_CorrectiveAction_Dates

        #region G_FollowUp_Dates

        #region G_FollowUp_Dates_Target

        if (!tbx_p2_corrective_writtenTargetDate.Text.Equals(String.Empty))
        {
            DateTime writtenDate = Convert.ToDateTime(tbx_p2_corrective_writtenTargetDate.Text);
            report.p2_corrective_writtenTargetDate = writtenDate;
        }

        if (!tbx_p2_corrective_educationTargetDate.Text.Equals(String.Empty))
        {
            DateTime educationDate = Convert.ToDateTime(tbx_p2_corrective_educationTargetDate.Text);
            report.p2_corrective_educationTargetDate = educationDate;
        }

        if (!tbx_p2_corrective_equipmentTargetDate.Text.Equals(String.Empty))
        {
            DateTime equipmentDate = Convert.ToDateTime(tbx_p2_corrective_equipmentTargetDate.Text);
            report.p2_corrective_equipmentTargetDate = equipmentDate;
        }

        if (!tbx_p2_corrective_environmentTargetDate.Text.Equals(String.Empty))
        {
            DateTime environmentDate = Convert.ToDateTime(tbx_p2_corrective_environmentTargetDate.Text);
            report.p2_corrective_environmentTargetDate = environmentDate;
        }

        if (!tbx_p2_corrective_patientTargetDate.Text.Equals(String.Empty))
        {
            DateTime patientDate = Convert.ToDateTime(tbx_p2_corrective_patientTargetDate.Text);
            report.p2_corrective_patientTargetDate = patientDate;
        }

        #endregion G_FollowUp_Dates_Target

        #region G_FollowUp_Dates_Completed

        if (!tbx_p2_corrective_writtenCompletedDate.Text.Equals(String.Empty))
        {
            DateTime writtenDate = Convert.ToDateTime(tbx_p2_corrective_writtenCompletedDate.Text);
            report.p2_corrective_writtenCompletedDate = writtenDate;
        }

        if (!tbx_p2_corrective_educationCompletedDate.Text.Equals(String.Empty))
        {
            DateTime educationDate = Convert.ToDateTime(tbx_p2_corrective_educationCompletedDate.Text);
            report.p2_corrective_educationCompletedDate = educationDate;
        }

        if (!tbx_p2_corrective_equipmentCompletedDate.Text.Equals(String.Empty))
        {
            DateTime equipmentDate = Convert.ToDateTime(tbx_p2_corrective_equipmentCompletedDate.Text);
            report.p2_corrective_equipmentCompletedDate = equipmentDate;
        }

        if (!tbx_p2_corrective_environmentCompletedDate.Text.Equals(String.Empty))
        {
            DateTime environmentDate = Convert.ToDateTime(tbx_p2_corrective_environmentCompletedDate.Text);
            report.p2_corrective_environmentCompletedDate = environmentDate;
        }

        if (!tbx_p2_corrective_patientCompletedDate.Text.Equals(String.Empty))
        {
            DateTime patientDate = Convert.ToDateTime(tbx_p2_corrective_patientCompletedDate.Text);
            report.p2_corrective_patientCompletedDate = patientDate;
        }

        #endregion G_FollowUp_Dates_Completed

        #endregion G_FollowUp_Dates

        #region H_FixedShiftRotation
        #region H_FixedShiftRotation_Week1
        if (!tbx_p2_manager_week1_sun.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_sun.Text);
            report.p2_manager_week1_sun = d;
        }

        if (!tbx_p2_manager_week1_mon.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_mon.Text);
            report.p2_manager_week1_mon = d;
        }

        if (!tbx_p2_manager_week1_tue.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_tue.Text);
            report.p2_manager_week1_tue = d;
        }

        if (!tbx_p2_manager_week1_wed.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_wed.Text);
            report.p2_manager_week1_wed = d;
        }

        if (!tbx_p2_manager_week1_thu.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_thu.Text);
            report.p2_manager_week1_thu = d;
        }

        if (!tbx_p2_manager_week1_fri.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_fri.Text);
            report.p2_manager_week1_fri = d;
        }

        if (!tbx_p2_manager_week1_sat.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week1_sat.Text);
            report.p2_manager_week1_sat = d;
        }
        #endregion H_FixedShiftRotation_Week1

        #region H_FixedShiftRotation_Week2
        if (!tbx_p2_manager_week2_sun.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_sun.Text);
            report.p2_manager_week2_sun = d;
        }

        if (!tbx_p2_manager_week2_mon.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_mon.Text);
            report.p2_manager_week2_mon = d;
        }

        if (!tbx_p2_manager_week2_tue.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_tue.Text);
            report.p2_manager_week2_tue = d;
        }

        if (!tbx_p2_manager_week2_wed.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_wed.Text);
            report.p2_manager_week2_wed = d;
        }

        if (!tbx_p2_manager_week2_thu.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_thu.Text);
            report.p2_manager_week2_thu = d;
        }

        if (!tbx_p2_manager_week2_fri.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_fri.Text);
            report.p2_manager_week2_fri = d;
        }

        if (!tbx_p2_manager_week2_sat.Text.Equals(String.Empty))
        {
            Decimal d = Convert.ToDecimal(tbx_p2_manager_week2_sat.Text);
            report.p2_manager_week2_sat = d;
        }
        #endregion H_FixedShiftRotation_Week2
        #endregion H_FixedShiftRotation

        return report;
    }
Exemplo n.º 31
0
 /// <summary>
 /// Create a new Incident object.
 /// </summary>
 /// <param name="incidentID">Initial value of IncidentID.</param>
 /// <param name="incidentNumber">Initial value of IncidentNumber.</param>
 /// <param name="heatTicketNumber">Initial value of HeatTicketNumber.</param>
 /// <param name="technicianName">Initial value of TechnicianName.</param>
 /// <param name="technicianEmail">Initial value of TechnicianEmail.</param>
 /// <param name="technicianPhone">Initial value of TechnicianPhone.</param>
 /// <param name="serviceGroupID">Initial value of ServiceGroupID.</param>
 /// <param name="issueStartDate">Initial value of IssueStartDate.</param>
 /// <param name="issueResolutionDate">Initial value of IssueResolutionDate.</param>
 /// <param name="issueDeviceID">Initial value of IssueDeviceID.</param>
 /// <param name="issueLocation">Initial value of IssueLocation.</param>
 /// <param name="issueDescription">Initial value of IssueDescription.</param>
 /// <param name="issueSummary">Initial value of IssueSummary.</param>
 /// <param name="issueChronology">Initial value of IssueChronology.</param>
 /// <param name="issueRootCause">Initial value of IssueRootCause.</param>
 /// <param name="processImprovements">Initial value of ProcessImprovements.</param>
 /// <param name="otherSystemsAffected">Initial value of OtherSystemsAffected.</param>
 /// <param name="travelRequired">Initial value of TravelRequired.</param>
 /// <param name="severityID">Initial value of SeverityID.</param>
 /// <param name="impactID">Initial value of ImpactID.</param>
 /// <param name="visibilityID">Initial value of VisibilityID.</param>
 /// <param name="status">Initial value of Status.</param>
 /// <param name="reportID">Initial value of ReportID.</param>
 /// <param name="createdBy">Initial value of CreatedBy.</param>
 /// <param name="createdDate">Initial value of CreatedDate.</param>
 /// <param name="lastModifiedBy">Initial value of LastModifiedBy.</param>
 /// <param name="lastModifiedDate">Initial value of LastModifiedDate.</param>
 public static Incident CreateIncident(
             global::System.Guid incidentID, 
             string incidentNumber, 
             string heatTicketNumber, 
             string technicianName, 
             string technicianEmail, 
             string technicianPhone, 
             int serviceGroupID, 
             global::System.DateTime issueStartDate, 
             global::System.DateTime issueResolutionDate, 
             string issueDeviceID, 
             string issueLocation, 
             string issueDescription, 
             string issueSummary, 
             string issueChronology, 
             string issueRootCause, 
             string processImprovements, 
             bool otherSystemsAffected, 
             bool travelRequired, 
             int severityID, 
             int impactID, 
             int visibilityID, 
             string status, 
             int reportID, 
             string createdBy, 
             global::System.DateTime createdDate, 
             string lastModifiedBy, 
             global::System.DateTime lastModifiedDate)
 {
     Incident incident = new Incident();
     incident.IncidentID = incidentID;
     incident.IncidentNumber = incidentNumber;
     incident.HeatTicketNumber = heatTicketNumber;
     incident.TechnicianName = technicianName;
     incident.TechnicianEmail = technicianEmail;
     incident.TechnicianPhone = technicianPhone;
     incident.ServiceGroupID = serviceGroupID;
     incident.IssueStartDate = issueStartDate;
     incident.IssueResolutionDate = issueResolutionDate;
     incident.IssueDeviceID = issueDeviceID;
     incident.IssueLocation = issueLocation;
     incident.IssueDescription = issueDescription;
     incident.IssueSummary = issueSummary;
     incident.IssueChronology = issueChronology;
     incident.IssueRootCause = issueRootCause;
     incident.ProcessImprovements = processImprovements;
     incident.OtherSystemsAffected = otherSystemsAffected;
     incident.TravelRequired = travelRequired;
     incident.SeverityID = severityID;
     incident.ImpactID = impactID;
     incident.VisibilityID = visibilityID;
     incident.Status = status;
     incident.ReportID = reportID;
     incident.CreatedBy = createdBy;
     incident.CreatedDate = createdDate;
     incident.LastModifiedBy = lastModifiedBy;
     incident.LastModifiedDate = lastModifiedDate;
     return incident;
 }
 public void Save(Incident incident)
 {
     if (incident.ManagerNotificationRequired())
         _notifier.NotifyIncidentManager(incident);
 }
Exemplo n.º 33
0
        public async Task <ActionResult> Create([Bind(Include = "City,Created,Description,FirstName,ImageUri,IsEmergency,LastModified,LastName,OutageType,PhoneNumber,Resolved,State,Street,ZipCode")] IncidentViewModel incident, HttpPostedFileBase imageFile)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Incident incidentToSave = IncidentMappers.MapIncidentViewModel(incident);

                    using (IncidentAPIClient client = IncidentApiHelper.GetIncidentAPIClient())
                    {
                        var result = client.Incident.CreateIncident(incidentToSave);
                        if (!string.IsNullOrEmpty(result))
                        {
                            incidentToSave = JsonConvert.DeserializeObject <Incident>(result);
                        }
                    }

                    //Now upload the file if there is one
                    if (imageFile != null && imageFile.ContentLength > 0)
                    {
                        //### Add Blob Upload code here #####
                        //Give the image a unique name based on the incident id
                        var imageUrl = await StorageHelper.UploadFileToBlobStorage(incidentToSave.ID, imageFile);

                        //### Add Blob Upload code here #####
                        incidentToSave.ImageUri = imageUrl;

                        //Update the incident with the image URL of the upload
                        using (IncidentAPIClient client = IncidentApiHelper.GetIncidentAPIClient())
                        {
                            var result = await client.Incident.UpdateIncidentAsync(incidentToSave.ID, incidentToSave);

                            if (!string.IsNullOrEmpty(result))
                            {
                                incidentToSave = JsonConvert.DeserializeObject <Incident>(result);
                            }
                        }

                        //### Add Queue code here #####
                        //Add a message to the queue to process this image
                        await StorageHelper.AddMessageToQueue(incidentToSave.ID, imageFile.FileName);

                        //### Add Queue code here #####
                    }

                    //##### CLEAR CACHE ####
                    RedisCacheHelper.ClearCache(Settings.REDISCCACHE_KEY_INCIDENTDATA);
                    //##### CLEAR CACHE ####

                    //##### SEND EMAIL #####
                    await SendIncidentEmail(incidentToSave, Url.Action("Index", "Dashboard", null, Request.Url.Scheme));

                    //##### SEND EMAIL  #####

                    return(RedirectToAction("Index", "Dashboard"));
                }
            }
            catch
            {
                return(View());
            }

            return(View(incident));
        }
Exemplo n.º 34
0
        public static bool UpdateIncident(Incident oldInc, Incident newInc)
        {
            SqlConnection connection = TechSupportDBConnection.GetConnection();
            string updateStatement = "UPDATE Incidents SET " +
                "TechID = @NewTechID, Description = @NewDescription " +
                "WHERE IncidentID = " + oldInc.IncidentID;
            SqlCommand updateCommand = new SqlCommand(updateStatement, connection);

            updateCommand.Parameters.AddWithValue("@NewTechID", newInc.TechID);

            if (String.Equals(oldInc.Description, newInc.Description))
            {

                    updateCommand.Parameters.AddWithValue("@NewDescription", (oldInc.Description + Environment.NewLine
                        + DateTime.Now.ToShortDateString() + " updated/assigned the technician"));

            }
            else
            {
                updateCommand.Parameters.AddWithValue("@NewDescription", (oldInc.Description + Environment.NewLine
                    + DateTime.Now.ToShortDateString() + " " + newInc.Description));
            }

            try
            {
                connection.Open();
                int count = updateCommand.ExecuteNonQuery();
                if (count > 0)
                    return true;
                else return false;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (InvalidOperationException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                connection.Close();

            }
        }
Exemplo n.º 35
0
 internal void Allocate(Incident i)
 {
     incidentsToProcess.Add(i);
 }
Exemplo n.º 36
0
 /// <summary>
 /// Returns the contents of the given incident attachment.
 /// </summary>
 /// <param name="incidentId"></param>
 /// <param name="fileId"></param>
 /// <returns></returns>
 public byte[] getFileData(int incidentId, int fileId)
 {
     Incident incident = new Incident();
     incident.ID = new ID(); // incident id
     incident.ID.id = incidentId;
     incident.ID.idSpecified = true;
     FileAttachmentCommon file = new FileAttachmentCommon();
     file.ID = new ID(); // file id
     file.ID.id = fileId;
     file.ID.idSpecified = true;
     return _rnowClient.GetFileData(_rnowClientInfoHeader, incident , file.ID, false);
 }
Exemplo n.º 37
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            Contact contact1 = new Contact
            {
                FirstName                = "Colin",
                LastName                 = "Wilcox",
                Address1_City            = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98052",
                Anniversary              = new DateTime(2010, 3, 5),
                CreditLimit              = new Money(300),
                Description              = "Alpine Ski House",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(1),
                NumberOfChildren         = 1,
                Address1_Latitude        = 47.6741667,
                Address1_Longitude       = -122.1202778,
                CreditOnHold             = false
            };

            _contactId1 = service.Create(contact1);

            Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName);

            Contact contact2 = new Contact
            {
                FirstName                = "Brian",
                LastName                 = "Smith",
                Address1_City            = "Bellevue",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98008",
                Anniversary              = new DateTime(2010, 4, 5),
                CreditLimit              = new Money(30000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = false
            };

            _contactId2 = service.Create(contact2);

            Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName);

            Contact contact3 = new Contact
            {
                FirstName                = "Darren",
                LastName                 = "Parker",
                Address1_City            = "Kirkland",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98033",
                Anniversary              = new DateTime(2010, 10, 5),
                CreditLimit              = new Money(10000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = false
            };

            _contactId3 = service.Create(contact3);

            Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName);

            Contact contact4 = new Contact
            {
                FirstName                = "Ben",
                LastName                 = "Smith",
                Address1_City            = "Kirkland",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98033",
                Anniversary              = new DateTime(2010, 7, 5),
                CreditLimit              = new Money(12000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = true
            };

            _contactId4 = service.Create(contact4);

            Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName);

            Incident incident1 = new Incident
            {
                Title          = "Test Case 1",
                PriorityCode   = new OptionSetValue(1),      // 1 = High
                CaseOriginCode = new OptionSetValue(1),      // 1 = Phone
                CaseTypeCode   = new OptionSetValue(2),      // 2 = Problem
                Description    = "Description for Test Case 1.",
                FollowupBy     = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                CustomerId     = new EntityReference(Contact.EntityLogicalName, _contactId2)
            };

            _incidentId1 = service.Create(incident1);

            Console.Write("Created a sample incident 1: {0}, ", incident1.Title);

            Relationship relationship1 = new Relationship("incident_customer_contacts");
            EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection();

            relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1));
            service.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1);

            Console.Write("Added relationship between incident 1 and contact 1, ");


            Account account1 = new Account
            {
                Name          = "Coho Winery",
                Address1_Name = "Coho Vineyard & Winery",
                Address1_City = "Redmond"
            };

            _accountId1 = service.Create(account1);

            Console.Write("Created a sample account 1: {0}, ", account1.Name);

            Incident incident2 = new Incident
            {
                Title          = "Test Case 2",
                PriorityCode   = new OptionSetValue(1),      // 1 = High
                CaseOriginCode = new OptionSetValue(1),      // 1 = Phone
                CaseTypeCode   = new OptionSetValue(2),      // 2 = Problem
                Description    = "Description for Sample Case 2.",
                FollowupBy     = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                CustomerId     = new EntityReference(Contact.EntityLogicalName, _contactId1)
            };

            _incidentId2 = service.Create(incident2);

            Console.Write("Created a sample incident 2: {0}, ", incident2.Title);

            Relationship relationship2 = new Relationship("incident_customer_accounts");
            EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection();

            relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1));
            service.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2);

            Console.Write("Added relationship between incident 2 and account 1, ");

            Lead lead = new Lead()
            {
                FirstName = "Diogo",
                LastName  = "Andrade"
            };

            _leadId = service.Create(lead);
            Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName);

            Account account2 = new Account
            {
                Name              = "Contoso Ltd",
                ParentAccountId   = new EntityReference(Account.EntityLogicalName, _accountId1),
                Address1_Name     = "Contoso Pharmaceuticals",
                Address1_City     = "Redmond",
                OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId)
            };

            _accountId2 = service.Create(account2);

            Console.Write("Created a sample account 2: {0}, ", account2.Name);

            Relationship relationship3 = new Relationship("account_primary_contact");
            EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection();

            relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2));
            service.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3);

            Console.WriteLine("Added relationship between account 2 and contact 2.");

            Console.WriteLine("Required records have been created.");
        }
 public IActionResult Delete(Incident incident)
 {
     context.Incidents.Remove(incident);
     context.SaveChanges();
     return(RedirectToAction("Index", "Home"));
 }
Exemplo n.º 39
0
        private void BindValues()
        {
            if (IncidentId != 0)
            {
                int    FolderId                = -1;
                string sIdentifier             = "";
                bool   canViewFinances         = Incident.CanViewFinances(IncidentId);
                bool   canViewTimeTrackingInfo = Incident.CanViewTimeTrackingInfo(IncidentId);

                using (IDataReader reader = Incident.GetIncident(IncidentId))
                {
                    if (reader.Read())
                    {
                        ///  IncidentId, ProjectId, ProjectTitle, CreatorId,
                        ///  Title, Description, Resolution, Workaround, CreationDate,
                        ///  TypeId, TypeName, PriorityId, PriorityName,
                        ///  SeverityId, SeverityName, IsEmail, MailSenderEmail, StateId, TaskTime,
                        ///  IncidentBoxId, OrgUid, ContactUid, ClientName, ControllerId,
                        ///  ResponsibleGroupState, TotalMinutes, TotalApproved

                        lblCreator.Text      = CommonHelper.GetUserStatus((int)reader["CreatorId"]);
                        lblCreationDate.Text = ((DateTime)reader["CreationDate"]).ToShortDateString() + " " + ((DateTime)reader["CreationDate"]).ToShortTimeString();

                        if (reader["Identifier"] != DBNull.Value)
                        {
                            sIdentifier = reader["Identifier"].ToString();
                        }
                        if (reader["IncidentBoxId"] != DBNull.Value)
                        {
                            FolderId = (int)reader["IncidentBoxId"];
                        }
                        lblClient.Text   = Util.CommonHelper.GetClientLink(this.Page, reader["OrgUid"], reader["ContactUid"], reader["ClientName"]);
                        lblTaskTime.Text = Util.CommonHelper.GetHours((int)reader["TaskTime"]);

                        if (canViewTimeTrackingInfo)
                        {
                            SpentTimeLabel.Text = String.Format(CultureInfo.InvariantCulture,
                                                                "{0} / {1}:",
                                                                LocRM3.GetString("spentTime"),
                                                                LocRM3.GetString("approvedTime"));

                            lblSpentTime.Text = String.Format(CultureInfo.InvariantCulture,
                                                              "{0} / {1}",
                                                              Util.CommonHelper.GetHours((int)reader["TotalMinutes"]),
                                                              Util.CommonHelper.GetHours((int)reader["TotalApproved"]));
                        }
                    }
                }

                List <string> sCategories = new List <string>();
                using (IDataReader reader = Incident.GetListCategories(IncidentId))
                {
                    while (reader.Read())
                    {
                        sCategories.Add(reader["CategoryName"].ToString());
                    }
                }
                string[] mas = sCategories.ToArray();
                if (mas.Length > 0)
                {
                    lblGenCats.Text   = String.Join(", ", mas);
                    trGenCats.Visible = true;
                }
                else
                {
                    trGenCats.Visible = false;
                }

                List <string> sIssCategories = new List <string>();
                using (IDataReader reader = Incident.GetListIncidentCategoriesByIncident(IncidentId))
                {
                    while (reader.Read())
                    {
                        sIssCategories.Add(reader["CategoryName"].ToString());
                    }
                }
                string[] mas1 = sIssCategories.ToArray();
                if (mas1.Length > 0)
                {
                    lblIssCats.Text   = String.Join(", ", mas1);
                    trIssCats.Visible = true;
                }
                else
                {
                    trIssCats.Visible = false;
                }

                if (FolderId > 0)
                {
                    IncidentBox         box      = IncidentBox.Load(FolderId);
                    IncidentBoxDocument settings = IncidentBoxDocument.Load(FolderId);
                    if (Security.CurrentUser.IsExternal)
                    {
                        lblFolder.Text = String.Format("{0}", box.Name);
                    }
                    else if (Security.IsUserInGroup(InternalSecureGroups.Administrator))
                    {
                        lblFolder.Text = String.Format("<a href='../Admin/EMailIssueBoxView.aspx?IssBoxId={1}'>{0}</a>", box.Name, box.IncidentBoxId);
                    }
                    else
                    {
                        lblFolder.Text = String.Format("<a href=\"javascript:OpenPopUpWindow(&quot;../Incidents/IncidentBoxView.aspx?IssBoxId={1}&IncidentId={2}&quot;,500,375)\">{0}</a>",
                                                       box.Name, box.IncidentBoxId, IncidentId.ToString());
                    }
                    lblManager.Text = CommonHelper.GetUserStatus(settings.GeneralBlock.Manager);
                    if (sIdentifier == "")
                    {
                        lblTicket.Text = TicketUidUtil.Create(box.IdentifierMask, IncidentId);
                    }
                    else
                    {
                        lblTicket.Text = sIdentifier;
                    }
                }

                trClient.Visible   = PortalConfig.CommonIncidentAllowViewClientField;
                trGenCats.Visible  = PortalConfig.CommonIncidentAllowViewGeneralCategoriesField;
                trIssCats.Visible  = PortalConfig.IncidentAllowViewIncidentCategoriesField;
                trTaskTime.Visible = PortalConfig.CommonIncidentAllowViewTaskTimeField;
            }
        }
Exemplo n.º 40
0
  /// <summary>
  /// Creates any entity records that this sample requires.
  /// </summary>
  public void CreateRequiredRecords()
  {
   Contact contact1 = new Contact
   {
    FirstName = "Colin",
    LastName = "Wilcox",
    Address1_City = "Redmond",
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98052",
    Anniversary = new DateTime(2010, 3, 5),
    CreditLimit = new Money(300),
    Description = "Alpine Ski House",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(1),
    NumberOfChildren = 1,
    Address1_Latitude = 47.6741667,
    Address1_Longitude = -122.1202778,
    CreditOnHold = false
   };
   _contactId1 = _serviceProxy.Create(contact1);

   Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName);

   Contact contact2 = new Contact
   {
    FirstName = "Brian",
    LastName = "Smith",
    Address1_City = "Bellevue",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98008",
    Anniversary = new DateTime(2010, 4, 5),
    CreditLimit = new Money(30000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = false
   };
   _contactId2 = _serviceProxy.Create(contact2);

   Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName);

   Contact contact3 = new Contact
   {
    FirstName = "Darren",
    LastName = "Parker",
    Address1_City = "Kirkland",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98033",
    Anniversary = new DateTime(2010, 10, 5),
    CreditLimit = new Money(10000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = false
   };
   _contactId3 = _serviceProxy.Create(contact3);

   Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName);

   Contact contact4 = new Contact
   {
    FirstName = "Ben",
    LastName = "Smith",
    Address1_City = "Kirkland",
    FamilyStatusCode = new OptionSetValue(3),
    Address1_StateOrProvince = "WA",
    Address1_PostalCode = "98033",
    Anniversary = new DateTime(2010, 7, 5),
    CreditLimit = new Money(12000),
    Description = "Coho Winery",
    StatusCode = new OptionSetValue(1),
    AccountRoleCode = new OptionSetValue(2),
    NumberOfChildren = 2,
    Address1_Latitude = 47.6105556,
    Address1_Longitude = -122.1994444,
    CreditOnHold = true
   };
   _contactId4 = _serviceProxy.Create(contact4);

   Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName);

   Incident incident1 = new Incident
   {
    Title = "Test Case 1",
    PriorityCode = new OptionSetValue(1), // 1 = High
    CaseOriginCode = new OptionSetValue(1), // 1 = Phone
    CaseTypeCode = new OptionSetValue(2), // 2 = Problem
    Description = "Description for Test Case 1.",
    FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
    CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId2)
   };

   _incidentId1 = _serviceProxy.Create(incident1);

   Console.Write("Created a sample incident 1: {0}, ", incident1.Title);

   Relationship relationship1 = new Relationship("incident_customer_contacts");
   EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection();
   relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1));
   _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1);

   Console.Write("Added relationship between incident 1 and contact 1, ");


   Account account1 = new Account
   {
    Name = "Coho Winery",
    Address1_Name = "Coho Vineyard & Winery",
    Address1_City = "Redmond"
   };
   _accountId1 = _serviceProxy.Create(account1);

   Console.Write("Created a sample account 1: {0}, ", account1.Name);

   Incident incident2 = new Incident
   {
    Title = "Test Case 2",
    PriorityCode = new OptionSetValue(1), // 1 = High
    CaseOriginCode = new OptionSetValue(1), // 1 = Phone
    CaseTypeCode = new OptionSetValue(2), // 2 = Problem
    Description = "Description for Sample Case 2.",
    FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
    CustomerId = new EntityReference(Contact.EntityLogicalName, _contactId1)
   };

   _incidentId2 = _serviceProxy.Create(incident2);

   Console.Write("Created a sample incident 2: {0}, ", incident2.Title);

   Relationship relationship2 = new Relationship("incident_customer_accounts");
   EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection();
   relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1));
   _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2);

   Console.Write("Added relationship between incident 2 and account 1, ");

   Lead lead = new Lead()
   {
    FirstName = "Diogo",
    LastName = "Andrade"
   };
   _leadId = _serviceProxy.Create(lead);
   Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName);

   Account account2 = new Account
   {
    Name = "Contoso Ltd",
    ParentAccountId = new EntityReference(Account.EntityLogicalName, _accountId1),
    Address1_Name = "Contoso Pharmaceuticals",
    Address1_City = "Redmond",
    OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId)
   };
   _accountId2 = _serviceProxy.Create(account2);

   Console.Write("Created a sample account 2: {0}, ", account2.Name);

   Relationship relationship3 = new Relationship("account_primary_contact");
   EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection();
   relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2));
   _serviceProxy.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3);

   Console.WriteLine("Added relationship between account 2 and contact 2.");
  }
Exemplo n.º 41
0
 internal void MarkFileImported(ImportFile importFile)
 {
     int id = importFile.FileId;
     IFAttachInc2 attach = null;
     if (null != _Incident && null != _Incident.FAttach2)
     {
         foreach (var f in _Incident.FAttach2)
         {
             if (f.ID == id)
             {
                 attach = f;
                 break;
             }
         }
     }
     if (null == attach) return;
     // update the description of an incident's attachment
     Incident incident = new Incident();
     incident.ID = new ID();
     incident.ID.id = _Incident.ID;
     incident.ID.idSpecified = true;
     FileAttachmentIncident file = new FileAttachmentIncident();
     file.ID = new ID();
     file.ID.id = id;
     file.ID.idSpecified = true;
     file.action = ActionEnum.update;
     file.actionSpecified = true;
     file.Private = attach.Private;
     file.PrivateSpecified = true;
     bool updated;
     switch (importFile.StatusCode)
     {
         case 70:
         case 75:
             file.Description = importFile.Description +  string.Format("{{{0:00}}}", importFile.StatusCode);
             updated = true;
             break;
         default:
             updated = false;
             break;
     }
     if (updated)
     {
         incident.FileAttachments = new FileAttachmentIncident[1] { file };
         try
         {
             _rnSrv.updateObject(new RNObject[1] { incident });
         }
         catch (Exception ex)
         {
             _Model._Proxy.NoticeLog(String.Format("EBS Bulk Import failed to update the description of file {0}, id {1}",
                 importFile.Name, id), ex.Message);
         }
     }
 }
Exemplo n.º 42
0
        /// <summary>
        /// returns the Incident specified by the incident ID
        /// </summary>
        /// <param name="incID">The IncidentID of the incident to be returned</param>
        /// <returns>the Specified Incident</returns>
        public static Incident ReturnIncident(int @incID)
        {
            Incident returnInc = new Incident();
            string selectStatement = "SELECT IncidentID, Incidents.CustomerID, Customers.Name, ProductCode, DateOpened, Title, Description, TechID " +
                "FROM Incidents JOIN Customers on Incidents.CustomerID = Customers.CustomerID WHERE IncidentID = " + @incID;

            try
            {
                using (SqlConnection connection = TechSupportDBConnection.GetConnection())
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (SqlException ex)
                    {
                        throw ex;
                    }
                    using (SqlCommand selectCommand = new SqlCommand(selectStatement, connection))

                    using (SqlDataReader reader = selectCommand.ExecuteReader())
                    {
                        int incCustName = reader.GetOrdinal("Name");
                        int incProdCode = reader.GetOrdinal("ProductCode");
                        int incDateOrd = reader.GetOrdinal("DateOpened");
                        int incTitleOrd = reader.GetOrdinal("Title");
                        int incDescOrd = reader.GetOrdinal("Description");
                        int incTechIDOrd = reader.GetOrdinal("TechID");
                        while (reader.Read())
                        {
                            returnInc.IncidentID = (int)reader["IncidentID"];
                            returnInc.CustomerID = (int)reader["CustomerID"];

                            if (reader.IsDBNull(incTechIDOrd))
                            {
                               returnInc.TechID = null;
                            }
                            else
                            {
                               returnInc.TechID = (int)reader["TechID"];
                            }

                            returnInc.CustomerName = reader.GetString(incCustName);
                            returnInc.ProductCode = reader.GetString(incProdCode);
                            returnInc.DateOpened = reader.GetDateTime(incDateOrd);
                            returnInc.Title = reader.GetString(incTitleOrd);
                            returnInc.Description = reader.GetString(incDescOrd);

                        }
                        connection.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            catch (InvalidOperationException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return returnInc;
        }
        private bool SaveAccidentToOperational(AccidentStandardDTO accident)
        {
            try
            {
                if (accident == null)
                {
                    return(false);
                }

                var incident = operational.Incident.Where(i => i.IncidentNumber == accident.IncidentNo).FirstOrDefault();

                if (incident != null)
                {
                    return(true);
                }

                int?incidentAreaId          = null;
                int?incidentCauseId         = null;
                int?incidentCityId          = null;
                int?incidentCrashSeverityId = null;
                int?incidentCrashTypeId     = null;
                int?incidentEmirateId       = null;
                int?incidentIntersectionId  = null;
                int?incidentLightingId      = null;
                int?incidentLocationId      = null;
                int?incidentLocationTypeId  = null;
                int?incidentPConditionId    = null;
                int?incidentPoliceStationId = null;
                int?incidentRoadTypeId      = null;
                int?incidentTypeId          = null;
                int?incidentWeatherId       = null;

                if (accident.AreaName != null && accident.AreaName.Trim().Length > 0)
                {
                    var incidentArea = operational.IncidentAreas.Where(a => a.AreaNameAr == accident.AreaName).FirstOrDefault();

                    if (incidentArea == null)
                    {
                        incidentArea = operational.IncidentAreas.Add(new IncidentArea {
                            AreaNameAr = accident.AreaName
                        });
                    }

                    operational.SaveChanges();

                    incidentAreaId = incidentArea.Id;
                }

                if (accident.CauseName != null && accident.CauseName.Trim().Length > 0)
                {
                    var incidentCause = operational.IncidentCauses.Where(a => a.CauseNameAr == accident.CauseName).FirstOrDefault();

                    if (incidentCause == null)
                    {
                        incidentCause = operational.IncidentCauses.Add(new IncidentCause {
                            CauseNameAr = accident.CauseName
                        });
                    }

                    operational.SaveChanges();

                    incidentCauseId = incidentCause.Id;
                }

                if (accident.CityName != null && accident.CityName.Trim().Length > 0)
                {
                    var incidentCity = operational.IncidentCities.Where(a => a.CityNameAr == accident.CityName).FirstOrDefault();

                    if (incidentCity == null)
                    {
                        incidentCity = operational.IncidentCities.Add(new IncidentCity {
                            CityNameAr = accident.CityName
                        });
                    }

                    operational.SaveChanges();

                    incidentCityId = incidentCity.Id;
                }

                if (accident.CrashSeverityName != null && accident.CrashSeverityName.Trim().Length > 0)
                {
                    var incidentCrashSeverity = operational.IncidentCrashSeverities.Where(a => a.CrashSeverityNameAr == accident.CrashSeverityName).FirstOrDefault();

                    if (incidentCrashSeverity == null)
                    {
                        incidentCrashSeverity = operational.IncidentCrashSeverities.Add(new IncidentCrashSeverity {
                            CrashSeverityNameAr = accident.CrashSeverityName
                        });
                    }

                    operational.SaveChanges();

                    incidentCrashSeverityId = incidentCrashSeverity.Id;
                }

                if (accident.CrashTypeName != null && accident.CrashTypeName.Trim().Length > 0)
                {
                    var incidentCrashType = operational.IncidentCrashTypes.Where(a => a.IncidentCrashTypeNameAr == accident.CrashTypeName).FirstOrDefault();

                    if (incidentCrashType == null)
                    {
                        incidentCrashType = operational.IncidentCrashTypes.Add(new IncidentCrashType {
                            IncidentCrashTypeNameAr = accident.CrashTypeName
                        });
                    }

                    operational.SaveChanges();

                    incidentCrashTypeId = incidentCrashType.Id;
                }

                if (accident.EmirateName != null && accident.EmirateName.Trim().Length > 0)
                {
                    var incidentEmirate = operational.IncidentEmirates.Where(a => a.EmirateNameAr == accident.EmirateName).FirstOrDefault();

                    if (incidentEmirate == null)
                    {
                        incidentEmirate = operational.IncidentEmirates.Add(new IncidentEmirate {
                            EmirateNameAr = accident.EmirateName
                        });
                    }

                    operational.SaveChanges();

                    incidentEmirateId = incidentEmirate.Id;
                }

                if (accident.IntersectionName != null && accident.IntersectionName.Trim().Length > 0)
                {
                    var incidentIntersection = operational.IncidentIntersections.Where(a => a.IntersectionNameAr == accident.IntersectionName).FirstOrDefault();

                    if (incidentIntersection == null)
                    {
                        incidentIntersection = operational.IncidentIntersections.Add(new IncidentIntersection {
                            IntersectionNameAr = accident.IntersectionName
                        });
                    }

                    operational.SaveChanges();

                    incidentIntersectionId = incidentIntersection.Id;
                }

                if (accident.LightingName != null && accident.LightingName.Trim().Length > 0)
                {
                    var incidentLighting = operational.IncidentLightings.Where(a => a.LightingNameAr == accident.LightingName).FirstOrDefault();

                    if (incidentLighting == null)
                    {
                        incidentLighting = operational.IncidentLightings.Add(new IncidentLighting {
                            LightingNameAr = accident.LightingName
                        });
                    }

                    operational.SaveChanges();

                    incidentLightingId = incidentLighting.Id;
                }

                if (accident.LocationName != null && accident.LocationName.Trim().Length > 0)
                {
                    var incidentLocation = operational.IncidentLocations.Where(a => a.LocationNameAr == accident.LocationName).FirstOrDefault();

                    if (incidentLocation == null)
                    {
                        incidentLocation = operational.IncidentLocations.Add(new IncidentLocation {
                            LocationNameAr = accident.LocationName
                        });
                    }

                    operational.SaveChanges();

                    incidentLocationId = incidentLocation.Id;
                }

                if (accident.LocationTypeName != null && accident.LocationTypeName.Trim().Length > 0)
                {
                    var incidentLocationType = operational.IncidentLocationTypes.Where(a => a.LocationTypeNameAr == accident.LocationTypeName).FirstOrDefault();

                    if (incidentLocationType == null)
                    {
                        incidentLocationType = operational.IncidentLocationTypes.Add(new IncidentLocationType {
                            LocationTypeNameAr = accident.LocationTypeName
                        });
                    }

                    operational.SaveChanges();

                    incidentLocationTypeId = incidentLocationType.Id;
                }

                if (accident.PConditionName != null && accident.PConditionName.Trim().Length > 0)
                {
                    var incidentPCondition = operational.IncidentPConditions.Where(a => a.PConditionNameAr == accident.PConditionName).FirstOrDefault();

                    if (incidentPCondition == null)
                    {
                        incidentPCondition = operational.IncidentPConditions.Add(new IncidentPCondition {
                            PConditionNameAr = accident.PConditionName
                        });
                    }

                    operational.SaveChanges();

                    incidentPConditionId = incidentPCondition.Id;
                }

                if (accident.PoliceStationName != null && accident.PoliceStationName.Trim().Length > 0)
                {
                    var incidentPoliceStation = operational.IncidentPoliceStation.Where(a => a.PoliceStationNameAr == accident.PoliceStationName).FirstOrDefault();

                    if (incidentPoliceStation == null)
                    {
                        incidentPoliceStation = operational.IncidentPoliceStation.Add(new IncidentPoliceStation {
                            PoliceStationNameAr = accident.PoliceStationName
                        });
                    }

                    operational.SaveChanges();

                    incidentPoliceStationId = incidentPoliceStation.PoliceStationId;
                }

                if (accident.RoadTypeName != null && accident.RoadTypeName.Trim().Length > 0)
                {
                    var incidentRoadType = operational.IncidentRoadTypes.Where(a => a.RoadTypeNameAr == accident.RoadTypeName).FirstOrDefault();

                    if (incidentRoadType == null)
                    {
                        incidentRoadType = operational.IncidentRoadTypes.Add(new IncidentRoadType {
                            RoadTypeNameAr = accident.RoadTypeName
                        });
                    }

                    operational.SaveChanges();

                    incidentRoadTypeId = incidentRoadType.Id;
                }

                if (accident.IncidentTypeName != null && accident.IncidentTypeName.Trim().Length > 0)
                {
                    var incidentIncidentType = operational.IncidentTypes.Where(a => a.IncidentTypeNameAr == accident.IncidentTypeName).FirstOrDefault();

                    if (incidentIncidentType == null)
                    {
                        incidentIncidentType = operational.IncidentTypes.Add(new IncidentType {
                            IncidentTypeNameAr = accident.IncidentTypeName
                        });
                    }

                    operational.SaveChanges();

                    incidentTypeId = incidentIncidentType.IncidentTypeId;
                }

                if (accident.WeatherName != null && accident.WeatherName.Trim().Length > 0)
                {
                    var incidentWeather = operational.IncidentWeathers.Where(a => a.WeatherNameAr == accident.WeatherName).FirstOrDefault();

                    if (incidentWeather == null)
                    {
                        incidentWeather = operational.IncidentWeathers.Add(new IncidentWeather {
                            WeatherNameAr = accident.WeatherName
                        });
                    }

                    operational.SaveChanges();

                    incidentWeatherId = incidentWeather.Id;
                }

                var         pointString = string.Format("POINT({0} {1})", accident.Longitude.ToString(), accident.Latitude.ToString());
                DbGeography dbGeography = DbGeography.FromText(pointString);

                var newAccident = new Incident
                {
                    AreaId                  = incidentAreaId,
                    CauseId                 = incidentCauseId,
                    CityId                  = incidentCityId,
                    IncidentTypeId          = incidentTypeId,
                    IntersectionId          = incidentIntersectionId,
                    LocationId              = incidentLocationId,
                    LightingId              = incidentLightingId,
                    LocationTypeId          = incidentLocationTypeId,
                    CrashSeverityId         = incidentCrashSeverityId,
                    CrashTypeId             = incidentCrashTypeId,
                    EmirateId               = incidentEmirateId,
                    PConditionId            = incidentPConditionId,
                    PoliceStationId         = incidentPoliceStationId,
                    RoadTypeId              = incidentRoadTypeId,
                    WeatherId               = incidentWeatherId,
                    IncidentAddress         = accident.AddressComment,
                    LanesCount              = accident.LanesCount,
                    TotalInjuriesFatalities = accident.TotalInjuriesFatalities,
                    SevereInjuries          = accident.SevereInjuriesCount,
                    SlightInjuries          = accident.SlightInjuriesCount,
                    Latitude                = accident.Latitude,
                    Longitude               = accident.Longitude,
                    MediumInjuries          = accident.MediumInjuriesCount,
                    Speed               = (int)accident.RoadSpeed,
                    Fatalities          = accident.FatalitiesCount,
                    GeoLocation         = dbGeography,
                    IncidentNumber      = accident.IncidentNo,
                    IsNoticed           = false,
                    CreatedTime         = accident.CreatedTime,
                    LocationDescription = accident.LocationDescription,
                    IncidentDescription = accident.CrashDescription
                };

                operational.Incident.Add(newAccident);

                return(operational.SaveChanges() > 0);
            }
            catch (DbEntityValidationException ex)
            {
                Utility.WriteLog(ex);
                return(false);
            }
            catch (DbUpdateException ex)
            {
                Utility.WriteLog(ex);
                return(false);
            }
            catch (EntityCommandCompilationException ex)
            {
                Utility.WriteLog(ex);
                return(false);
            }
            catch (EntityCommandExecutionException ex)
            {
                Utility.WriteLog(ex);
                return(false);
            }
            catch (Exception ex)
            {
                Utility.WriteLog(ex);
                return(false);
            }
        }
Exemplo n.º 44
0
        public void Should_Apply_Left_Outer_Join_Filters_When_The_Right_hand_side_of_the_expression_was_found()
        {
            var context = new XrmFakedContext();
            var service = context.GetFakedOrganizationService();

            // Date for filtering, we only want "expired" records, i.e. those that weren't set as regarding in any emails for this period and logically even exist this long
            var days = 5;

            var incident = new Incident
            {
                Id         = Guid.NewGuid(),
                Title      = "Test case",
                StatusCode = new OptionSetValue((int)IncidentState.Active)
            };

            var email = new Email
            {
                Id = Guid.NewGuid(),
                RegardingObjectId = incident.ToEntityReference(),
            };

            incident["createdon"] = DateTime.UtcNow.AddDays(-6);
            email["createdon"]    = DateTime.UtcNow.AddDays(10);

            context.Initialize(new List <Entity>()
            {
                incident, email
            });

            // Remove either incident createdon conditionexpression, or LinkEntities and the e-mail conditionexpression and it will pass
            // What this query expresses: Get all incidents, that are older than given number of days and that also didn't receive emails for this number of days
            var query = new QueryExpression
            {
                ColumnSet  = new ColumnSet(true),
                EntityName = Incident.EntityLogicalName,
                Criteria   =
                {
                    FilterOperator = LogicalOperator.And,
                    Filters        =
                    {
                        new FilterExpression
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     =
                            {
                                new ConditionExpression("statuscode", ConditionOperator.Equal,     new OptionSetValue((int)IncidentState.Active)),
                                new ConditionExpression("createdon",  ConditionOperator.LessEqual, DateTime.UtcNow.AddDays(-1 * days))
                            }
                        }
                    }
                },
                LinkEntities =
                {
                    new LinkEntity
                    {
                        LinkFromEntityName    = "incident",
                        LinkToEntityName      = "email",
                        LinkFromAttributeName = "incidentid",
                        LinkToAttributeName   = "regardingobjectid",
                        JoinOperator          = JoinOperator.LeftOuter,
                        LinkCriteria          = new FilterExpression
                        {
                            Filters =
                            {
                                new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions     =
                                    {
                                        new ConditionExpression("createdon", ConditionOperator.GreaterEqual, DateTime.UtcNow.AddDays(-1 * days))
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var incidents = service.RetrieveMultiple(query).Entities;

            Assert.Equal(1, incidents.Count);
        }
Exemplo n.º 45
0
        public async Task <string> UpdateStatus(IncidentStatusRequest statusRequest)
        {
            Services.Log.Info("Incident Status Update Request [Hub]");
            string responseText;

            var currentUserID = ((ServiceUser)Context.User).Id;

            stranddContext context = new stranddContext();

            //Retrieve Incident
            Incident updateIncident = await(from r in context.Incidents where (r.Id == statusRequest.IncidentGUID) select r).FirstOrDefaultAsync();

            //Find the Incident to Edit and return Bad Response if not found
            if (updateIncident != null)
            {
                //Check for Submitted Status and Update
                if (statusRequest.NewStatusCode != null)
                {
                    updateIncident.StatusCode            = statusRequest.NewStatusCode;
                    updateIncident.StatusCustomerConfirm = false;
                    updateIncident.StatusProviderConfirm = false;
                }

                //Check for Submitted Pricing and Update
                if (statusRequest.ServiceFee != 0)
                {
                    updateIncident.ServiceFee = statusRequest.ServiceFee;
                }

                //Check if ETA and Save Arrival Time
                if (statusRequest.ETA != 0)
                {
                    if (statusRequest.NewStatusCode == "ARRIVED")
                    {
                        updateIncident.ProviderArrivalTime = System.DateTime.Now;
                    }
                    else
                    {
                        DateTimeOffset?priorETA = updateIncident.ProviderArrivalTime;
                        updateIncident.ProviderArrivalTime = System.DateTime.Now.AddMinutes(statusRequest.ETA);

                        if (priorETA != null)
                        {
                            DateTimeOffset compareETA = (DateTimeOffset)priorETA;

                            compareETA = compareETA.AddMinutes(Convert.ToInt32(WebConfigurationManager.AppSettings["RZ_DelayMinuteBuffer"]));
                            if (DateTimeOffset.Compare(compareETA, (DateTimeOffset)updateIncident.ProviderArrivalTime) < 0)
                            {
                                statusRequest.Delayed = true;
                            }
                        }
                    }
                }
            }
            else
            {
                // Return Failed Response
                responseText = "Incident not found [" + statusRequest.IncidentGUID + "] in the system";
                Services.Log.Warn(responseText);
                return(responseText);
            }

            //Save record
            await context.SaveChangesAsync();

            Services.Log.Info("Incident [" + updateIncident.Id + "] Status Updated" + " to Code: " + updateIncident.StatusCode);

            await HistoryEvent.logHistoryEventAsync("INCIDENT_STATUS_ADMIN", updateIncident.StatusCode, updateIncident.Id, currentUserID, null, null);

            IncidentController.ProcessStatusRequestBehavior(statusRequest, updateIncident, Services);

            //Return Successful Response
            responseText = "Status Updated";
            return(responseText);
        }
Exemplo n.º 46
0
 public void AddToincidents(Incident incident)
 {
     base.AddObject("incidents", incident);
 }
Exemplo n.º 47
0
 public async Task <Guid> AddAsync(Incident entity)
 {
     throw await Task.Run(() => new NotImplementedException());
 }
Exemplo n.º 48
0
        public static List<Incident> GetOpenIncidentsByTech(int IdToCheck)
        {
            List<Incident> incidentsList = new List<Incident>();

            string selectStatement = "SELECT Products.Name as ProductName, DateOpened, DateClosed, " +
            "Customers.Name AS Name, Incidents.TechID, " +
            " Technicians.Name AS TechName, Title " +
                "FROM Incidents " +
                    "LEFT OUTER JOIN Products ON Incidents.ProductCode = Products.ProductCode " +
                    "LEFT OUTER JOIN Customers ON Incidents.CustomerID = Customers.CustomerID " +
                    "LEFT OUTER JOIN Technicians ON Incidents.TechID = Technicians.TechID "
                        + " WHERE Incidents.DateClosed IS NULL AND Incidents.TechID = " + IdToCheck;

            try
            {
                using (SqlConnection connection = TechSupportDBConnection.GetConnection())
                {
                    try
                    {
                        connection.Open();
                    }
                    catch (SqlException ex)
                    {
                        throw ex;
                    }
                    using (SqlCommand selectCommand = new SqlCommand(selectStatement, connection))

                    using (SqlDataReader reader = selectCommand.ExecuteReader())
                    {
                        int prodNameOrd = reader.GetOrdinal("ProductName");
                        int prodDateOrd = reader.GetOrdinal("DateOpened");
                        int prodCustOrd = reader.GetOrdinal("Name");
                        int prodTitleOrd = reader.GetOrdinal("Title");

                        while (reader.Read())
                        {
                            Incident incident = new Incident();
                            incident.ProductName = reader.GetString(prodNameOrd);
                            incident.DateOpened = reader.GetDateTime(prodDateOrd);
                            incident.CustomerName = reader.GetString(prodCustOrd);
                            incident.TechID = CheckValue(reader["TechID"]);

                            incident.Title = reader.GetString(prodTitleOrd);

                            incidentsList.Add(incident);
                        }
                        connection.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }

            catch (Exception ex)
            {
                throw ex;
            }

            return incidentsList;
        }
Exemplo n.º 49
0
 public ActionResult Create(Incident Incident, int EngineerId, int MachineId)
 {
     _db.Incidents.Add(Incident);
     _db.SaveChanges();
     return(RedirectToAction("Index"));
 }
Exemplo n.º 50
0
    /// <summary>
    /// This function is called when the player scans a tile
    /// </summary>
    /// <param name="result">The scanned value of the NFC Tag</param>
    public void OnMove(string result)
    {
        //If the locallibrary hasnt been made yet, do nothing
        if (local == null)
        {
            return;
        }
        // If it is the players turn and the incident popup is not active
        if (myTurn && IncidentPopup.activeSelf == false)
        {
            // Set the scanned value to the correct position
            int scan;
            int.TryParse(result, out scan);
            int scanPosition    = local.layout.list.IndexOf(scan.ToString());
            int currentPosition = local.players.list[local.turn].currentPosition;

            //Is it the players first turn?
            if (currentPosition == 31)
            {
                // set position and validate move
                currentPosition       = local.layout.list.IndexOf(scan.ToString());
                PlayerState.validMove = true;
            }
            //Has the player moved inccorect in a previous turn?
            else if (PlayerState.movedIncorrect)
            {
                //if the new scanned tile is correct with the position the player should be on
                // Show pop up and end
                if (scanPosition == currentPosition)
                {
                    popupText.text             = "Klaar met bewegen";
                    PlayerState.movedIncorrect = false;
                    PlayerState.validMove      = true;
                    endTurn();
                    return;
                }
            }
            //If player scanned a different tile
            //Calculate if its a valid move
            else if (currentPosition != scanPosition && PlayerState.energy > 0)
            {
                // if modulo 0 niet naar rechts
                if ((currentPosition + 1) % 6 != 0)
                {
                    if (currentPosition + 1 == scanPosition)
                    {
                        PlayerState.validMove = true;
                    }
                }
                if (currentPosition < 24)
                {
                    if (currentPosition + 6 == scanPosition)
                    {
                        PlayerState.validMove = true;
                    }
                }
                if ((currentPosition + 1) % 6 != 1)
                {
                    if (currentPosition - 1 == scanPosition)
                    {
                        PlayerState.validMove = true;
                    }
                }
                if (currentPosition > 5)
                {
                    if (currentPosition - 6 == scanPosition)
                    {
                        PlayerState.validMove = true;
                    }
                }
            }
            // If Player scanned the same tile where he already was at
            else if (currentPosition == scanPosition && PlayerState.energy > 0)
            {
                PlayerState.validMove = true;
            }
            // If the playe scanned a wrong tile
            // Show it to the player and set movedincorrect to false
            if (!PlayerState.validMove && PlayerState.energy > 0)
            {
                popupText.text             = "Ga terug naar je goede positie";
                PlayerState.movedIncorrect = true;
                // show return phone to old place dialogue
            }
            //If the player moved correctly, update energy and postiion
            else if (PlayerState.validMove && PlayerState.energy > 0)
            {
                // alter currenTile and energy
                local.players.list[local.turn].currentPosition = scanPosition;
                changeEnergy(-1);
                PlayerState.validMove = false;
                hasMoved = true;

                //Check if player encountered an incident
                // If so set the popup and randomise the new position of the incident
                foreach (Incident i in local.incidents.list)
                {
                    if (i.tile == local.players.list[local.turn].currentPosition)
                    {
                        encounteredIncident = i;

                        tempDialogue.title       = encounteredIncident.title;
                        tempDialogue.description = encounteredIncident.description;
                        tempDialogue.button      = encounteredIncident.button;
                        tempDialogue.image       = "Elephant";
                        togglePopUp();
                        int randomTile;
                        int.TryParse(UnityEngine.Random.Range(1f, 30f).ToString("0"), out randomTile);
                        i.tile = randomTile;
                    }
                }
                // If the player ran out of energy, show and end turn
                if (PlayerState.energy == 0)
                {
                    tempDialogue.title       = "Benzine op";
                    tempDialogue.description = "Oh nee, je brandstof is op.";
                    tempDialogue.button      = "Beeindig beurt";
                    tempDialogue.image       = "Elephant";
                    togglePopUp();
                }
                //If player has moved correctly, still has energy and didnt encounter an incident
                else
                {
                    popupText.text = local.players.list[local.turn].currentPosition.ToString();
                }
            }
        }
    }
Exemplo n.º 51
0
 public static Incident CreateIncident(long ID, global::System.Collections.ObjectModel.ObservableCollection<IncidentImpactedComponent> impactedComponents, global::System.Collections.ObjectModel.ObservableCollection<Mail2Bug.IcmOnCallApiODataReference.Microsoft.AzureAd.Icm.Types.Api.CustomFieldGroup> customFieldGroups, global::System.Collections.ObjectModel.ObservableCollection<ExternalAssociationTarget> externalIncidents)
 {
     Incident incident = new Incident();
     incident.Id = ID;
     if ((impactedComponents == null))
     {
         throw new global::System.ArgumentNullException("impactedComponents");
     }
     incident.ImpactedComponents = impactedComponents;
     if ((customFieldGroups == null))
     {
         throw new global::System.ArgumentNullException("customFieldGroups");
     }
     incident.CustomFieldGroups = customFieldGroups;
     if ((externalIncidents == null))
     {
         throw new global::System.ArgumentNullException("externalIncidents");
     }
     incident.ExternalIncidents = externalIncidents;
     return incident;
 }
Exemplo n.º 52
0
 /// <summary>
 /// There are no comments for Incident in the schema.
 /// </summary>
 public void AddToIncident(Incident incident)
 {
     base.AddObject("Incident", incident);
 }
Exemplo n.º 53
0
 public void IAdd(Incident incident)
 {
     db.Incident.Add(incident);
     db.SaveChanges();
 }
Exemplo n.º 54
0
        static void Main(string[] args)
        {
            int fin = 0;

            while (fin == 0)
            {
                Console.WriteLine("1- Avion");
                Console.WriteLine("2- Aeroport");
                Console.WriteLine("3- Client");
                Console.WriteLine("4- Baggage");
                Console.WriteLine("5- Billet");
                Console.WriteLine("6- Embarquement");
                Console.WriteLine("7- Employé");
                Console.WriteLine("8- Incident");
                Console.WriteLine("9- Maintenance");
                Console.WriteLine("10- Navigant");
                Console.WriteLine("11- Sol");
                Console.WriteLine("12- Tarif");
                Console.WriteLine("13- Vol");
                Console.WriteLine("14- Voyage");
                Console.WriteLine("0- Sortie");
                Console.WriteLine("Choisissez un élément dans la liste suivante :");
                string choix = Console.ReadLine();
                if (choix == "0")
                {
                    fin = 1;
                }
                if (choix == "1")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le modèle");
                        string modele = Console.ReadLine();
                        Console.WriteLine("Entrez la disponibilité (true/false)");
                        string disponible = Console.ReadLine();
                        Console.WriteLine("Entrez les places economique");
                        string Eco = Console.ReadLine();
                        Console.WriteLine("Entrez les places Premiere");
                        string Premiere = Console.ReadLine();
                        Console.WriteLine("Entrez les places Premium");
                        string Premium = Console.ReadLine();
                        Console.WriteLine("Entrez les places Business");
                        string Busi = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre d'équipage");
                        string equipage = Console.ReadLine();
                        Console.WriteLine("Entrez false si il n'a pas de proprietaire sinon True");
                        string proprietaire = Console.ReadLine();
                        Console.WriteLine("Entrez le code Aita de l'aeroport lié");
                        string Aita  = Console.ReadLine();
                        Avion  avion = new Avion()
                        {
                            Modele            = modele,
                            Disponible        = Convert.ToBoolean(disponible),
                            NbPlaceEconomique = Convert.ToInt32(Eco),
                            NbPlaceBusiness   = Convert.ToInt32(Busi),
                            NbPlacePremiere   = Convert.ToInt32(Premiere),
                            NbPlacePremium    = Convert.ToInt32(Premium),
                            NbPlaceEquipege   = Convert.ToInt32(equipage),
                            Proprietaire      = Convert.ToBoolean(proprietaire),
                            CodeAeroport      = Aita
                        };
                        db.Avions.Add(avion);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "2")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le code AITA");
                        string AITA = Console.ReadLine();
                        Console.WriteLine("Entrez le nom");
                        string nom = Console.ReadLine();
                        Console.WriteLine("Entrez l'adresse");
                        string adresse = Console.ReadLine();
                        Console.WriteLine("Entrez la ville");
                        string ville = Console.ReadLine();
                        Console.WriteLine("Entrez le pays");
                        string   pays     = Console.ReadLine();
                        Aeroport aeroport = new Aeroport()
                        {
                            CodeAITA = AITA,
                            Nom      = nom,
                            Adresse  = adresse,
                            Ville    = ville,
                            Pays     = pays,
                        };
                        db.Aeroports.Add(aeroport);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "3")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez votre prénom");
                        string prenom = Console.ReadLine();
                        Console.WriteLine("Entrez votre nom");
                        string nom = Console.ReadLine();
                        Console.WriteLine("Entrez votre date de naissance sous la forme 'aaaa-mm-jj'");
                        string datenaiss = Console.ReadLine();
                        Client client    = new Client()
                        {
                            Prenom    = prenom,
                            Nom       = nom,
                            DateNaiss = datenaiss
                        };
                        db.Clients.Add(client);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "4")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le poids");
                        string poids = Console.ReadLine();
                        Console.WriteLine("Entrez le tarrif");
                        string tarif = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du client");
                        string client = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du voyage");
                        string voyage = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du billet");
                        string billet = Console.ReadLine();

                        Baggage baggage = new Baggage()
                        {
                            Poids_Kg_ = Convert.ToDouble(poids),
                            Tarifs    = Convert.ToDecimal(tarif),
                            IdClient  = Convert.ToInt32(client),
                            IdVoyages = Convert.ToInt32(voyage),
                            IdBillet  = Convert.ToInt32(billet)
                        };
                        db.Baggages.Add(baggage);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "5")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez l'in du tarrif");
                        string tarif = Console.ReadLine();
                        Console.WriteLine("Entrez l'in du voyage");
                        string voyage = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du client");
                        string client = Console.ReadLine();
                        Console.WriteLine("Entrez le prix du billet a l'achat");
                        string prix = Console.ReadLine();
                        Console.WriteLine("Entrez false ou true si il y a une réduction ou non");
                        string reduction = Console.ReadLine();

                        Billet billet = new Billet()
                        {
                            IdTarifs         = Convert.ToInt32(tarif),
                            IdVoyages        = Convert.ToInt32(voyage),
                            IdClient         = Convert.ToInt32(client),
                            PrixPendantAchat = Convert.ToInt32(prix),
                            Reduction        = Convert.ToBoolean(reduction)
                        };
                        db.Billets.Add(billet);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "6")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez l'id du client");
                        string client = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du vol");
                        string vol = Console.ReadLine();


                        Embarquement embarquement = new Embarquement()
                        {
                            IdClient = Convert.ToInt32(client),
                            idVol    = Convert.ToInt32(vol),
                        };
                        db.Embarquements.Add(embarquement);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "7")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le nom");
                        string nom = Console.ReadLine();
                        Console.WriteLine("Entrez le prénom");
                        string prenom = Console.ReadLine();
                        Console.WriteLine("Entrez la date de naissance");
                        string datenaiss = Console.ReadLine();
                        Console.WriteLine("Entrez la date d'embauche");
                        string dateEmbauche = Console.ReadLine();
                        Console.WriteLine("Entrez false ou true si il possede le permis piste ou non");
                        string permis = Console.ReadLine();

                        Employe employe = new Employe()
                        {
                            Nom                 = nom,
                            Prenom              = prenom,
                            DateNaiss           = datenaiss,
                            DateEmbauche        = dateEmbauche,
                            PermisVehiculePiste = Convert.ToBoolean(permis)
                        };
                        db.Employes.Add(employe);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "8")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez l'indice de gravité (int)");
                        string gravite = Console.ReadLine();
                        Console.WriteLine("Entrez un commentaire");
                        string commentaire = Console.ReadLine();
                        Console.WriteLine("Entrez la date");
                        string date = Console.ReadLine();
                        Console.WriteLine("Entrez l'id de l'employé");
                        string employe = Console.ReadLine();
                        Console.WriteLine("Entrez l'id de l'avion");
                        string avion = Console.ReadLine();
                        Console.WriteLine("Entrez l'id de la maintenance");
                        string maintenance = Console.ReadLine();

                        Incident incident = new Incident()
                        {
                            IndiceGravite = Convert.ToInt32(gravite),
                            Commentaire   = commentaire,
                            Date          = Convert.ToDateTime(date),
                            idEmploye     = Convert.ToInt32(employe),
                            idAvion       = Convert.ToInt32(avion),
                            IdMaintenance = Convert.ToInt32(maintenance)
                        };
                        db.Incidents.Add(incident);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "9")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le nom du chef d'équipe");
                        string nom = Console.ReadLine();
                        Console.WriteLine("Entrez l'id d'un employé");
                        string employe = Console.ReadLine();
                        Console.WriteLine("Entrez la date du début prevu");
                        string debutprevu = Console.ReadLine();
                        Console.WriteLine("Entrez la date de fin prevu");
                        string finprevu = Console.ReadLine();
                        Console.WriteLine("Entrez la date du début reel");
                        string debutreel = Console.ReadLine();
                        Console.WriteLine("Entrez la date de fin reel");
                        string finreele = Console.ReadLine();


                        Maintenance maintenance = new Maintenance()
                        {
                            NomChefEquipe   = nom,
                            idEmployee      = Convert.ToInt32(employe),
                            DateDebutPrevue = Convert.ToDateTime(debutprevu),
                            DateFinPrevue   = Convert.ToDateTime(finprevu),
                            DateDebutReelle = Convert.ToDateTime(debutreel),
                            DateFinReelle   = Convert.ToDateTime(finreele),
                        };
                        db.Maintenances.Add(maintenance);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "10")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le nom du poste");
                        string nomPoste = Console.ReadLine();
                        Console.WriteLine("Entrez true/false si il y a un pilote");
                        string pilote = Console.ReadLine();
                        Console.WriteLine("Entrez true/false si il y a un co-pilote");
                        string coPilote = Console.ReadLine();
                        Console.WriteLine("Entrez true/false si il y a une hotesse");
                        string hotesse = Console.ReadLine();


                        Naviguant naviguant = new Naviguant()
                        {
                            NomPoste = nomPoste,
                            Pilote   = Convert.ToBoolean(pilote),
                            CoPilote = Convert.ToBoolean(coPilote),
                            Hotesse  = Convert.ToBoolean(hotesse),
                        };
                        db.Naviguants.Add(naviguant);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "11")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le nom du poste");
                        string nomPoste = Console.ReadLine();
                        Console.WriteLine("Entrez le code AITA de l'aeroport");
                        string Aita = Console.ReadLine();



                        Sol sol = new Sol()
                        {
                            NomPoste     = nomPoste,
                            CodeAeroport = Aita,
                        };
                        db.Sols.Add(sol);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "12")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le type de tarif");
                        string typetarif = Console.ReadLine();
                        Console.WriteLine("Entrez la classe");
                        string classe = Console.ReadLine();
                        Console.WriteLine("Entrez le prix");
                        string prix = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du voyage");
                        string voyage = Console.ReadLine();



                        Tarif tarif = new Tarif()
                        {
                            TypeTarif = typetarif,
                            Classe    = classe,
                            Prix      = Convert.ToInt32(prix),
                            IdVoyages = Convert.ToInt32(voyage),
                        };
                        db.Tarifs.Add(tarif);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "13")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le code de l'aeroport de depart");
                        string aeroportdepart = Console.ReadLine();
                        Console.WriteLine("Entrez le code de l'aeroport d'arrivee prevu");
                        string aeroportarriveeprevu = Console.ReadLine();
                        Console.WriteLine("Entrez le code de l'aeroport d'arrivee reel");
                        string aeroportarriveereel = Console.ReadLine();
                        Console.WriteLine("Entrez la date de depart prevu");
                        string datedepartprevu = Console.ReadLine();
                        Console.WriteLine("Entrez la date de depart reele");
                        string departreel = Console.ReadLine();
                        Console.WriteLine("Entrez la date d'arrivee prevu");
                        string arriveeprevu = Console.ReadLine();
                        Console.WriteLine("Entrez la date d'arrivee reele");
                        string arriveereele = Console.ReadLine();
                        Console.WriteLine("Entrez la reference de la ligne");
                        string reference = Console.ReadLine();
                        Console.WriteLine("Entrez la reference du vol");
                        string referenceVol = Console.ReadLine();
                        Console.WriteLine("Entrez la distance");
                        string distance = Console.ReadLine();
                        Console.WriteLine("Entrez le temps de vol prévu");
                        string volprevu = Console.ReadLine();
                        Console.WriteLine("Entrez le temps de vol réel");
                        string volreel = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre d'employé");
                        string nbemploye = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre de place restante");
                        string nbplacerestante = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre de place restante business");
                        string nbplacebusi = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre de place restante premiere");
                        string placePremiere = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre de place restante economique");
                        string placeEco = Console.ReadLine();
                        Console.WriteLine("Entrez le nombre de place restante premium");
                        string placePremium = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du pilote");
                        string pilote = Console.ReadLine();
                        Console.WriteLine("Entrez l'id du co-pilote");
                        string copilote = Console.ReadLine();
                        Console.WriteLine("Entrez l'id due l'hotesse");
                        string hotesse = Console.ReadLine();


                        Vol vol = new Vol()
                        {
                            AeroportDepart        = aeroportdepart,
                            AeroportArriveePrevue = aeroportarriveeprevu,
                            AeroportArriveeReel   = aeroportarriveereel,
                            DateDepartPrevue      = Convert.ToDateTime(datedepartprevu),
                            DateDepartReel        = Convert.ToDateTime(departreel),
                            DateArriveePrevue     = Convert.ToDateTime(arriveeprevu),
                            DateArriveeReel       = Convert.ToDateTime(arriveereele),
                            ReferenceLigne        = reference,
                            ReferenceVol          = referenceVol,
                            Distance = distance,
                            TempsVolPrevue_heure_     = volprevu.ParseTime(),
                            TempsVolReel_heure_       = volreel.ParseTime(),
                            nbEmployee                = Convert.ToInt32(nbemploye),
                            NbPlaceRestante           = Convert.ToInt32(nbplacerestante),
                            NbPlaceRestanteBusiness   = Convert.ToInt32(nbplacebusi),
                            NbPlaceRestanteEconomique = Convert.ToInt32(placeEco),
                            NbPlaceRestantePremiere   = Convert.ToInt32(placePremiere),
                            NbPlaceRestantePremium    = Convert.ToInt32(placePremium),
                            idPilote   = Convert.ToInt32(pilote),
                            idCopilote = Convert.ToInt32(copilote),
                            idHotesse  = Convert.ToInt32(hotesse),
                        };
                        db.Vols.Add(vol);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
                if (choix == "14")
                {
                    using (var db = new ProjetBDD2Entities())
                    {
                        Console.WriteLine("Entrez le nom du voyage");
                        string nom = Console.ReadLine();
                        Console.WriteLine("Entrez l'id de l'avion");
                        string avion = Console.ReadLine();



                        Voyage voyage = new Voyage()
                        {
                            Nom      = nom,
                            IdAvions = Convert.ToInt32(avion)
                        };
                        db.Voyages.Add(voyage);
                        db.SaveChanges();
                        Console.WriteLine("Ajout pris en compte !");

                        Console.ReadKey();
                        Console.Clear();
                    }
                }
            }
        }
Exemplo n.º 55
0
        public Incident CloseIncident([FromBody] Incident incident)
        {
            var exisitingIncident = _context.Incidents.FirstOrDefault(x => x.ID == incident.ID);

            exisitingIncident.CreationTime = DateTimeOffset.UtcNow;
            exisitingIncident.Status       = "Inaktiv";

            var existingVehicles = new List <Vehicle>();

            foreach (var item in incident.Preparednesses)
            {
                var vehicle = _context.Vehicles.Include(s => s.Status).FirstOrDefault(x => x.ID == item.Vehicle.ID);
                existingVehicles.Add(vehicle);
            }

            var status = new Status();

            status.ID = 3;

            var existingStatus = _context.Status.FirstOrDefault(x => x.ID == status.ID);

            foreach (var item2 in existingVehicles)
            {
                item2.Status = existingStatus;
            }

            var existingPreparednesses = _context.Preparednesses.Where(x => x.Incident.ID == incident.ID).Where(x => x.Status == "Aktiv").ToList();

            foreach (var item3 in existingPreparednesses)
            {
                item3.Status = "Inaktiv";
            }

            var existingJournals = _context.Journals.Where(x => x.Incident.ID == incident.ID).Where(x => x.Status == "Aktiv").ToList();

            foreach (var journal in existingJournals)
            {
                journal.Status = "Inaktiv";
            }

            var logger = new Logger();

            logger.Incident = incident;
            logger.Time     = DateTimeOffset.UtcNow;

            var closedIncident = iParser.CloseIncident(incident);

            logger.LogMessage = closedIncident.Item1;
            logger.Success    = closedIncident.Item2;

            _context.Loggers.Add(logger);

            _context.SaveChanges();

            incident.Loggers = new List <Logger>();
            incident.Loggers.Add(logger);

            incident.Loggers = null;

            _messageHubContext.Clients.All.InvokeAsync("IncidentClosed");

            _messageHubContext.Clients.All.InvokeAsync("ClearAllAfterClose");

            return(incident);
        }
        public void When_filtering_by_an_enum_attribute_and_using_proxy_types_right_result_is_returned()
        {
            var fakedContext = new XrmFakedContext { };

            var entityAccount = new Account { Id = Guid.NewGuid(), Name = "Test Account", LogicalName = "account" };
            var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference(), EMailAddress1 = "*****@*****.**" };

            var entityCase = new Incident
            {
                Id = Guid.NewGuid(),
                PrimaryContactId = entityContact.ToEntityReference(),
                CustomerId = entityAccount.ToEntityReference(),
                Title = "Unit Test Case"
            };

            entityCase["statecode"] = new OptionSetValue((int) IncidentState.Active);

            fakedContext.Initialize(new List<Entity>() {
               entityAccount,entityContact, entityCase
            });


            var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' >
              <entity name='incident' >
                <attribute name='incidentid' />
                <attribute name='statecode' /> 
                <order attribute='createdon' descending='true' /> 
                 <filter type='and' > 
                  <condition attribute='statecode' operator='neq' value='2' /> 
                </filter>
              </entity>
            </fetch>";

            var rows = fakedContext.GetFakedOrganizationService().RetrieveMultiple(new FetchExpression(fetchXml));
            Assert.Equal(rows.Entities.Count, 1);

        }
            public async Task CreatesParsedIncidents()
            {
                var firstIncident = new Incident()
                {
                    CreateDate = Cursor + TimeSpan.FromMinutes(1),
                    Source     = new IncidentSourceData {
                        CreateDate = Cursor + TimeSpan.FromMinutes(5)
                    }
                };

                var secondIncident = new Incident()
                {
                    CreateDate = Cursor + TimeSpan.FromMinutes(2),
                    Source     = new IncidentSourceData {
                        CreateDate = Cursor + TimeSpan.FromMinutes(6)
                    }
                };

                var thirdIncident = new Incident()
                {
                    CreateDate = Cursor + TimeSpan.FromMinutes(3),
                    Source     = new IncidentSourceData {
                        CreateDate = Cursor + TimeSpan.FromMinutes(4)
                    }
                };

                var incidents = new[] { firstIncident, secondIncident, thirdIncident };

                SetupClientQuery(
                    Cursor,
                    incidents);

                var firstFirstParsedIncident   = new ParsedIncident(firstIncident, "", ComponentStatus.Up);
                var firstSecondParsedIncident  = new ParsedIncident(firstIncident, "", ComponentStatus.Up);
                var secondFirstParsedIncident  = new ParsedIncident(secondIncident, "", ComponentStatus.Up);
                var secondSecondParsedIncident = new ParsedIncident(secondIncident, "", ComponentStatus.Up);
                var thirdParsedIncident        = new ParsedIncident(thirdIncident, "", ComponentStatus.Up);

                Parser
                .Setup(x => x.ParseIncident(firstIncident))
                .Returns(new[] { firstFirstParsedIncident, firstSecondParsedIncident });

                Parser
                .Setup(x => x.ParseIncident(secondIncident))
                .Returns(new[] { secondFirstParsedIncident, secondSecondParsedIncident });

                Parser
                .Setup(x => x.ParseIncident(thirdIncident))
                .Returns(new[] { thirdParsedIncident });

                var lastCreateDate = DateTime.MinValue;

                Factory
                .Setup(x => x.CreateAsync(It.IsAny <ParsedIncident>()))
                .ReturnsAsync(new IncidentEntity())
                .Callback <ParsedIncident>(incident =>
                {
                    var nextCreateDate = incident.StartTime;
                    Assert.True(nextCreateDate >= lastCreateDate);
                    lastCreateDate = nextCreateDate;
                });

                var result = await Processor.FetchSince(Cursor);

                Assert.Equal(incidents.Max(i => i.CreateDate), result);

                Factory
                .Verify(
                    x => x.CreateAsync(firstFirstParsedIncident),
                    Times.Once());

                Factory
                .Verify(
                    x => x.CreateAsync(secondFirstParsedIncident),
                    Times.Once());
            }
Exemplo n.º 58
0
        internal void MarkFileImported(ImportFile importFile)
        {
            int          id     = importFile.FileId;
            IFAttachInc2 attach = null;

            if (null != _Incident && null != _Incident.FAttach2)
            {
                foreach (var f in _Incident.FAttach2)
                {
                    if (f.ID == id)
                    {
                        attach = f;
                        break;
                    }
                }
            }
            if (null == attach)
            {
                return;
            }
            // update the description of an incident's attachment
            Incident incident = new Incident();

            incident.ID             = new ID();
            incident.ID.id          = _Incident.ID;
            incident.ID.idSpecified = true;
            FileAttachmentIncident file = new FileAttachmentIncident();

            file.ID               = new ID();
            file.ID.id            = id;
            file.ID.idSpecified   = true;
            file.action           = ActionEnum.update;
            file.actionSpecified  = true;
            file.Private          = attach.Private;
            file.PrivateSpecified = true;
            bool updated;

            switch (importFile.StatusCode)
            {
            case 70:
            case 75:
                file.Description = importFile.Description + string.Format("{{{0:00}}}", importFile.StatusCode);
                updated          = true;
                break;

            default:
                updated = false;
                break;
            }
            if (updated)
            {
                incident.FileAttachments = new FileAttachmentIncident[1] {
                    file
                };
                try
                {
                    _rnSrv.updateObject(new RNObject[1] {
                        incident
                    });
                }
                catch (Exception ex)
                {
                    _Model._Proxy.NoticeLog(String.Format("EBS Bulk Import failed to update the description of file {0}, id {1}",
                                                          importFile.Name, id), ex.Message);
                }
            }
        }
Exemplo n.º 59
0
 public IncidentUpdate(Incident incident) : base(incident)
 {
 }
Exemplo n.º 60
0
    /// <summary>
    /// Called when the button in incidentPopUp is pressed.
    /// </summary>
    public void popUpBtn()
    {
        //If the game was won or lost
        if (tempDialogue.image == "Treasure" || tempDialogue.image == "TreasureL")
        {
            SceneManager.LoadScene("main");
        }
        //If an incident was encountered
        else if (encounteredIncident != null)
        {
            //Based on the incidents action, do something
            switch (encounteredIncident.action)
            {
            /* case "CornerNE":
             *   local.players.list[currentTurn].currentPosition = 5;
             *   PlayerState.movedIncorrect = true;
             *   break;
             * case "CornerNW":
             *   local.players.list[currentTurn].currentPosition = 0;
             *   PlayerState.movedIncorrect = true;
             *   break;
             * case "CornerSE":
             *   local.players.list[currentTurn].currentPosition = 29;
             *   PlayerState.movedIncorrect = true;
             *   break;
             * case "CornerSW":
             *   local.players.list[currentTurn].currentPosition = 24;
             *   PlayerState.movedIncorrect = true;
             *   break;*/
            case "Energy-1":
                changeEnergy(-1);
                break;

            case "Energy-2":
                changeEnergy(-2);
                break;

            case "Energy-3":
                changeEnergy(-3);
                break;

            case "Energy+3":
                changeEnergy(3);
                break;
            }
            //If player may continue after incident
            if (encounteredIncident.action == "Energy+3" || encounteredIncident.action.Contains("Corner"))
            {
                IncidentPopup.SetActive(false);
            }
            //If player has to end turn after incident
            else
            {
                endTurn();
            }
            encounteredIncident = null;
        }
        //If a quest was encountered
        else if (tempQuest != null)
        {
            IncidentPopup.SetActive(false);
            advanceProgress();
            endTurn();
        }
        //If the player ran out of energy
        else if (PlayerState.energy == 0)
        {
            endTurn();
        }
    }