Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["DOC_ID"]))
                {
                    string  document_id = Request.QueryString["DOC_ID"];
                    decimal doc_id      = decimal.Parse(document_id);
                    VIDEO   v           = MediaVideoMgr.SelectVideoById(doc_id);

                    List <SETTINGS> sets               = SQMSettings.SelectSettingsGroup("MEDIA_UPLOAD", "");
                    string          storageContainer   = sets.Find(x => x.SETTING_CD == "STORAGE_CONTAINER").VALUE.ToString();
                    string          storageURL         = sets.Find(x => x.SETTING_CD == "STORAGE_URL").VALUE.ToString();
                    string          storageQueryString = sets.Find(x => x.SETTING_CD == "STORAGE_QUERY").VALUE.ToString();

                    int    index    = v.FILE_NAME.ToString().IndexOf(".");
                    string fileType = v.FILE_NAME.Substring(index);
                    string videoSrc = storageURL + storageContainer + "/" + v.VIDEO_ID.ToString() + fileType + storageQueryString;
                    srcControl.Attributes.Add("src", videoSrc);

                    if (fileType.ToLower().Equals(".mp4"))
                    {
                        srcControl.Attributes.Add("type", "video/mp4");
                    }
                }
            }
            catch (Exception ex)
            {
                //
                Response.Write("Unable to stream video: " + ex.Message.ToString()); Response.End();
            }
        }
Exemple #2
0
        static void Main(string[] args)
        {
            output = new StringBuilder();
            plantDataMultiplier = 1.0;

            WriteLine("Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            entities = new PSsqmEntities();

            sets           = SQMSettings.SelectSettingsGroup("FILE_UPLOAD", "");
            primaryCompany = Convert.ToInt32(sets.Find(x => x.SETTING_CD == "CompanyID").VALUE);
            fileDelimiter  = sets.Find(x => x.SETTING_CD == "FileDelimiter1").VALUE.ToCharArray();
            sets           = SQMSettings.SelectSettingsGroup("AUTOMATE", "");

            try
            {
                // arguments:
                // no arguments supplied == process all files
                // ref == import references files only
                // person == import person files only

                if (args.Length == 0 || args.Contains("ref"))
                {
                    // Process resource file
                    ProcessFile("Reference");
                }
            }
            catch (Exception ex)
            {
                WriteLine("Error Processing Reference File: " + ex.ToString());
            }

            try
            {
                if (args.Length == 0 || args.Contains("person"))
                {
                    // Process Person Input file from PeopleSoft
                    ProcessFile("Person");
                }
            }
            catch (Exception ex)
            {
                WriteLine("Error Processing Person File: " + ex.ToString());
            }


            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            WriteLogFile();
        }
Exemple #3
0
        static string ProcessEHSData()
        {
            string nextStep = "";

            WriteLine("EHSDATA Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "TASK");            // ABW 20140805

            try
            {
                using (var entities = new PSsqmEntities())
                {
                    long     updateIndicator = DateTime.UtcNow.Ticks;
                    SETTINGS setting         = null;

                    // get any AUTOMATE settings
                    sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "TASK");

                    DateTime rollupFromDate = DateTime.UtcNow.AddMonths(-11);                           // this should be a setting
                    // set end date to end of current month to clear spurrious entries ?
                    DateTime rollupToDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month));

                    /*
                     * int rollupMonthsAhead = 0;
                     * setting = sets.Where(x => x.SETTING_CD == "ROLLUP_MONTHS_AHEAD").FirstOrDefault();
                     * if (setting != null && !string.IsNullOrEmpty(setting.VALUE))
                     * {
                     *      int.TryParse(setting.VALUE, out rollupMonthsAhead);
                     *      rollupToDate = rollupToDate.AddMonths(rollupMonthsAhead);
                     * }
                     */

                    List <EHS_MEASURE> measureList = (from m in entities.EHS_MEASURE select m).ToList();

                    decimal plantManagerAuditsMeasureID        = measureList.First(m => m.MEASURE_CD == "S30003").MEASURE_ID;
                    decimal ehsAuditsMeasureID                 = measureList.First(m => m.MEASURE_CD == "S30001").MEASURE_ID;
                    decimal supervisorAuditsMeasureID          = measureList.First(m => m.MEASURE_CD == "S30002").MEASURE_ID;
                    decimal plantManagerAuditsCreatedMeasureID = measureList.First(m => m.MEASURE_CD == "S3C003").MEASURE_ID;
                    decimal ehsAuditsCreatedMeasureID          = measureList.First(m => m.MEASURE_CD == "S3C001").MEASURE_ID;
                    decimal supervisorAuditsCreatedMeasureID   = measureList.First(m => m.MEASURE_CD == "S3C002").MEASURE_ID;
                    decimal allAuditsCreatedMeasureID          = measureList.FirstOrDefault(m => m.MEASURE_CD == "S3C000").MEASURE_ID;
                    var     auditDailyMeasureIDs               = new List <decimal>()
                    {
                        plantManagerAuditsMeasureID,
                        ehsAuditsMeasureID,
                        supervisorAuditsMeasureID,
                    };
                    var auditMonthlyMeasureIDs = new List <decimal>()
                    {
                        plantManagerAuditsCreatedMeasureID,
                        ehsAuditsCreatedMeasureID,
                        supervisorAuditsCreatedMeasureID,
                        allAuditsCreatedMeasureID
                    };


                    decimal nearMissMeasureID            = measureList.First(m => m.MEASURE_CD == "S20002").MEASURE_ID;
                    decimal firstAidMeasureID            = measureList.First(m => m.MEASURE_CD == "S20003").MEASURE_ID;
                    decimal recordableMeasureID          = measureList.First(m => m.MEASURE_CD == "S20004").MEASURE_ID;
                    decimal lostTimeCaseMeasureID        = measureList.First(m => m.MEASURE_CD == "S20005").MEASURE_ID;
                    decimal fatalityMeasureID            = measureList.First(m => m.MEASURE_CD == "S20006").MEASURE_ID;
                    decimal otherIncidentsID             = measureList.First(m => m.MEASURE_CD == "S20001").MEASURE_ID;
                    decimal closedInvestigationMeasureID = measureList.First(m => m.MEASURE_CD == "S20007").MEASURE_ID;
                    var     incidentMeasureIDs           = new List <decimal>()
                    {
                        nearMissMeasureID,
                        firstAidMeasureID,
                        recordableMeasureID,
                        lostTimeCaseMeasureID,
                        fatalityMeasureID,
                        otherIncidentsID,
                        closedInvestigationMeasureID
                    };

                    decimal timeLostMeasureID         = entities.EHS_MEASURE.First(m => m.MEASURE_CD == "S60001").MEASURE_ID;
                    decimal timeRestrictedMeasureID   = entities.EHS_MEASURE.First(m => m.MEASURE_CD == "S60003").MEASURE_ID;
                    var     incidentMonthlyMeasureIDs = new List <decimal>()
                    {
                        timeLostMeasureID,
                        timeRestrictedMeasureID
                    };

                    decimal injuryIllnessIssueTypeID = entities.INCIDENT_TYPE.First(i => i.TITLE == "Injury/Illness").INCIDENT_TYPE_ID;
                    decimal nearMissIssueTypeID      = entities.INCIDENT_TYPE.First(i => i.TITLE == "Near Miss").INCIDENT_TYPE_ID;


                    List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0).Where(l => l.STATUS == "A").ToList();
                    PLANT_ACTIVE pact      = null;

                    var createdAudits = (from a in entities.AUDIT where a.AUDIT_DT >= rollupFromDate && new decimal[3] {
                        1, 2, 3
                    }.Contains(a.AUDIT_TYPE_ID) select a).ToList();
                    //var incidents = (from i in entities.INCIDENT where i.INCIDENT_DT >= rollupFromDate && (i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID || i.ISSUE_TYPE_ID == nearMissIssueTypeID) select i).ToList();
                    var incidents = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS") where i.INCIDENT_DT >= rollupFromDate && (i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID || i.ISSUE_TYPE_ID == nearMissIssueTypeID) select i).ToList();

                    // AUDITS
                    foreach (var plant in plantList)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.Audit select a).SingleOrDefault();
                        if (pact != null && pact.EFF_START_DATE.HasValue)                               // plant is active
                        {
                            var auditsForPlant = createdAudits.Where(a => a.DETECT_PLANT_ID == plant.PLANT_ID && a.CURRENT_STATUS != "I");

                            // new timespan logic
                            DateTime fromDate = rollupFromDate > (DateTime)pact.EFF_START_DATE ? rollupFromDate : (DateTime)pact.EFF_START_DATE;
                            DateTime toDate   = pact.EFF_END_DATE.HasValue && (DateTime)pact.EFF_END_DATE < rollupToDate ? (DateTime)pact.EFF_END_DATE : rollupToDate;

                            WriteLine("AUDIT Rollup For Plant " + pact.PLANT_ID + "  from date = " + fromDate.ToShortDateString() + "  to date = " + toDate.ToShortDateString());

                            // loop by month to get audits created for month and then by day to calculate completions
                            for (DateTime dt = fromDate; dt <= toDate; dt = dt.AddMonths(1))
                            {
                                int plantManagerAuditsCreatedMonth = 0;
                                int ehsAuditsCreatedMonth          = 0;
                                int supervisorAuditsCreatedMonth   = 0;
                                int auditsCreatedMonth             = 0;

                                for (var currDate = new System.DateTime(dt.Year, dt.Month, 1); currDate <= new System.DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month)); currDate = currDate.AddDays(1))
                                {
                                    int plantManagerAudits = 0;
                                    int ehsAudits          = 0;
                                    int supervisorAudits   = 0;

                                    // fetch audits scheduled for this day
                                    var auditsForDay = auditsForPlant.Where(a => TruncateTime(a.AUDIT_DT) == currDate.Date);
                                    if (auditsForDay.Any())
                                    {
                                        auditsCreatedMonth             += auditsForDay.Count();
                                        plantManagerAuditsCreatedMonth += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 1);
                                        ehsAuditsCreatedMonth          += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 2);
                                        supervisorAuditsCreatedMonth   += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 3);
                                    }
                                    // get audits scheduled for this day that have been completed
                                    var closedAuditsForDay = auditsForDay.Where(a => a.CLOSE_DATE_DATA_COMPLETE != null);
                                    if (closedAuditsForDay.Any())
                                    {
                                        plantManagerAudits = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 1);
                                        ehsAudits          = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 2);
                                        supervisorAudits   = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 3);
                                    }

                                    var dailyData = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, auditDailyMeasureIDs, true, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, plantManagerAuditsMeasureID, plantManagerAudits, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, ehsAuditsMeasureID, ehsAudits, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, supervisorAuditsMeasureID, supervisorAudits, updateIndicator);
                                    foreach (var data in dailyData)
                                    {
                                        if (data.EntityState == EntityState.Detached && data.VALUE != 0)
                                        {
                                            entities.EHS_DATA.AddObject(data);
                                        }
                                        else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                        {
                                            entities.DeleteObject(data);
                                        }
                                    }
                                }

                                var monthlyData = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, new DateTime(dt.Year, dt.Month, 1), auditMonthlyMeasureIDs, true, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, plantManagerAuditsCreatedMeasureID, plantManagerAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, supervisorAuditsCreatedMeasureID, supervisorAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, ehsAuditsCreatedMeasureID, ehsAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, allAuditsCreatedMeasureID, auditsCreatedMonth, updateIndicator);
                                foreach (var data in monthlyData)
                                {
                                    if (data.EntityState == EntityState.Detached && data.VALUE != 0)
                                    {
                                        entities.EHS_DATA.AddObject(data);
                                    }
                                    else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                    {
                                        entities.DeleteObject(data);
                                    }
                                }

                                entities.SaveChanges();
                            }
                        }
                        entities.SaveChanges();
                    }

                    // INCIDENTS
                    foreach (var plant in plantList)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                        if (pact != null && pact.EFF_START_DATE.HasValue)                               // plant is active
                        {
                            var incidentsForPlant = incidents.Where(i => i.DETECT_PLANT_ID == plant.PLANT_ID);
                            //var minDate = new[] { pact.EFF_START_DATE, incidentsForPlant.Min(i => (DateTime?)i.INCIDENT_DT) }.Max();
                            //var maxDate = new[] { pact.EFF_END_DATE, incidentsForPlant.Max(i => (DateTime?)i.INCIDENT_DT) }.Min();
                            // new timespan logic
                            DateTime fromDate = rollupFromDate > (DateTime)pact.EFF_START_DATE ? rollupFromDate : (DateTime)pact.EFF_START_DATE;
                            DateTime toDate   = pact.EFF_END_DATE.HasValue && (DateTime)pact.EFF_END_DATE < rollupToDate ? (DateTime)pact.EFF_END_DATE : rollupToDate;

                            WriteLine("INCIDENT Rollup For Plant " + pact.PLANT_ID + "  from date = " + fromDate.ToShortDateString() + "  to date = " + toDate.ToShortDateString());

                            for (var currDate = fromDate; currDate <= toDate; currDate = currDate.AddDays(1))
                            {
                                int nearMisses           = 0;
                                int firstAidCases        = 0;
                                int recordables          = 0;
                                int lostTimeCases        = 0;
                                int fatalities           = 0;
                                int otherIncidents       = 0;
                                int closedInvestigations = 0;

                                var firstAidOrdinals = new Dictionary <string, Dictionary <string, int> >()
                                {
                                    { "type", null },
                                    { "bodyPart", null },
                                    { "rootCause", null },
                                    { "tenure", null },
                                    { "daysToClose", null }
                                };
                                var recordableOrdinals = new Dictionary <string, Dictionary <string, int> >()
                                {
                                    { "type", null },
                                    { "bodyPart", null },
                                    { "rootCause", null },
                                    { "tenure", null },
                                    { "daysToClose", null }
                                };

                                var incidentsForDay = incidentsForPlant.Where(i => TruncateTime(i.INCIDENT_DT) == currDate.Date);
                                //if (incidentsForDay.Any())
                                if (incidentsForDay.Count() > 0)
                                {
                                    var firstAidIncidents   = incidentsForDay.Where(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FIRST_AID);
                                    var recordableIncidents = incidentsForDay.Where(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.RECORDABLE);
                                    otherIncidents = incidentsForDay.Where(i => i.ISSUE_TYPE_ID != injuryIllnessIssueTypeID).Count();
                                    // Basic data
                                    nearMisses    = incidentsForDay.Count(i => i.ISSUE_TYPE_ID == nearMissIssueTypeID);
                                    firstAidCases = firstAidIncidents.Count();
                                    recordables   = recordableIncidents.Count();
                                    lostTimeCases = incidentsForDay.Count(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.LOST_TIME);
                                    fatalities    = incidentsForDay.Count(i =>
                                                                          i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FATALITY.HasValue && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FATALITY.Value);
                                    closedInvestigations = incidentsForDay.Count(i => i.CLOSE_DATE.HasValue);

                                    // First Aid ordinals
                                    // check which ordinal data we wish to capture
                                    SETTINGS setFirstAid = sets.Where(s => s.SETTING_CD == "FIRSTAID-ORDINALS").FirstOrDefault();
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("type"))
                                    {
                                        firstAidOrdinals["type"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_TYPE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("bodyPart"))
                                    {
                                        firstAidOrdinals["bodyPart"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_BODY_PART).ToDictionary(b => b.Key ?? "", b => b.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("rootCause"))
                                    {
                                        firstAidOrdinals["rootCause"] = firstAidIncidents.SelectMany(i => i.INCFORM_CAUSATION).GroupBy(c => c.CAUSEATION_CD).ToDictionary(c =>
                                                                                                                                                                          c.Key ?? "", c => c.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("tenure"))
                                    {
                                        firstAidOrdinals["tenure"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.JOB_TENURE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("daysToClose"))
                                    {
                                        firstAidOrdinals["daysToClose"] = firstAidIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                                                                                                                     ((TimeSpan)(i.INCIDENT_DT - i.CLOSE_DATE)).Days).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                                                                                                                                                                                                                                   (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                                                                                                                                                                                                                                                                                                                                                                             x.Key ?? "", x => x.Count());

                                        /*
                                         * firstAidOrdinals["daysToClose"] = firstAidIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                         * EntityFunctions.DiffDays(i.INCIDENT_DT, i.CLOSE_DATE)).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                         * (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                         * x.Key ?? "", x => x.Count());
                                         */
                                    }

                                    // Recordable ordinals
                                    // check which ordinal data we wish to capture
                                    SETTINGS setRecordable = sets.Where(s => s.SETTING_CD == "RECORDABLE-ORDINALS").FirstOrDefault();
                                    if (setRecordable != null && setRecordable.VALUE.Contains("type"))
                                    {
                                        recordableOrdinals["type"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_TYPE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("bodyPart"))
                                    {
                                        recordableOrdinals["bodyPart"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_BODY_PART).ToDictionary(b => b.Key ?? "", b => b.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("rootCause"))
                                    {
                                        recordableOrdinals["rootCause"] = recordableIncidents.SelectMany(i => i.INCFORM_CAUSATION).GroupBy(c => c.CAUSEATION_CD).ToDictionary(c =>
                                                                                                                                                                              c.Key ?? "", c => c.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("tenure"))
                                    {
                                        recordableOrdinals["tenure"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.JOB_TENURE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("daysToClose"))
                                    {
                                        recordableOrdinals["daysToClose"] = recordableIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                                                                                                                         ((TimeSpan)(i.INCIDENT_DT - i.CLOSE_DATE)).Days).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                                                                                                                                                                                                                                       (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                                                                                                                                                                                                                                                                                                                                                                                 x.Key ?? "", x => x.Count());

                                        /*
                                         *                                                                              recordableOrdinals["daysToClose"] = recordableIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                         * EntityFunctions.DiffDays(i.INCIDENT_DT, i.CLOSE_DATE)).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                         * (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                         * x.Key ?? "", x => x.Count());
                                         */
                                    }
                                }

                                var dataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMeasureIDs, true, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, nearMissMeasureID, nearMisses, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, firstAidMeasureID, firstAidCases, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, recordableMeasureID, recordables, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, lostTimeCaseMeasureID, lostTimeCases, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, fatalityMeasureID, fatalities, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, otherIncidentsID, otherIncidents, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, closedInvestigationMeasureID, closedInvestigations, updateIndicator);
                                foreach (var data in dataList)
                                {
                                    if (data.VALUE != 0)
                                    {
                                        if (data.EntityState == EntityState.Detached)
                                        {
                                            entities.EHS_DATA.AddObject(data);
                                        }
                                        if (incidentsForDay.Any())
                                        {
                                            if (data.MEASURE_ID == firstAidMeasureID)
                                            {
                                                UpdateOrdinalData(entities, data, firstAidOrdinals);
                                            }
                                            else if (data.MEASURE_ID == recordableMeasureID)
                                            {
                                                UpdateOrdinalData(entities, data, recordableOrdinals);
                                            }
                                        }
                                    }
                                    else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                    {
                                        if (data.MEASURE_ID == firstAidMeasureID)
                                        {
                                            foreach (var key in firstAidOrdinals.Keys.ToArray())
                                            {
                                                firstAidOrdinals[key] = new Dictionary <string, int>();
                                            }
                                            UpdateOrdinalData(entities, data, firstAidOrdinals);
                                        }
                                        else if (data.MEASURE_ID == recordableMeasureID)
                                        {
                                            foreach (var key in recordableOrdinals.Keys.ToArray())
                                            {
                                                recordableOrdinals[key] = new Dictionary <string, int>();
                                            }
                                            UpdateOrdinalData(entities, data, recordableOrdinals);
                                        }
                                        entities.DeleteObject(data);
                                    }
                                }
                            }

                            // MONTHLY INCIDENTS (from PLANT_ACCOUNTING)
                            var             accountingForPlant = entities.PLANT_ACCOUNTING.Where(a => a.PLANT_ID == plant.PLANT_ID);
                            List <EHS_DATA> ehsdataList;

                            for (var currDate = fromDate; currDate <= toDate; currDate = currDate.AddDays(1))
                            {
                                decimal timeLost       = 0;
                                decimal timeRestricted = 0;

                                if (currDate.Day == 1)
                                {
                                    // get or create data records for the 1st day of the month
                                    ehsdataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMonthlyMeasureIDs, true, updateIndicator);
                                    var accountingForMonth = accountingForPlant.FirstOrDefault(a => a.PERIOD_YEAR == currDate.Year && a.PERIOD_MONTH == currDate.Month);
                                    if (accountingForMonth != null)
                                    {
                                        timeLost       = accountingForMonth.TIME_LOST ?? 0;
                                        timeRestricted = accountingForMonth.TOTAL_DAYS_RESTRICTED ?? 0;
                                    }
                                    EHSDataMapping.SetEHSDataValue(ehsdataList, timeLostMeasureID, timeLost, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(ehsdataList, timeRestrictedMeasureID, timeRestricted, updateIndicator);
                                    WriteLine("ACCOUNTING Rollup For Plant " + pact.PLANT_ID + " date = " + currDate.ToShortDateString());
                                }
                                else
                                {
                                    // get any spurrious data that might have been entered manually. we will want to delete these
                                    ehsdataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMonthlyMeasureIDs, false, updateIndicator);
                                }

                                foreach (var data in ehsdataList)
                                {
                                    if (data.EntityState == EntityState.Detached && data.VALUE.HasValue && currDate.Day == 1)
                                    {
                                        entities.EHS_DATA.AddObject(data);
                                    }
                                    else if (data.EntityState != EntityState.Detached && currDate.Day != 1)
                                    {
                                        entities.DeleteObject(data);
                                    }
                                }
                            }
                        }

                        entities.SaveChanges();
                    }

                    entities.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                output.AppendFormat("EHS Data RollUp Error - {0}", ex);
            }

            return(nextStep);
        }
Exemple #4
0
        static string ProcessEnvironmental()
        {
            PSsqmEntities entities     = new PSsqmEntities();
            SETTINGS      setting      = null;
            string        nextStep     = "";
            DateTime      toDate       = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
            DateTime      fromDate     = toDate.AddMonths(-3);
            int           status       = 0;
            DateTime      currencyDate = DateTime.MinValue;

            WriteLine("ENVIRONMENTAL Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "");            // ABW 20140805

            try
            {
                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_ENV_PERIODSPAN").FirstOrDefault();
                if (setting != null)
                {
                    fromDate = toDate.AddMonths(Convert.ToInt32(setting.VALUE) * -1);
                }

                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_ENV_NEXTPAGE").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1)
                {
                    nextStep = setting.VALUE;
                }

                CURRENCY_XREF latestCurrency = CurrencyMgr.GetLatestRecord(entities);
                if (latestCurrency != null)
                {
                    currencyDate = new DateTime(latestCurrency.EFF_YEAR, latestCurrency.EFF_MONTH, DateTime.DaysInMonth(latestCurrency.EFF_YEAR, latestCurrency.EFF_MONTH));
                }
                WriteLine("Max Currency Date = " + currencyDate.ToShortDateString());

                List <EHSProfile> profileList = new List <EHSProfile>();
                foreach (decimal plantID in (from p in entities.EHS_PROFILE select p.PLANT_ID).ToList())
                {
                    profileList.Add(new EHSProfile().Load(Convert.ToDecimal(plantID), false, true));
                }

                foreach (EHSProfile profile in profileList)                             // do each plant having a metric profile
                {
                    WriteLine(profile.Plant.PLANT_NAME);
                    DateTime periodDate = fromDate;

                    while (periodDate <= toDate)                                                // do each month within the rollup span
                    {
                        WriteLine(" " + periodDate.Year.ToString() + "/" + periodDate.Month.ToString());
                        if (profile.InputPeriod == null || profile.InputPeriod.PeriodDate != periodDate)
                        {
                            profile.LoadPeriod(periodDate);
                        }

                        if (profile.ValidPeriod())
                        {
                            if (!profile.InputPeriod.PlantAccounting.APPROVAL_DT.HasValue)
                            {
                                profile.InputPeriod.PlantAccounting.APPROVAL_DT = toDate;
                                profile.InputPeriod.PlantAccounting.APPROVER_ID = 1m;                      // default to the sysadmin user
                            }
                            status = profile.UpdateMetricHistory(periodDate);                              // new roll-up logic
                            WriteLine(" ... " + status.ToString());
                        }
                        periodDate = periodDate.AddMonths(1);
                    }
                }

                WriteLine("ENVIRONMENTAL Rollup Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            }
            catch (Exception ex)
            {
                WriteLine("ENVIRONMENTAL RollUp Error: " + ex.ToString());
            }

            return(nextStep);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                return;
            }

            output = new StringBuilder();
            SETTINGS setting  = null;
            bool     validIP  = true;
            string   pageURI  = HttpContext.Current.Request.Url.AbsoluteUri;
            string   nextPage = "";
            DateTime toDate   = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);
            DateTime fromDate = toDate.AddMonths(-3);

            WriteLine("ENV Data Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            WriteLine(pageURI);

            try
            {
                string          currentIP = GetIPAddress();
                List <SETTINGS> sets      = SQMSettings.SelectSettingsGroup("AUTOMATE", "");           // ABW 20140805

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();

                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_ENV_PERIODSPAN").FirstOrDefault();
                if (setting != null)
                {
                    fromDate = toDate.AddMonths(Convert.ToInt32(setting.VALUE) * -1);
                }

                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_ENV_NEXTPAGE").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1)
                {
                    nextPage = setting.VALUE;
                }

                /*
                 * if (strValidIP.Equals(currentIP))
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from a valid IP address " + currentIP);
                 *      validIP = true;
                 *
                 *      if (Request.QueryString["validation"] != null)
                 *      {
                 *              if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                 *                      validIP = true;
                 *      }
                 *      else
                 *      {
                 *              WriteLine("Main Incident RollUp requested from incorrect source.");
                 *              validIP = false;
                 *      }
                 * }
                 * else
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from invalid IP address " + currentIP);
                 *      validIP = false;
                 * }
                 */
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Main ENV Data RollUp Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            //validIP = true;

            if (!validIP)
            {
                WriteLine("Main ENV Data RollUp Invalid IP Address");
                ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
                WriteLogFile();

                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                return;
            }

            try
            {
                PSsqmEntities entities = new PSsqmEntities();

                int      status       = 0;
                DateTime currencyDate = DateTime.MinValue;

                CURRENCY_XREF latestCurrency = CurrencyMgr.GetLatestRecord(entities);
                if (latestCurrency != null)
                {
                    currencyDate = new DateTime(latestCurrency.EFF_YEAR, latestCurrency.EFF_MONTH, DateTime.DaysInMonth(latestCurrency.EFF_YEAR, latestCurrency.EFF_MONTH));
                }
                WriteLine("Max Currency Date = " + currencyDate.ToShortDateString());


                List <EHSProfile> profileList = new List <EHSProfile>();
                foreach (decimal plantID in (from p in entities.EHS_PROFILE select p.PLANT_ID).ToList())
                {
                    profileList.Add(new EHSProfile().Load(Convert.ToDecimal(plantID), false, true));
                }

                foreach (EHSProfile profile in profileList)                             // do each plant having a metric profile
                {
                    WriteLine(profile.Plant.PLANT_NAME);
                    DateTime periodDate = fromDate;

                    while (periodDate <= toDate)                                                // do each month within the rollup span
                    {
                        WriteLine(" " + periodDate.Year.ToString() + "/" + periodDate.Month.ToString());
                        if (profile.InputPeriod == null || profile.InputPeriod.PeriodDate != periodDate)
                        {
                            profile.LoadPeriod(periodDate);
                        }

                        if (profile.ValidPeriod())
                        {
                            if (!profile.InputPeriod.PlantAccounting.APPROVAL_DT.HasValue)
                            {
                                profile.InputPeriod.PlantAccounting.APPROVAL_DT = toDate;
                                profile.InputPeriod.PlantAccounting.APPROVER_ID = 1m;                      // default to the sysadmin user
                            }
                            status = profile.UpdateMetricHistory(periodDate);                              // new roll-up logic
                            WriteLine(" ... " + status.ToString());
                            periodDate = periodDate.AddMonths(1);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                WriteLine("Main ENV Data RollUp Error - " + ex.ToString());
            }

            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();

            try
            {
                if (!string.IsNullOrEmpty(nextPage))
                {
                    int    s1          = pageURI.LastIndexOf('/');
                    int    s2          = pageURI.LastIndexOf('.') > -1 ? pageURI.LastIndexOf('.') : pageURI.Length;
                    string nextPageURI = pageURI.Substring(0, s1 + 1) + nextPage + pageURI.Substring(s2, pageURI.Length - s2);
                    Response.Redirect(nextPageURI);
                }
            }
            catch (Exception ex)
            {
                output = new StringBuilder();
                WriteLine("RollUp Redirect Error - " + ex.ToString());
                WriteLogFile();
            }

            System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
        }
Exemple #6
0
        static void ScheduleAllAudits()
        {
            List <SETTINGS> sets              = SQMSettings.SelectSettingsGroup("AUTOMATE", ""); // ABW 20140805
            int             startRangeHours   = 04;
            int             startRangeMinutes = 45;
            int             endRangeHours     = 05;
            int             endRangeMinutes   = 15;

            try
            {
                startRange        = sets.Find(x => x.SETTING_CD == "AuditScheduleStart").VALUE.ToString();
                startRangeHours   = Convert.ToInt16(startRange.Substring(0, 2));
                startRangeMinutes = Convert.ToInt16(startRange.Substring(3, 2));
            }
            catch { }
            try
            {
                endRange        = sets.Find(x => x.SETTING_CD == "AuditScheduleEnd").VALUE.ToString();
                endRangeHours   = Convert.ToInt16(endRange.Substring(0, 2));
                endRangeMinutes = Convert.ToInt16(endRange.Substring(3, 2));
            }
            catch { }

            List <AUDIT_SCHEDULER> scheduler = EHSAuditMgr.SelectActiveAuditSchedulers(0, null);            // currently, we will select all schedules for all plants
            AUDIT audit = null;
            List <EHSAuditQuestion> questions = null;
            AUDIT_ANSWER            answer    = null;
            decimal  auditId = 0;
            TimeSpan start   = new TimeSpan(startRangeHours, startRangeMinutes, 0);
            TimeSpan end     = new TimeSpan(endRangeHours, endRangeMinutes, 0);

            WriteLine("Audits will be created for locations with a local time of " + startRangeHours + ":" + startRangeMinutes + " through " + endRangeHours + ":" + endRangeMinutes);
            foreach (AUDIT_SCHEDULER schedule in scheduler)
            {
                AUDIT_TYPE audittype = EHSAuditMgr.SelectAuditTypeById(entities, (decimal)schedule.AUDIT_TYPE_ID);
                // check that the audit is still active
                if (audittype != null)
                {
                    if (!audittype.INACTIVE)
                    {
                        // ABW 1/5/16 - changing the scheduler from scheduling one week of audits to creating audits that are to be scheduled that day.
                        //     All audits will be scheduled at 5am local plant time for the day.
                        //WriteLine("");
                        //WriteLine("The following " + type.TITLE + " assessments were created for Assessment Scheduler " + schedule.AUDIT_SCHEDULER_ID + ": ");
                        //// determine the date to schedule, by finding the next occurance of the selected day of the week after the current day
                        //DateTime auditDate = DateTime.Today;
                        //while ((int)auditDate.DayOfWeek != schedule.DAY_OF_WEEK)
                        //{
                        //	auditDate = auditDate.AddDays(1);
                        //}

                        // get the plant
                        PLANT auditPlant = SQMModelMgr.LookupPlant((decimal)schedule.PLANT_ID);
                        // check the local plant time to see if it is almost 5am.  If so, schedule the audit. If not, do nothing.
                        DateTime localTime = WebSiteCommon.LocalTime(DateTime.UtcNow, auditPlant.LOCAL_TIMEZONE);
                        if ((int)localTime.DayOfWeek == schedule.DAY_OF_WEEK && ((localTime.TimeOfDay > start) && (localTime.TimeOfDay < end)))
                        {
                            WriteLine("");
                            WriteLine("The following " + audittype.TITLE + " assessments were created for Assessment Scheduler " + schedule.AUDIT_SCHEDULER_ID + ": ");
                            // for the location, select all people that should get the audit
                            List <PERSON> auditors = SQMModelMgr.SelectPlantPrivgroupPersonList(auditPlant.PLANT_ID, new string[1] {
                                schedule.JOBCODE_CD
                            }, true);
                            foreach (PERSON person in auditors)
                            {
                                // check to see if there is already an audit for this plant/type/date/person
                                audit = EHSAuditMgr.SelectAuditForSchedule(auditPlant.PLANT_ID, audittype.AUDIT_TYPE_ID, person.PERSON_ID, localTime);
                                if (audit == null)
                                {
                                    // create audit header
                                    auditId = 0;
                                    audit   = new AUDIT()
                                    {
                                        DETECT_COMPANY_ID = Convert.ToDecimal(auditPlant.COMPANY_ID),
                                        DETECT_BUS_ORG_ID = auditPlant.BUS_ORG_ID,
                                        DETECT_PLANT_ID   = auditPlant.PLANT_ID,
                                        AUDIT_TYPE        = "EHS",
                                        CREATE_DT         = localTime,
                                        CREATE_BY         = "Automated Scheduler",
                                        DESCRIPTION       = audittype.TITLE,
                                        // CREATE_PERSON = SessionManager.UserContext.Person.PERSON_ID, // do we want to set this to admin?
                                        AUDIT_DT         = localTime,
                                        AUDIT_TYPE_ID    = audittype.AUDIT_TYPE_ID,
                                        AUDIT_PERSON     = person.PERSON_ID,
                                        CURRENT_STATUS   = "A",
                                        PERCENT_COMPLETE = 0,
                                        TOTAL_SCORE      = 0
                                    };

                                    entities.AddToAUDIT(audit);
                                    entities.SaveChanges();
                                    auditId = audit.AUDIT_ID;

                                    // create audit answer records
                                    questions = EHSAuditMgr.SelectAuditQuestionListByType(audittype.AUDIT_TYPE_ID);
                                    foreach (var q in questions)
                                    {
                                        answer = new AUDIT_ANSWER()
                                        {
                                            AUDIT_ID               = auditId,
                                            AUDIT_QUESTION_ID      = q.QuestionId,
                                            ANSWER_VALUE           = "",
                                            ORIGINAL_QUESTION_TEXT = q.QuestionText,
                                            //COMMENT = q.AnswerComment
                                        };
                                        entities.AddToAUDIT_ANSWER(answer);
                                    }
                                    entities.SaveChanges();
                                    // create task record for their calendar
                                    EHSAuditMgr.CreateOrUpdateTask(auditId, person.PERSON_ID, 50, localTime.AddDays(audittype.DAYS_TO_COMPLETE), "A", 0);

                                    // send an email
                                    EHSNotificationMgr.NotifyOnAuditCreate(auditId, person.PERSON_ID);
                                    System.Threading.Thread.Sleep(timer);                                     //will wait for 2 seconds to allow Google Mail to process email requests

                                    WriteLine(person.LAST_NAME + ", " + person.FIRST_NAME + " - assessment added");
                                }
                                else
                                {
                                    // ABW 1/5/16 - Since this will be running once every hour now, we don't want to see this message
                                    //WriteLine(person.LAST_NAME + ", " + person.FIRST_NAME + " - assessment already exists for this date");
                                }
                            }
                        }
                        else
                        {
                            // ABW 1/5/16 - Do we need to write any message out to explaing why the audit wasn't created?  I don't think so
                            //WriteLine("Assessment Type " + schedule.AUDIT_TYPE_ID + " - assessment already exists for this date OR is not scheduled to be created");
                        }
                    }
                    else
                    {
                        WriteLine("Assessment Type " + schedule.AUDIT_TYPE_ID + " inactive. Assessments not created for Scheduler Record " + schedule.AUDIT_SCHEDULER_ID.ToString());
                    }
                }
                else
                {
                    WriteLine("Assessment Type " + schedule.AUDIT_TYPE_ID + " not found. Assessments not created for Scheduler Record " + schedule.AUDIT_SCHEDULER_ID.ToString());
                }
            }
        }
Exemple #7
0
        static string OverdueTaskNotifications(DateTime currentTime)
        {
            string   nextStep     = "";
            DateTime openFromDate = new DateTime(2000, 1, 1);
            DateTime localTime;
            int      execAtHour = 10;           // set exec time default to 5 am EST

            WriteLine("OVERDUE TASK NOTIFICATIONS Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            SETTINGS        setting = null;
            List <SETTINGS> sets    = SQMSettings.SelectSettingsGroup("AUTOMATE", "");

            try
            {
                // execute at specified hour of day (e.g. TASKNOTIFY_TIME == 01:00)
                if ((setting = sets.Where(x => x.SETTING_CD == "TASKNOTIFY_TIME").FirstOrDefault()) != null)
                {
                    // throwing an error here if the setting format was incorrect will be helpful for debugging
                    execAtHour = int.Parse(WebSiteCommon.SplitString(setting.VALUE, ':').First());
                }

                entities = new PSsqmEntities();

                List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0);
                PLANT        plant     = null;

                List <TaskItem> openTaskList = TaskMgr.SelectOpenTasks(currentTime, openFromDate);
                if (openTaskList.Count > 0)
                {
                    WriteLine("Open Tasks ...");
                    foreach (TaskItem taskItem in openTaskList)
                    {
                        try
                        {
                            if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident)
                            {
                                INCIDENT incident = EHSIncidentMgr.SelectIncidentById(entities, taskItem.Task.RECORD_ID);
                                if (incident != null && (plant = plantList.Where(l => l.PLANT_ID == incident.DETECT_PLANT_ID).FirstOrDefault()) != null)
                                {
                                    if (execAtHour == WebSiteCommon.LocalTime(currentTime, plant.LOCAL_TIMEZONE).Hour)
                                    {
                                        WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS);
                                        // notify assigned person and escalation person if over-over due
                                        EHSNotificationMgr.NotifyIncidentTaskStatus(incident, taskItem, ((int)SysPriv.action).ToString());
                                        System.Threading.Thread.Sleep(timer);                                         //will wait for 2 seconds to allow Google Mail to process email requests

                                        if (taskItem.Taskstatus >= SQM.Website.TaskStatus.Overdue)
                                        {
                                            // send to notification list for plant, BU, ...
                                            //EHSNotificationMgr.NotifyIncidentStatus(incident, taskItem.Task.TASK_STEP, ((int)SysPriv.notify).ToString(), "");
                                            //System.Threading.Thread.Sleep(timer); //will wait for 2 seconds to allow Google Mail to process email requests
                                        }
                                    }
                                }
                                else
                                {
                                    WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS + "  This task does not have a corresponding incident or plant record");
                                }
                            }
                            else if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.PreventativeAction)
                            {
                                INCIDENT incident = EHSIncidentMgr.SelectIncidentById(entities, taskItem.Task.RECORD_ID);
                                if (incident != null && (plant = plantList.Where(l => l.PLANT_ID == incident.DETECT_PLANT_ID).FirstOrDefault()) != null)
                                {
                                    if (execAtHour == WebSiteCommon.LocalTime(currentTime, plant.LOCAL_TIMEZONE).Hour)
                                    {
                                        WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS);
                                        // notify assigned person and escalation person if over-over due
                                        EHSNotificationMgr.NotifyPrevActionTaskStatus(incident, taskItem, ((int)SysPriv.action).ToString());
                                        System.Threading.Thread.Sleep(timer);                                         //will wait for 2 seconds to allow Google Mail to process email requests
                                    }
                                }
                                else
                                {
                                    WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS + "  This task does not have a corresponding preventative action or plant record");
                                }
                            }
                            else if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.Audit)
                            {
                                AUDIT audit = EHSAuditMgr.SelectAuditById(entities, taskItem.Task.RECORD_ID);
                                if (audit != null && (plant = plantList.Where(l => l.PLANT_ID == audit.DETECT_PLANT_ID).FirstOrDefault()) != null)
                                {
                                    if (execAtHour == WebSiteCommon.LocalTime(currentTime, plant.LOCAL_TIMEZONE).Hour)
                                    {
                                        WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS);
                                        if (taskItem.Task.TASK_STEP == "0")
                                        {
                                            EHSNotificationMgr.NotifyAuditStatus(audit, taskItem);
                                            System.Threading.Thread.Sleep(timer);                                             //will wait for 2 seconds to allow Google Mail to process email requests
                                        }
                                        else
                                        {
                                            EHSNotificationMgr.NotifyAuditTaskStatus(audit, taskItem, ((int)SysPriv.action).ToString());
                                            System.Threading.Thread.Sleep(timer);                                             //will wait for 2 seconds to allow Google Mail to process email requests
                                        }
                                    }
                                }
                                else
                                {
                                    WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS + "  This task does not have a corresponding audit or plant record");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteLine("Error: " + ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine("OVERDUE TASK NOTIFICATIONS Error - " + ex.ToString());
            }

            WriteLine("OVERDUE TASK NOTIFICATIONS Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            return(nextStep);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageMode = "";

            if (!string.IsNullOrEmpty(Request.QueryString["m"]))               // .../...aspx?p=xxxxx
            {
                pageMode = Request.QueryString["m"].ToLower();                 // page mode (web == running manually from the menu)
            }

            if (IsPostBack)
            {
                if (pageMode != "web")
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                }
                return;
            }

            output = new StringBuilder();
            bool     validIP         = true;
            DateTime thisPeriod      = DateTime.UtcNow;
            decimal  updateIndicator = thisPeriod.Ticks;
            decimal  locationID      = 0;

            WriteLine("Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            try
            {
                string          currentIP = GetIPAddress();
                List <SETTINGS> sets      = SQMSettings.SelectSettingsGroup("AUTOMATE", "");           // ABW 20140805

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();

                /*
                 * if (strValidIP.Equals(currentIP))
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from a valid IP address " + currentIP);
                 *      validIP = true;
                 *
                 *      if (Request.QueryString["validation"] != null)
                 *      {
                 *              if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                 *                      validIP = true;
                 *      }
                 *      else
                 *      {
                 *              WriteLine("Main Incident RollUp requested from incorrect source.");
                 *              validIP = false;
                 *      }
                 * }
                 * else
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from invalid IP address " + currentIP);
                 *      validIP = false;
                 * }
                 */
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Main Email Notification Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            validIP = true;

            if (!validIP)
            {
                WriteLine("Main Incident RollUp Invalid IP Address");
                ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
                WriteLogFile();

                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                return;
            }

            try
            {
                PSsqmEntities entities = new PSsqmEntities();

                List <TaskItem> openAuditList = TaskMgr.SelectOpenAudits(DateTime.UtcNow, DateTime.UtcNow);
                if (openAuditList.Count > 0)
                {
                    WriteLine("Open Audits ...");
                    foreach (TaskItem taskItem in openAuditList)
                    {
                        WriteLine("Audit: " + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS);
                        AUDIT audit = EHSAuditMgr.SelectAuditById(entities, taskItem.Task.RECORD_ID);
                        if (audit != null)
                        {
                            EHSNotificationMgr.NotifyAuditStatus(audit, taskItem);
                        }
                    }
                }

                List <TaskItem> openTaskList = TaskMgr.SelectOpenTasks(DateTime.UtcNow, DateTime.UtcNow);
                if (openTaskList.Count > 0)
                {
                    WriteLine("Open Tasks ...");
                    foreach (TaskItem taskItem in openTaskList)
                    {
                        WriteLine("Task: " + taskItem.Task.TASK_ID.ToString() + " RecordType:  " + taskItem.Task.RECORD_TYPE.ToString() + "  " + "RecordID:" + taskItem.Task.RECORD_ID.ToString() + "  Status = " + taskItem.Task.STATUS);
                        if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident)
                        {
                            INCIDENT incident = EHSIncidentMgr.SelectIncidentById(entities, taskItem.Task.RECORD_ID);
                            if (incident != null)
                            {
                                // notify assigned person and escalation person if over-over due
                                EHSNotificationMgr.NotifyIncidentTaskStatus(incident, taskItem, ((int)SysPriv.action).ToString());
                                if (taskItem.Taskstatus >= TaskStatus.Overdue)
                                {
                                    // send to notification list for plant, BU, ...
                                    EHSNotificationMgr.NotifyIncidentStatus(incident, taskItem.Task.TASK_STEP, ((int)SysPriv.notify).ToString(), "");
                                }
                            }
                        }
                        else if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.PreventativeAction)
                        {
                            INCIDENT incident = EHSIncidentMgr.SelectIncidentById(entities, taskItem.Task.RECORD_ID);
                            if (incident != null)
                            {
                                // notify assigned person and escalation person if over-over due
                                EHSNotificationMgr.NotifyPrevActionTaskStatus(incident, taskItem, ((int)SysPriv.action).ToString());
                            }
                        }
                        else if (taskItem.Task.RECORD_TYPE == (int)TaskRecordType.Audit)
                        {
                            AUDIT audit = EHSAuditMgr.SelectAuditById(entities, taskItem.Task.RECORD_ID);
                            if (audit != null)
                            {
                                EHSNotificationMgr.NotifyAuditTaskStatus(audit, taskItem, ((int)SysPriv.action).ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine("Main Email Notificaion Error - " + ex.ToString());
            }

            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();

            System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            output   = new StringBuilder();
            entities = new PSsqmEntities();
            bool validIP = false;

            WriteLine("Conversion Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            try
            {
                string          currentIP = GetIPAddress();
                List <SETTINGS> sets      = SQMSettings.SelectSettingsGroup("AUTOMATE", "");           // ABW 20140805

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();

                if (strValidIP.Equals(currentIP))
                {
                    WriteLine("Incidents Conversion being accessed from a valid IP address " + currentIP);
                    validIP = true;

                    if (Request.QueryString["validation"] != null)
                    {
                        if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                        {
                            validIP = true;
                        }
                    }
                    else
                    {
                        WriteLine("Incidents Conversion requested from incorrect source.");
                        validIP = false;
                    }
                }
                else
                {
                    WriteLine("Incidents Conversion being accessed from invalid IP address " + currentIP);
                    validIP = false;
                }
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Incidents Conversion Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            //validIP = true;

            if (validIP)
            {
                try
                {
                    //
                    MoveQuestionsToFormTables();
                }
                catch (Exception ex)
                {
                    WriteLine("Main UpdatePastDueAssessmentStatus Error: " + ex.ToString());
                }

                try
                {
                    // Schedule new audits
                    ScheduleAllAudits();
                }
                catch (Exception ex)
                {
                    WriteLine("Main ScheduleAssessments Error: " + ex.ToString());
                    //WriteLine("Main ScheduleAudits Detailed Error: " + ex.InnerException.ToString());
                }
            }
            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();
        }
Exemple #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            output   = new StringBuilder();
            entities = new PSsqmEntities();

            string pageMode = "";

            if (!string.IsNullOrEmpty(Request.QueryString["m"]))               // .../...aspx?p=xxxxx
            {
                pageMode = Request.QueryString["m"].ToLower();                 // page mode (web == running manually from the menu)
            }

            if (IsPostBack)
            {
                if (pageMode != "web")
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                }
                return;
            }

            sets           = SQMSettings.SelectSettingsGroup("FILE_UPLOAD", "");
            primaryCompany = Convert.ToInt32(sets.Find(x => x.SETTING_CD == "CompanyID").VALUE);
            fileDelimiter  = sets.Find(x => x.SETTING_CD == "FileDelimiter1").VALUE.ToCharArray();

            sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "");
            bool validIP = false;

            WriteLine("Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            try
            {
                string currentIP = GetIPAddress();

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();
                if (strValidIP.Equals(currentIP))
                {
                    WriteLine("Resource Import being accessed from a valid IP address " + currentIP);
                    validIP = true;

                    if (Request.QueryString["validation"] != null)
                    {
                        if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                        {
                            validIP = true;
                        }
                    }
                    else
                    {
                        WriteLine("Resource Import requested from incorrect source.");
                        validIP = false;
                    }
                }
                else
                {
                    WriteLine("Resource Import being accessed from invalid IP address " + currentIP);
                    validIP = false;
                }
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Resource Import Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            //validIP = true;

            if (validIP)
            {
                try
                {
                    // Process resource file
                    ProcessFile("Reference");
                }
                catch (Exception ex)
                {
                    WriteLine("Error Processing Reference File: " + ex.ToString());
                }

                try
                {
                    // Process Person Input file from PeopleSoft
                    ProcessFile("Person");
                }
                catch (Exception ex)
                {
                    WriteLine("Error Processing Person File: " + ex.ToString());
                    //WriteLine("Main ScheduleAudits Detailed Error: " + ex.InnerException.ToString());
                }
            }

            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();

            if (pageMode != "web")
            {
                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            output   = new StringBuilder();
            entities = new PSsqmEntities();

            List <SETTINGS> MailSettings = SQMSettings.SelectSettingsGroup("MAIL", "");

            foreach (SETTINGS set in MailSettings)
            {
                switch (set.SETTING_CD)
                {
                case "MailServer":
                    mailServer = set.VALUE;
                    break;

                case "MailFrom":
                    mailFrom = set.VALUE;
                    break;

                case "MailSMTPPort":
                    mailSMTPPort = set.VALUE;
                    break;

                case "MailEnableSSL":
                    mailEnableSSL = set.VALUE;
                    break;

                case "MailURL":
                    mailURL = set.VALUE;
                    break;

                case "MailPassword":
                    mailPassword = set.VALUE;
                    break;

                default:
                    break;
                }
            }

            List <SETTINGS> ReceiptImportSettings = SQMSettings.SelectSettingsGroup("IMPORT_RECEIPT", "");

            foreach (SETTINGS ris in ReceiptImportSettings)
            {
                switch (ris.SETTING_CD)
                {
                case "CompanyID":
                    companyID = Convert.ToInt16(ris.VALUE);
                    break;

                case "FileLocation":
                    fileLocation = ris.VALUE;
                    break;

                case "FileDelimiter":
                    fileDelimiter = ris.VALUE.ToCharArray();
                    break;

                case "LogFileEmail":
                    logFileEmail = ris.VALUE;
                    break;

                case "ReceiptFile":
                    receiptFile = ris.VALUE + "*";
                    break;

                case "InspectionFile":
                    inspectionFile = ris.VALUE + "*";
                    break;

                default:
                    break;
                }
            }

            timestamp = string.Format("{0:yyyy-MM-dd-HHmm}", DateTime.Now);
            emailBody = "";

            WriteLine("Processing files in: " + fileLocation);
            string[] fileEntries;
            try
            {
                // check for each file separately and process
                WriteLine("Start Receipt file processing.");
                // Process each file type
                fileEntries = Directory.GetFiles(fileLocation, receiptFile);
                fileCount   = 0;
                foreach (string fileName in fileEntries)
                {
                    fileCount += 1;
                    ProcessInputFile("RECEIPT", fileName);
                }
                WriteLine("<br/>Start Inspection file processing.");
                //originalFile = fileLocation + ConfigurationSettings.AppSettings["PlantFile"];
                fileEntries = Directory.GetFiles(fileLocation, inspectionFile);
                fileCount   = 0;
                foreach (string fileName in fileEntries)
                {
                    fileCount += 1;
                    ProcessInputFile("INSPECT", fileName);
                }
                WriteLine("<br/><br/>");
            }
            catch (Exception ex)
            {
                WriteLine("Error: " + ex.ToString());
            }

            WriteLogFile();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageMode = "";

            if (!string.IsNullOrEmpty(Request.QueryString["m"]))               // .../...aspx?p=xxxxx
            {
                pageMode = Request.QueryString["m"].ToLower();                 // page mode (web == running manually from the menu)
            }

            if (IsPostBack)
            {
                if (pageMode != "web")
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                }
                return;
            }

            output = new StringBuilder();
            SETTINGS         setting  = null;
            bool             validIP  = true;
            int              workdays = 7;
            string           pageURI  = HttpContext.Current.Request.Url.AbsoluteUri;
            string           nextPage = "";
            PLANT_ACCOUNTING pa       = null;

            fromDate = DateTime.UtcNow.AddMonths(-11);                // set the incident 'select from' date.  TODO: get this from SETTINGS table
            // set end date to end of current month to clear spurrious entries ?
            DateTime rollupToDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month));

            WriteLine("Incident Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            WriteLine(pageURI);

            try
            {
                string          currentIP = GetIPAddress();
                List <SETTINGS> sets      = SQMSettings.SelectSettingsGroup("AUTOMATE", "");           // ABW 20140805

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();
                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_WORKDAYS").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE))
                {
                    if (!int.TryParse(setting.VALUE, out workdays))
                    {
                        workdays = 7;
                    }
                }
                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_NEXTPAGE").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1)
                {
                    nextPage = setting.VALUE;
                }

                /*
                 * int rollupMonthsAhead = 0;
                 * setting = sets.Where(x => x.SETTING_CD == "ROLLUP_MONTHS_AHEAD").FirstOrDefault();
                 * if (setting != null  &&  !string.IsNullOrEmpty(setting.VALUE))
                 * {
                 *      int.TryParse(setting.VALUE, out rollupMonthsAhead);
                 *      rollupToDate = rollupToDate.AddMonths(rollupMonthsAhead);
                 * }
                 */
                /*
                 * if (strValidIP.Equals(currentIP))
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from a valid IP address " + currentIP);
                 *      validIP = true;
                 *
                 *      if (Request.QueryString["validation"] != null)
                 *      {
                 *              if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                 *                      validIP = true;
                 *      }
                 *      else
                 *      {
                 *              WriteLine("Main Incident RollUp requested from incorrect source.");
                 *              validIP = false;
                 *      }
                 * }
                 * else
                 * {
                 *      WriteLine("Main Incident RollUp being accessed from invalid IP address " + currentIP);
                 *      validIP = false;
                 * }
                 */
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Main Incident RollUp Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            //validIP = true;

            if (!validIP)
            {
                WriteLine("Main Incident RollUp Invalid IP Address");
                ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
                WriteLogFile();

                if (pageMode != "web")
                {
                    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
                }
                return;
            }

            try
            {
                PSsqmEntities entities = new PSsqmEntities();

                // fetch all incidents occurring after the minimum reporting date
                List <INCIDENT> incidentList = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS")
                                                where
                                                i.ISSUE_TYPE_ID != (decimal)EHSIncidentTypeId.PreventativeAction &&
                                                i.INCIDENT_DT >= fromDate && i.DETECT_PLANT_ID > 0
                                                select i).OrderBy(l => l.DETECT_PLANT_ID).ThenBy(l => l.INCIDENT_DT).ToList();

                List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0);
                PLANT        plant     = null;

                // fetch all the plant accounting records for the target timespan
                DateTime minDate = incidentList.Select(l => l.INCIDENT_DT).Min();
                minDate = minDate.AddMonths(-1);
                List <PLANT_ACCOUNTING> paList = (from a in entities.PLANT_ACCOUNTING
                                                  where
                                                  EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) >= minDate && EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) <= rollupToDate
                                                  select a).OrderBy(l => l.PLANT_ID).ThenBy(l => l.PERIOD_YEAR).ThenBy(l => l.PERIOD_MONTH).ToList();

                List <EHSIncidentTimeAccounting> summaryList = new List <EHSIncidentTimeAccounting>();

                foreach (INCIDENT incident in incidentList)
                {
                    WriteLine("Incident ID: " + incident.INCIDENT_ID.ToString() + "  Occur Date: " + Convert.ToDateTime(incident.INCIDENT_DT).ToShortDateString());
                    incident.INCFORM_CAUSATION.Load();
                    if (incident.ISSUE_TYPE_ID == (decimal)EHSIncidentTypeId.InjuryIllness)
                    {
                        incident.INCFORM_LOSTTIME_HIST.Load();
                    }
                    plant       = plantList.Where(l => l.PLANT_ID == (decimal)incident.DETECT_PLANT_ID).FirstOrDefault();
                    summaryList = EHSIncidentMgr.SummarizeIncidentAccounting(summaryList, EHSIncidentMgr.CalculateIncidentAccounting(incident, plant.LOCAL_TIMEZONE, workdays));
                }

                plant = null;
                PLANT_ACTIVE pact = null;
                DateTime     periodDate;

                foreach (PLANT_ACCOUNTING pah in paList.OrderBy(l => l.PLANT_ID).ToList())
                {
                    if (pact == null || pact.PLANT_ID != pah.PLANT_ID)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == pah.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                    }
                    //if (pact != null && pact.EFF_END_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date)
                    if (pact != null && pact.EFF_START_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date)
                    {
                        pah.TIME_LOST       = pah.TOTAL_DAYS_RESTRICTED = 0;
                        pah.TIME_LOST_CASES = pah.RECORDED_CASES = pah.FIRST_AID_CASES = 0;
                    }
                }

                plant = null;
                pact  = null;
                foreach (EHSIncidentTimeAccounting period in summaryList.OrderBy(l => l.PlantID).ThenBy(l => l.PeriodYear).ThenBy(l => l.PeriodMonth).ToList())
                {
                    if (plant == null || plant.PLANT_ID != period.PlantID)
                    {
                        plant = plantList.Where(l => l.PLANT_ID == period.PlantID).FirstOrDefault();
                        pact  = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                    }
                    periodDate = new DateTime(period.PeriodYear, period.PeriodMonth, 1);

                    if (pact != null && pact.EFF_START_DATE.HasValue && periodDate >= pact.EFF_START_DATE)
                    {
                        // write PLANT_ACCOUNTING metrics
                        if ((pa = paList.Where(l => l.PLANT_ID == period.PlantID && l.PERIOD_YEAR == period.PeriodYear && l.PERIOD_MONTH == period.PeriodMonth).FirstOrDefault()) == null)
                        {
                            paList.Add((pa = new PLANT_ACCOUNTING()));
                            pa.PLANT_ID     = period.PlantID;
                            pa.PERIOD_YEAR  = period.PeriodYear;
                            pa.PERIOD_MONTH = period.PeriodMonth;
                        }
                        pa.TIME_LOST             = period.LostTime;
                        pa.TOTAL_DAYS_RESTRICTED = period.RestrictedTime;
                        pa.TIME_LOST_CASES       = period.LostTimeCase;
                        pa.RECORDED_CASES        = period.RecordableCase;
                        pa.FIRST_AID_CASES       = period.FirstAidCase;
                        pa.LAST_UPD_DT           = DateTime.UtcNow;
                        pa.LAST_UPD_BY           = "automated";

                        EHSModel.UpdatePlantAccounting(entities, pa);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLine("Main Incident RollUp Error - " + ex.ToString());
            }

            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();

            try
            {
                if (!string.IsNullOrEmpty(nextPage))
                {
                    int    s1          = pageURI.LastIndexOf('/');
                    int    s2          = pageURI.LastIndexOf('.') > -1 ? pageURI.LastIndexOf('.') : pageURI.Length;
                    string nextPageURI = pageURI.Substring(0, s1 + 1) + nextPage + pageURI.Substring(s2, pageURI.Length - s2);
                    Response.Redirect(nextPageURI);
                }
            }
            catch (Exception ex)
            {
                output = new StringBuilder();
                WriteLine("RollUp Redirect Error - " + ex.ToString());
                WriteLogFile();
            }

            if (pageMode != "web")
            {
                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
            }
        }
Exemple #13
0
        private void SetupPage()
        {
            if (ddlPlantSelect.Items.Count < 1)
            {
                List <BusinessLocation> locationList = SQMModelMgr.SelectBusinessLocationList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, 0, true);
                SQMBasePage.SetLocationList(ddlPlantSelect, UserContext.FilterPlantAccessList(locationList), 0);

                rcbStatusSelect.SelectedValue = "A";
            }
            divAuditList.Visible = true;
            pnlChartSection.Style.Add("display", "none");
            lblChartType.Visible = ddlChartType.Visible = false;

            dmFromDate.ShowPopupOnFocus = dmToDate.ShowPopupOnFocus = true;
            // ABW 1/5/16 - use user's default plant local time for search default
            DateTime localTime = SessionManager.UserContext.LocalTime;

            dmFromDate.SelectedDate = localTime.AddMonths(-1);
            dmToDate.SelectedDate   = localTime.AddMonths(1);

            if (Mode == AuditMode.Audit)
            {
                lblViewEHSRezTitle.Text  = GetLocalResourceObject("lblViewEHSRezTitleResource1.Text").ToString();
                lblPageInstructions.Text = GetLocalResourceObject("lblPageInstructionsResource1.Text").ToString();
                //lblStatus.Text = "Assessment Status:";
                rbNew.Text           = GetLocalResourceObject("rbNewResource1.Text").ToString();
                lblAuditDate.Visible = true;
                phAudit.Visible      = true;

                SETTINGS sets = SQMSettings.GetSetting("EHS", "AUDITSEARCHFROM");
                if (sets != null)
                {
                    try
                    {
                        string[] args = sets.VALUE.Split('-');
                        if (args.Length > 1)
                        {
                            dmFromDate.SelectedDate = new DateTime(Convert.ToInt32(args[0]), Convert.ToInt32(args[1]), Convert.ToInt32(args[2]));
                        }
                        else
                        {
                            dmFromDate.SelectedDate = SessionManager.UserContext.LocalTime.AddMonths(Convert.ToInt32(args[0]) * -1);
                        }
                    }
                    catch { }
                }

                if (rcbAuditType.Items.Count < 1)
                {
                    foreach (AUDIT_TYPE ip in EHSAuditMgr.SelectAuditTypeList(SessionManager.PrimaryCompany().COMPANY_ID, false))
                    {
                        RadComboBoxItem item = new RadComboBoxItem(ip.TITLE, ip.AUDIT_TYPE_ID.ToString());
                        item.Checked = true;
                        rcbAuditType.Items.Add(item);
                    }
                }

                // lookup charts defined for this module & app context
                //PERSPECTIVE_VIEW view = ViewModel.LookupView(entities, "HSIR", "HSIR", 0);
                //if (view != null)
                //{
                //	ddlChartType.Items.Clear();
                //	ddlChartType.Items.Add(new RadComboBoxItem("", ""));
                //	foreach (PERSPECTIVE_VIEW_ITEM vi in view.PERSPECTIVE_VIEW_ITEM.Where(l => l.STATUS != "I").OrderBy(l => l.ITEM_SEQ).ToList())
                //	{
                //		RadComboBoxItem item = new RadComboBoxItem();
                //		item.Text = vi.TITLE;
                //		item.Value = vi.ITEM_SEQ.ToString();
                //		item.ImageUrl = ViewModel.GetViewItemImageURL(vi);
                //		ddlChartType.Items.Add(item);
                //	}
                //}
                ddlChartType.Items.Clear();
                ddlChartType.Items.Add(new RadComboBoxItem("", ""));
                ddlChartType.Items.Add(new RadComboBoxItem("Audit Summary", "charts"));
                ddlChartType.Items.Add(new RadComboBoxItem("Data Results", "report"));
            }
        }
Exemple #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            output   = new StringBuilder();
            entities = new PSsqmEntities();
            bool validIP = false;

            WriteLine("Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            try
            {
                string          currentIP = GetIPAddress();
                List <SETTINGS> sets      = SQMSettings.SelectSettingsGroup("AUTOMATE", "");           // ABW 20140805

                string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString();

                if (strValidIP.Equals(currentIP))
                {
                    WriteLine("Main ScheduleAssessments being accessed from a valid IP address " + currentIP);
                    validIP = true;

                    if (Request.QueryString["validation"] != null)
                    {
                        if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4"))
                        {
                            validIP = true;
                        }
                    }
                    else
                    {
                        WriteLine("Main ScheduleAssessments requested from incorrect source.");
                        validIP = false;
                    }
                }
                else
                {
                    WriteLine("Main ScheduleAssessments being accessed from invalid IP address " + currentIP);
                    validIP = false;
                }
            }
            catch (Exception ex)
            {
                validIP = false;
                WriteLine("Main ScheduleAssessments Error validating IP Address: " + ex.ToString());
            }

            // make sure this code is NOT moved to production
            //validIP = true;

            if (validIP)
            {
                try
                {
                    // Update the status of all audits that have a date past due
                    UpdatePastDueAuditStatus();
                }
                catch (Exception ex)
                {
                    WriteLine("Main UpdatePastDueAssessmentStatus Error: " + ex.ToString());
                }

                try
                {
                    // Schedule new audits
                    ScheduleAllAudits();
                }
                catch (Exception ex)
                {
                    WriteLine("Main ScheduleAssessments Error: " + ex.ToString());
                    //WriteLine("Main ScheduleAudits Detailed Error: " + ex.InnerException.ToString());
                }
            }
            WriteLine("");
            WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            ltrStatus.Text = output.ToString().Replace("\n", "<br/>");
            WriteLogFile();

            System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true);
        }
Exemple #15
0
        static string ProcessIncidents()
        {
            PSsqmEntities entities          = new PSsqmEntities();
            SETTINGS      setting           = null;
            int           workdays          = 7;
            int           rollupMonthsAhead = 0;
            string        nextStep          = "";
            DateTime      fromDate          = DateTime.UtcNow.AddMonths(-11);  // set the incident 'select from' date.  TODO: get this from SETTINGS table
            // set end date to end of current month to clear spurrious entries ?
            DateTime rollupToDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month));

            WriteLine("INCIDENT Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "");            // ABW 20140805

            try
            {
                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_WORKDAYS").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE))
                {
                    if (!int.TryParse(setting.VALUE, out workdays))
                    {
                        workdays = 7;
                    }
                }

                setting = sets.Where(x => x.SETTING_CD == "ROLLUP_NEXTPAGE").FirstOrDefault();
                if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1)
                {
                    nextStep = setting.VALUE;
                }

                // fetch all incidents occurring after the minimum reporting date
                List <INCIDENT> incidentList = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS")
                                                where
                                                i.ISSUE_TYPE_ID != (decimal)EHSIncidentTypeId.PreventativeAction &&
                                                i.INCIDENT_DT >= fromDate && i.DETECT_PLANT_ID > 0
                                                select i).OrderBy(l => l.DETECT_PLANT_ID).ThenBy(l => l.INCIDENT_DT).ToList();

                List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0);
                PLANT        plant     = null;

                // fetch all the plant accounting records for the target timespan
                DateTime minDate = incidentList.Select(l => l.INCIDENT_DT).Min();
                minDate = minDate.AddMonths(-1);
                PLANT_ACCOUNTING        pa     = null;
                List <PLANT_ACCOUNTING> paList = (from a in entities.PLANT_ACCOUNTING
                                                  where
                                                  EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) >= minDate && EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) <= rollupToDate
                                                  select a).OrderBy(l => l.PLANT_ID).ThenBy(l => l.PERIOD_YEAR).ThenBy(l => l.PERIOD_MONTH).ToList();

                List <EHSIncidentTimeAccounting> summaryList = new List <EHSIncidentTimeAccounting>();

                foreach (INCIDENT incident in incidentList)
                {
                    WriteLine("Incident ID: " + incident.INCIDENT_ID.ToString() + "  Occur Date: " + Convert.ToDateTime(incident.INCIDENT_DT).ToShortDateString());
                    incident.INCFORM_CAUSATION.Load();
                    if (incident.ISSUE_TYPE_ID == (decimal)EHSIncidentTypeId.InjuryIllness)
                    {
                        incident.INCFORM_LOSTTIME_HIST.Load();
                    }
                    plant       = plantList.Where(l => l.PLANT_ID == (decimal)incident.DETECT_PLANT_ID).FirstOrDefault();
                    summaryList = EHSIncidentMgr.SummarizeIncidentAccounting(summaryList, EHSIncidentMgr.CalculateIncidentAccounting(incident, plant.LOCAL_TIMEZONE, workdays));
                }

                plant = null;
                PLANT_ACTIVE pact = null;
                DateTime     periodDate;

                foreach (PLANT_ACCOUNTING pah in paList.OrderBy(l => l.PLANT_ID).ToList())
                {
                    if (pact == null || pact.PLANT_ID != pah.PLANT_ID)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == pah.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                    }
                    //if (pact != null && pact.EFF_END_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date)
                    if (pact != null && pact.EFF_START_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date)
                    {
                        pah.TIME_LOST       = pah.TOTAL_DAYS_RESTRICTED = 0;
                        pah.TIME_LOST_CASES = pah.RECORDED_CASES = pah.FIRST_AID_CASES = 0;
                    }
                }

                plant = null;
                pact  = null;
                foreach (EHSIncidentTimeAccounting period in summaryList.OrderBy(l => l.PlantID).ThenBy(l => l.PeriodYear).ThenBy(l => l.PeriodMonth).ToList())
                {
                    if (plant == null || plant.PLANT_ID != period.PlantID)
                    {
                        plant = plantList.Where(l => l.PLANT_ID == period.PlantID).FirstOrDefault();
                        pact  = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                    }
                    periodDate = new DateTime(period.PeriodYear, period.PeriodMonth, 1);

                    if (pact != null && pact.EFF_START_DATE.HasValue && periodDate >= pact.EFF_START_DATE)
                    {
                        // write PLANT_ACCOUNTING metrics
                        if ((pa = paList.Where(l => l.PLANT_ID == period.PlantID && l.PERIOD_YEAR == period.PeriodYear && l.PERIOD_MONTH == period.PeriodMonth).FirstOrDefault()) == null)
                        {
                            paList.Add((pa = new PLANT_ACCOUNTING()));
                            pa.PLANT_ID     = period.PlantID;
                            pa.PERIOD_YEAR  = period.PeriodYear;
                            pa.PERIOD_MONTH = period.PeriodMonth;
                        }
                        pa.TIME_LOST             = period.LostTime;
                        pa.TOTAL_DAYS_RESTRICTED = period.RestrictedTime;
                        pa.TIME_LOST_CASES       = period.LostTimeCase;
                        pa.RECORDED_CASES        = period.RecordableCase;
                        pa.FIRST_AID_CASES       = period.FirstAidCase;
                        pa.LAST_UPD_DT           = DateTime.UtcNow;
                        pa.LAST_UPD_BY           = "automated";

                        EHSModel.UpdatePlantAccounting(entities, pa);
                    }
                }

                WriteLine("INCIDENT Rollup Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));
            }
            catch (Exception ex)
            {
                WriteLine("INCIDENT RollUp Error: " + ex.ToString());
            }

            return(nextStep);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            output   = new StringBuilder();
            entities = new PSsqmEntities();

            List <SETTINGS> MailSettings = SQMSettings.SelectSettingsGroup("MAIL", "");

            foreach (SETTINGS set in MailSettings)
            {
                switch (set.SETTING_CD)
                {
                case "MailServer":
                    mailServer = set.VALUE;
                    break;

                case "MailFrom":
                    mailFrom = set.VALUE;
                    break;

                case "MailSMTPPort":
                    mailSMTPPort = set.VALUE;
                    break;

                case "MailEnableSSL":
                    mailEnableSSL = set.VALUE;
                    break;

                case "MailURL":
                    mailURL = set.VALUE;
                    break;

                case "MailPassword":
                    mailPassword = set.VALUE;
                    break;

                default:
                    break;
                }
            }

            List <SETTINGS> ImportSettings = SQMSettings.SelectSettingsGroup("FILE_UPLOAD", "");

            foreach (SETTINGS ris in ImportSettings)
            {
                switch (ris.SETTING_CD)
                {
                case "CompanyID":
                    companyID = Convert.ToInt16(ris.VALUE);
                    break;

                case "FileLocation":
                    fileLocation = ris.VALUE;
                    break;

                case "UploadSources":
                    try
                    {
                        uploadSource = Convert.ToInt32(ris.VALUE);
                    }
                    catch
                    {
                        WriteLine("Source file locations have not been defined correctly in the configuration file. No files were processed.");
                        uploadSource = 0;
                    }
                    break;

                case "CompanyFile":
                    companyFile = ris.VALUE;
                    break;

                case "PlantFile":
                    plantFile = ris.VALUE;
                    break;

                case "PartFile":
                    partFile = ris.VALUE;
                    break;

                case "PlantDataFile":
                    plantDataFile = ris.VALUE;
                    break;

                case "CurrencyFile":
                    currencyFile = ris.VALUE;
                    break;

                case "DefaultPartProgram":
                    defaultPartProgram = ris.VALUE;
                    break;

                default:
                    break;
                }
            }

            timestamp = string.Format("{0:yyyy-MM-dd-HHmm}", DateTime.Now);
            emailBody = "";

            for (int i = 1; i <= uploadSource; i++)
            {
                string   fileLocationKey = "UploadFileLocation" + i.ToString();
                SETTINGS result          = ImportSettings.Find(x => x.SETTING_CD == fileLocationKey);
                fileLocation        = result.VALUE;
                result              = ImportSettings.Find(x => x.SETTING_CD == "FileDelimiter" + i.ToString());
                fileDelimiter       = result.VALUE.ToCharArray();
                result              = ImportSettings.Find(x => x.SETTING_CD == "UploadFileType" + i.ToString());
                fileType            = result.VALUE;
                result              = ImportSettings.Find(x => x.SETTING_CD == "PlantDataMultiplier" + i.ToString());
                plantDataMultiplier = Convert.ToDouble(result.VALUE);
                WriteLine("Processing files in: " + fileLocation);
                if (fileType.ToLower().Equals("ftp"))
                {
                    try
                    {
                        // check for each file separately and process
                        WriteLine("Start Company file processing.");
                        // Process each file type
                        ProcessFTPInputFile("COMPANY");
                        WriteLine("<br/>Start Plant file processing.");
                        ProcessFTPInputFile("PLANT");
                        WriteLine("<br/>Start Part file processing.");
                        ProcessFTPInputFile("PART");
                        WriteLine("<br/>Start Plant Data file processing.");
                        ProcessFTPInputFile("PLANT_DATA");
                        //WriteLine("<br/>Start Currency Data file processing.");
                        //ProcessFTPInputFile("CURRENCY_DATA");
                        WriteLine("<br/><br/>");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Error: " + ex.ToString());
                    }
                }
                else
                {
                    string[] fileEntries;
                    try
                    {
                        // check for each file separately and process
                        WriteLine("Start Company file processing.");
                        // Process each file type
                        //originalFile = fileLocation + ConfigurationSettings.AppSettings["CompanyFile"];
                        fileEntries = Directory.GetFiles(fileLocation, companyFile);
                        fileCount   = 0;
                        foreach (string fileName in fileEntries)
                        {
                            fileCount += 1;
                            ProcessInputFile("COMPANY", fileName);
                        }
                        WriteLine("<br/>Start Plant file processing.");
                        //originalFile = fileLocation + ConfigurationSettings.AppSettings["PlantFile"];
                        fileEntries = Directory.GetFiles(fileLocation, plantFile);
                        fileCount   = 0;
                        foreach (string fileName in fileEntries)
                        {
                            if (!fileName.ToLower().Contains("_data"))
                            {
                                fileCount += 1;
                                ProcessInputFile("PLANT", fileName);
                            }
                        }
                        WriteLine("<br/>Start Part file processing.");
                        //originalFile = fileLocation + ConfigurationSettings.AppSettings["PartFile"];
                        fileEntries = Directory.GetFiles(fileLocation, partFile);
                        fileCount   = 0;
                        foreach (string fileName in fileEntries)
                        {
                            fileCount += 1;
                            ProcessInputFile("PART", fileName);
                        }
                        WriteLine("<br/>Start Plant Data file processing.");
                        //originalFile = fileLocation + ConfigurationSettings.AppSettings["PlantDataFile"];
                        fileEntries = Directory.GetFiles(fileLocation, plantDataFile);
                        fileCount   = 0;
                        foreach (string fileName in fileEntries)
                        {
                            fileCount += 1;
                            ProcessInputFile("PLANT_DATA", fileName);
                        }
                        //WriteLine("<br/>Start Currency Data file processing.");
                        //originalFile = fileLocation + currencyFile;
                        //ProcessInputFile("CURRENCY_DATA", originalFile);
                        WriteLine("<br/><br/>");
                    }
                    catch (Exception ex)
                    {
                        WriteLine("Error: " + ex.ToString());
                    }
                }
            }

            WriteLogFile();
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.Clear();

                if (!String.IsNullOrEmpty(context.Request.QueryString["DOC_ID"]))
                {
                    String document_id = context.Request.QueryString["DOC_ID"];
                    String fileName    = "attachment";

                    Decimal doc_id   = decimal.Parse(document_id);
                    string  fileType = "";
                    String  mimeType = "";

                    if (!string.IsNullOrEmpty(context.Request.QueryString["DOC"]))
                    {
                        switch (context.Request.QueryString["DOC"])
                        {
                        case "a":                                 // attachment
                            ATTACHMENT a = SQMDocumentMgr.GetAttachment(doc_id);
                            fileType = Path.GetExtension(a.FILE_NAME);

                            if (!string.IsNullOrEmpty(context.Request.QueryString["FILE_NAME"]))
                            {
                                fileName = context.Request.QueryString["FILE_NAME"];
                            }
                            else
                            {
                                fileName += fileType;
                            }

                            mimeType = SQM.Website.Classes.FileExtensionConverter.ToMIMEType(fileType);
                            context.Response.ContentType = mimeType;
                            //context.Response.BinaryWrite(a.ATTACHMENT_FILE.ATTACHMENT_DATA);

                            // mt  - use below for video streams ?
                            context.Response.AddHeader("content-disposition", "inline; filename=" + fileName);
                            context.Response.AddHeader("content-length", a.ATTACHMENT_FILE.ATTACHMENT_DATA.Length.ToString());
                            context.Response.OutputStream.Write(a.ATTACHMENT_FILE.ATTACHMENT_DATA, 0, a.ATTACHMENT_FILE.ATTACHMENT_DATA.Length);
                            context.Response.Flush();
                            break;

                        case "v":                                 // video
                            VIDEO v = MediaVideoMgr.SelectVideoById(doc_id);

                            // get the file from Azure
                            fileType = Path.GetExtension(v.FILE_NAME);

                            if (!string.IsNullOrEmpty(context.Request.QueryString["FILE_NAME"]))
                            {
                                fileName = context.Request.QueryString["FILE_NAME"];
                            }
                            else
                            {
                                fileName += fileType;
                            }

                            List <SETTINGS> sets               = SQMSettings.SelectSettingsGroup("MEDIA_UPLOAD", "");
                            string          storageContainer   = sets.Find(x => x.SETTING_CD == "STORAGE_CONTAINER").VALUE.ToString();
                            string          storageURL         = sets.Find(x => x.SETTING_CD == "STORAGE_URL").VALUE.ToString();
                            string          storageQueryString = sets.Find(x => x.SETTING_CD == "STORAGE_QUERY").VALUE.ToString();

                            // Retrieve storage account from connection string.
                            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                                CloudConfigurationManager.GetSetting("StorageConnectionString"));

                            // Create the blob client.
                            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                            // Retrieve reference to a previously created container.
                            CloudBlobContainer container = blobClient.GetContainerReference(storageContainer);

                            // Retrieve reference to a blob named "photo1.jpg".
                            CloudBlockBlob blockBlob = container.GetBlockBlobReference(v.VIDEO_ID + fileType);

                            // Save blob contents to a file.
                            //using (var fileStream = System.IO.File.OpenWrite(@"path\myfile"))
                            //{
                            //	blockBlob.DownloadToStream(fileStream);
                            //}

                            mimeType = SQM.Website.Classes.FileExtensionConverter.ToMIMEType(fileType);
                            context.Response.ContentType = mimeType;

                            byte[] b = new byte[16 * 1024];
                            using (MemoryStream memoryStream = new MemoryStream())
                            {
                                blockBlob.DownloadToStream(memoryStream);
                                //memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                                //memoryStream.Close();
                                b = memoryStream.ToArray();
                            }

                            context.Response.AddHeader("content-disposition", "inline; filename=" + fileName);
                            context.Response.AddHeader("content-length", v.FILE_SIZE.ToString());
                            context.Response.BinaryWrite(b);
                            context.Response.Flush();

                            //// the following is the code for finding the file in the database
                            //VIDEO_FILE vf = MediaVideoMgr.SelectVideoFileById(doc_id);

                            //fileType = Path.GetExtension(v.FILE_NAME);

                            //if (!string.IsNullOrEmpty(context.Request.QueryString["FILE_NAME"]))
                            //	fileName = context.Request.QueryString["FILE_NAME"];
                            //else
                            //	fileName += fileType;

                            //mimeType = SQM.Website.Classes.FileExtensionConverter.ToMIMEType(fileType);
                            //context.Response.ContentType = mimeType;

                            //// mt  - use below for video streams ?
                            //context.Response.AddHeader("content-disposition", "inline; filename=" + fileName);
                            //context.Response.AddHeader("content-length", vf.VIDEO_DATA.Length.ToString());
                            ////context.Response.OutputStream.Write(vf.VIDEO_DATA, 0, vf.VIDEO_DATA.Length);
                            //context.Response.BinaryWrite(vf.VIDEO_DATA);

                            //context.Response.Flush();

                            //// the following is the code for finding the file on the server
                            //fileType = Path.GetExtension(v.FILE_NAME);

                            //fileName = context.Server.MapPath(v.FILE_NAME);
                            //System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

                            //try
                            //{
                            //	if (fileInfo.Exists)
                            //	{
                            //		context.Response.Clear();
                            //		context.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileInfo.Name + "\"");
                            //		context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                            //		context.Response.ContentType = "application/octet-stream";
                            //		context.Response.TransmitFile(fileInfo.FullName);
                            //		context.Response.Flush();
                            //	}
                            //	else
                            //	{
                            //		throw new Exception("File not found");
                            //	}
                            //}
                            //catch (Exception ex)
                            //{
                            //	context.Response.ContentType = "text/plain";
                            //	context.Response.Write(ex.Message);
                            //}
                            //finally
                            //{
                            //	context.Response.End();
                            //}
                            break;

                        case "va":                                 // video attachment
                            VIDEO_ATTACHMENT va = SQMDocumentMgr.GetVideoAttachment(doc_id);
                            fileType = Path.GetExtension(va.FILE_NAME);

                            if (!string.IsNullOrEmpty(context.Request.QueryString["FILE_NAME"]))
                            {
                                fileName = context.Request.QueryString["FILE_NAME"];
                            }
                            else
                            {
                                fileName += fileType;
                            }

                            mimeType = SQM.Website.Classes.FileExtensionConverter.ToMIMEType(fileType);
                            context.Response.ContentType = mimeType;
                            //context.Response.BinaryWrite(a.ATTACHMENT_FILE.ATTACHMENT_DATA);

                            // mt  - use below for video streams ?
                            context.Response.AddHeader("content-disposition", "inline; filename=" + fileName);
                            context.Response.AddHeader("content-length", va.VIDEO_ATTACHMENT_FILE.VIDEO_ATTACH_DATA.Length.ToString());
                            context.Response.OutputStream.Write(va.VIDEO_ATTACHMENT_FILE.VIDEO_ATTACH_DATA, 0, va.VIDEO_ATTACHMENT_FILE.VIDEO_ATTACH_DATA.Length);
                            context.Response.Flush();
                            break;

                        default:                                 // document
                            DOCUMENT d = SQMDocumentMgr.GetDocument(doc_id);
                            fileType = Path.GetExtension(d.FILE_NAME);
                            // set this to whatever your format is of the image
                            context.Response.ContentType = fileType;
                            mimeType = SQM.Website.Classes.FileExtensionConverter.ToMIMEType(fileType);
                            context.Response.ContentType = mimeType;
                            //context.Response.AddHeader("content-length", d.DOCUMENT_DATA.Length.ToString());
                            //context.Response.OutputStream.Write(d.DOCUMENT_DATA, 0, d.DOCUMENT_DATA.Length);
                            context.Response.AddHeader("content-length", d.DOCUMENT_FILE.DOCUMENT_DATA.Length.ToString());
                            context.Response.OutputStream.Write(d.DOCUMENT_FILE.DOCUMENT_DATA, 0, d.DOCUMENT_FILE.DOCUMENT_DATA.Length);
                            context.Response.Flush();
                            break;
                        }
                    }
                }

                else
                {
                    context.Response.ContentType = "text/html";
                    context.Response.Write("<p>Document not found</p>");
                }
            }
            catch (Exception e)
            {
                //SQMLogger.LogException(e);
            }
        }