public void BruteForceSearcherFileOffsetsCorrect()
        {
            using (var fs = File.OpenRead(IntegrationHelpers.GetDocumentPath("Single Page Simple - from inkscape.pdf")))
            {
                var bytes = new StreamInputBytes(fs);

                var locations = BruteForceSearcher.GetObjectLocations(bytes);

                Assert.Equal(13, locations.Count);

                Assert.Equal(6183, locations[new IndirectReference(1, 0)]);
                Assert.Equal(244, locations[new IndirectReference(2, 0)]);
                Assert.Equal(15, locations[new IndirectReference(3, 0)]);
                Assert.Equal(222, locations[new IndirectReference(4, 0)]);
                Assert.Equal(5766, locations[new IndirectReference(5, 0)]);
                Assert.Equal(353, locations[new IndirectReference(6, 0)]);
                Assert.Equal(581, locations[new IndirectReference(7, 0)]);
                Assert.Equal(5068, locations[new IndirectReference(8, 0)]);
                Assert.Equal(5091, locations[new IndirectReference(9, 0)]);

                var s = GetStringAt(bytes, locations[new IndirectReference(3, 0)]);
                Assert.StartsWith("3 0 obj", s);
            }
        }
Beispiel #2
0
        public async Task PUTProfile_ReturnsBadRequest_WhenModelInvalid()
        {
            // Arrange
            var model = new ProfileModel
            {
                UserName  = "******",
                Email     = "BadEmail",
                FirstName = "John",
                LastName  = "Doe"
            };

            var token = await IntegrationHelpers.GetAuthorizationTokenAsync(_client);

            using var request             = new HttpRequestMessage(HttpMethod.Put, "/api/account/profile");
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            request.Content = IntegrationHelpers.CreateHttpContent(model);

            // Act
            using var response = await _client.SendAsync(request);

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
        }
Beispiel #3
0
        public void CanMerge2SimpleDocumentsReversed()
        {
            var one = IntegrationHelpers.GetDocumentPath("Single Page Simple - from open office.pdf");
            var two = IntegrationHelpers.GetDocumentPath("Single Page Simple - from inkscape.pdf");

            var result = PdfMerger.Merge(one, two);

            System.IO.File.WriteAllBytes(@"C:\temp\merged.pdf", result);

            using (var document = PdfDocument.Open(result, ParsingOptions.LenientParsingOff))
            {
                Assert.Equal(2, document.NumberOfPages);

                Assert.Equal(1.5m, document.Version);

                var page1 = document.GetPage(1);

                Assert.Equal("I am a simple pdf.", page1.Text);

                var page2 = document.GetPage(2);

                Assert.Equal("Write something inInkscape", page2.Text);
            }
        }
Beispiel #4
0
        public void CanMergeWithSelection()
        {
            var first    = IntegrationHelpers.GetDocumentPath("Multiple Page - from Mortality Statistics.pdf");
            var contents = File.ReadAllBytes(first);

            var toCopy = new[] { 2, 1, 4, 3, 6, 5 };
            var result = PdfMerger.Merge(new [] { contents }, new [] { toCopy });

            WriteFile(nameof(CanMergeWithSelection), result);

            using (var existing = PdfDocument.Open(contents, ParsingOptions.LenientParsingOff))
                using (var merged = PdfDocument.Open(result, ParsingOptions.LenientParsingOff))
                {
                    Assert.Equal(6, merged.NumberOfPages);

                    for (var i = 1; i < merged.NumberOfPages; i++)
                    {
                        Assert.Equal(
                            existing.GetPage(toCopy[i - 1]).Text,
                            merged.GetPage(i).Text
                            );
                    }
                }
        }
Beispiel #5
0
        void TestDataAssay()
        {
            List <string> exts = new List <string>()
            {
                ".dat", ".cnn"
            };
            FileList <TestDataFile> hdlr = new FileList <TestDataFile>();

            hdlr.Init(exts, ctrllog);
            FileList <TestDataFile> files = null;

            // initialize operation timer here
            NC.App.Opstate.ResetTimer(filegather, files, 170, (int)NC.App.AppContext.StatusTimerMilliseconds);
            FireEvent(EventType.ActionPrep, this);
            NC.App.Opstate.StampOperationStartTime();

            if (NC.App.AppContext.FileInputList == null)
            {
                files = (FileList <TestDataFile>)hdlr.BuildFileList(NC.App.AppContext.FileInput, NC.App.AppContext.Recurse, true);
            }
            else
            {
                files = (FileList <TestDataFile>)hdlr.BuildFileList(NC.App.AppContext.FileInputList);
            }
            if (files == null || files.Count < 1)
            {
                NC.App.Opstate.StopTimer();
                NC.App.Opstate.StampOperationStopTime();
                FireEvent(EventType.ActionStop, this);
                ctrllog.TraceEvent(LogLevels.Warning, 33085, "No usable Test data/Disk .dat or .cnn files found");
                return;
            }

            AcquireParameters orig_acq = new AcquireParameters(NC.App.Opstate.Measurement.AcquireState);
            Detector          curdet   = NC.App.Opstate.Measurement.Detector;

            AssaySelector.MeasurementOption mo = NC.App.Opstate.Measurement.MeasOption;

            if (curdet.AB.Unset)
            {
                ABKey abkey = new ABKey(curdet.MultiplicityParams, 512);  // NEXT: maxbins is arbitrary, just the first of many for VSR
                LMRawAnalysis.SDTMultiplicityCalculator.SetAlphaBeta(abkey, curdet.AB);
            }

            // Each .dat file is a separate measurement
            foreach (TestDataFile td in files)
            {
                Measurement meas = null;
                ResetMeasurement();

                try
                {
                    if (!td.OpenForReading())
                    {
                        continue;
                    }
                    if (NC.App.Opstate.IsQuitRequested)
                    {
                        break;
                    }
                    uint run_seconds;

                    ushort number_good_runs      = 0;
                    ushort total_number_runs     = 0;
                    double run_count_time        = 0;
                    double total_good_count_time = 0;

                    if (mo != AssaySelector.MeasurementOption.holdup)
                    {
                        /* number of good runs */
                        string l = td.reader.ReadLine();
                        ushort.TryParse(l, out number_good_runs);
                        if (number_good_runs == 0)
                        {
                            ctrllog.TraceEvent(LogLevels.Error, 440, "This measurement has no good cycles.");
                            continue;
                        }
                        /* run count time */
                        l = td.reader.ReadLine();
                        double.TryParse(l, out run_count_time);
                        if (run_count_time <= 0.0)
                        {
                            ctrllog.TraceEvent(LogLevels.Error, 441, "Count time is <= 0.");
                            continue;
                        }
                    }

                    // update acq and then meas here
                    AcquireParameters newacq = ConfigureAcquireState(curdet, orig_acq, DateTimeOffset.Now, number_good_runs, td.Filename);
                    IntegrationHelpers.BuildMeasurement(newacq, curdet, mo);
                    meas          = NC.App.Opstate.Measurement;
                    meas.MeasDate = newacq.MeasDateTime;
                    meas.Persist();  // preserve the basic results record

                    /* convert to total count time */
                    total_number_runs     = number_good_runs;
                    total_good_count_time = number_good_runs *
                                            run_count_time;
                    meas.RequestedRepetitions = total_number_runs;

                    // update the acq status and do the persist

                    /* read in run data */
                    for (int i = 0; i < number_good_runs; i++)
                    {
                        /* run date and time (IAEA format) */
                        run_seconds = (uint)(i * (ushort)run_count_time); // from start time
                        AddTestDataCycle(i, run_seconds, run_count_time, meas, td);
                        if (i % 8 == 0)
                        {
                            FireEvent(EventType.ActionInProgress, this);
                        }
                    }
                    FireEvent(EventType.ActionInProgress, this);

                    if (meas.MeasOption == AssaySelector.MeasurementOption.verification &&
                        meas.INCCAnalysisState.Methods.Has(AnalysisMethod.AddASource) &&
                        meas.AcquireState.well_config == WellConfiguration.Passive)
                    {
                        AddASourceSetup aass = IntegrationHelpers.GetCurrentAASSParams(meas.Detector);
                        for (int n = 1; n <= aass.number_positions; n++)
                        {
                            /* number of good runs */
                            string l = td.reader.ReadLine();
                            if (td.reader.EndOfStream)
                            {
                                ctrllog.TraceEvent(LogLevels.Error, 440, "No add-a-source data found in disk file. AAS p" + n.ToString());
                            }
                            ushort.TryParse(l, out number_good_runs);
                            if (number_good_runs == 0)
                            {
                                ctrllog.TraceEvent(LogLevels.Error, 440, "This measurement has no good cycles. AAS p" + n.ToString());
                                continue;
                            }
                            /* run count time */
                            l = td.reader.ReadLine();
                            double.TryParse(l, out run_count_time);
                            if (run_count_time <= 0.0)
                            {
                                ctrllog.TraceEvent(LogLevels.Error, 441, "Count time is <= 0. AAS p" + n.ToString());
                                continue;
                            }
                            /* read in run data */
                            for (int i = 0; i < number_good_runs; i++)
                            {
                                /* run date and time (IAEA format) */
                                run_seconds = (uint)((n + 1) * (i + 1) * (ushort)run_count_time); // from start time
                                AddTestDataCycle(i, run_seconds, run_count_time, meas, td, " AAS p" + n.ToString(), n);
                                if (i % 8 == 0)
                                {
                                    FireEvent(EventType.ActionInProgress, this);
                                }
                            }
                            FireEvent(EventType.ActionInProgress, this);
                        }
                    }
                }
                catch (Exception e)
                {
                    NC.App.Opstate.SOH = OperatingState.Trouble;
                    ctrllog.TraceException(e, true);
                    ctrllog.TraceEvent(LogLevels.Error, 437, "Test data file processing stopped with error: '" + e.Message + "'");
                }
                finally
                {
                    td.CloseReader();
                    NC.App.Loggers.Flush();
                }
                FireEvent(EventType.ActionInProgress, this);
                ComputeFromINCC5SRData(meas);
                FireEvent(EventType.ActionInProgress, this);
            }

            NC.App.Opstate.ResetTokens();
            NC.App.Opstate.SOH = OperatingState.Stopping;
            NC.App.Opstate.StampOperationStopTime();
            FireEvent(EventType.ActionFinished, this);
        }
Beispiel #6
0
        /// <summary>
        /// Process one or more .NCC Review measurement data files, with related .NOP/.COP files.
        /// Presence of NOP/COP files is optional
        /// See Import Operator Declarations from Operator Review and Measurements from Radiation Review p. 24,
        /// See Operator Declaration File Format p. 87,
        /// See Operator Declaration File Format for Curium Ratio Measurements p. 88,
        /// See Radiation Review Measurement Data File Format p. 93, INCC Software Users Manual, March 29, 2009
        /// </summary>
        void INCCReviewFileProcessing()
        {
            FireEvent(EventType.ActionPrep, this);
            NC.App.Opstate.StampOperationStartTime();
            // This code would be the same for an interactive version of this operation
            //  > Start here
            // first find and process and .NOP files
            List <string> exts = new List <string>()
            {
                ".nop", ".cop"
            };
            FileList <CSVFile> hdlr = new FileList <CSVFile>();

            hdlr.Init(exts, ctrllog);
            FileList <CSVFile> files   = null;
            OPFiles            opfiles = new OPFiles();

            // The INCC5 semantics
            if (NC.App.AppContext.FileInputList == null)
            {
                files = (FileList <CSVFile>)hdlr.BuildFileList(NC.App.AppContext.FileInput, NC.App.AppContext.Recurse, true);
            }
            else
            {
                files = (FileList <CSVFile>)hdlr.BuildFileList(NC.App.AppContext.FileInputList);
            }
            if (files != null && files.Count > 0)
            {
                // construct lists of isotopics and items from the NOP and COP files
                opfiles.Process(files);
                ctrllog.TraceEvent(LogLevels.Verbose, 33085, "NOP items " + opfiles.Results.ItemIds.Count);
                //ctrllog.TraceEvent(LogLevels.Verbose, 33085, "COP entries " + opfiles.Results.COPRatioRecs.Count);
            }
            else
            {
                ctrllog.TraceEvent(LogLevels.Warning, 33085, "No operator declarations available, continuing with default values");
            }

            // process the NCC files only
            INCCFileOrFolderInfo foo = new INCCFileOrFolderInfo(ctrllog, "*.NCC");

            if (NC.App.AppContext.FileInputList == null)
            {
                foo.SetPath(NC.App.AppContext.FileInput);
            }
            else
            {
                foo.SetFileList(NC.App.AppContext.FileInputList);
            }
            foo.eh += new TransferEventHandler((s, e) => { FireEvent(EventType.ActionInProgress, e); });
            List <INCCTransferBase> res = foo.Restore();
            // use RemoveAll to cull those NCC files that reference a non-existent detector
            DetectorList dl = NC.App.DB.Detectors;

            foreach (INCCReviewFile rf in res)
            {
                List <Detector> tdk = dl.FindAll(d => 0 == string.Compare(d.Id.DetectorName, rf.detector, true));
                if (tdk.Count < 1)
                {
                    rf.skip = true;
                    ctrllog.TraceEvent(LogLevels.Warning, 33085, "No detector " + rf.detector + " defined, cannot complete processing NCC review file " + System.IO.Path.GetFileName(rf.Path));
                }
            }
            res.RemoveAll(rf => (rf as INCCReviewFile).skip);
            res.Sort((rf1, rf2) => // sort chronologically
            {
                return(DateTime.Compare((rf1 as INCCReviewFile).dt, (rf2 as INCCReviewFile).dt));
            });
            /// end here > The sorted, filtered and processed list here would be returned to the UI for display and interactive selection
            if (res == null || res.Count < 1)
            {
                NC.App.Opstate.StopTimer();
                NC.App.Opstate.StampOperationStopTime();
                FireEvent(EventType.ActionStop, this);
                ctrllog.TraceEvent(LogLevels.Warning, 33085, "No usable NCC review files found in " + System.IO.Path.GetFullPath(foo.GetPath()));
                return;
            }

            AcquireParameters orig_acq = new AcquireParameters(NC.App.Opstate.Measurement.AcquireState);

            // Each NCC file is a separate measurement
            foreach (INCCReviewFile irf in res)
            {
                ResetMeasurement();
                if (NC.App.Opstate.IsQuitRequested)
                {
                    break;
                }
                // Find the detector named in the NCC file (existence shown in earlier processing above)
                Detector curdet = NC.App.DB.Detectors.Find(d => string.Compare(d.Id.DetectorName, irf.detector, true) == 0);

                if (curdet.AB.Unset)
                {
                    ABKey abkey = new ABKey(curdet.MultiplicityParams, 512);                      // NEXT: maxbins is arbitrary, just the first of many for VSR
                    LMRawAnalysis.SDTMultiplicityCalculator.SetAlphaBeta(abkey, curdet.AB);
                }

                // set up acquire state based on the NCC file content
                AcquireParameters newacq = ConfigureAcquireState(curdet, orig_acq, irf);

                AssaySelector.MeasurementOption mo = NCCMeasOption(irf);
                // make a temp MeasId
                MeasId thisone = new MeasId(mo, newacq.MeasDateTime);
                // get the list of measurement Ids for this detector
                List <MeasId> list    = NC.App.DB.MeasurementIds(curdet.Id.DetectorName, mo.PrintName());
                MeasId        already = list.Find(mid => mid.Equals(thisone));
                if (already != null)
                {
                    // URGENT: do the replacement as it says
                    ctrllog.TraceEvent(LogLevels.Warning, 33085, "Replacing the matching {0} measurement, timestamp {1} (in a future release)", already.MeasOption.PrintName(), already.MeasDateTime.ToString());
                }

                IntegrationHelpers.BuildMeasurement(newacq, curdet, mo);
                Measurement meas = NC.App.Opstate.Measurement;
                meas.MeasDate = newacq.MeasDateTime; // use the date and time from the NCC file content

                meas.Persist();                      // preserve the basic results record
                if (AssaySelector.ForMass(meas.MeasOption) && !meas.INCCAnalysisState.Methods.AnySelected())
                {
                    ctrllog.TraceEvent(LogLevels.Warning, 437, "No mass methods for " + meas.INCCAnalysisState.Methods.selector.ToString());
                }

                try
                {
                    ushort total_number_runs     = 0;
                    double run_count_time        = 0;
                    double total_good_count_time = 0;

                    if (irf.num_runs == 0)
                    {
                        ctrllog.TraceEvent(LogLevels.Error, 440, "This measurement has no good cycles.");
                        continue;
                    }
                    if (meas.MeasOption == AssaySelector.MeasurementOption.holdup)
                    {
                        continue;
                    }

                    /* convert to total count time */
                    total_number_runs     = irf.num_runs;
                    total_good_count_time = irf.num_runs *
                                            run_count_time;
                    meas.RequestedRepetitions = total_number_runs;

                    // convert runs to cycles
                    for (int i = 0; i < irf.num_runs; i++)
                    {
                        /* run date and time (IAEA format) */
                        AddReviewFileCycle(i, irf.runs[i], irf.times[i], meas, irf.Path);
                        if (i % 8 == 0)
                        {
                            FireEvent(EventType.ActionInProgress, this);
                        }
                    }
                    FireEvent(EventType.ActionInProgress, this);

                    // NEXT: handle true AAS cycles as in INCC5
                    if (meas.MeasOption == AssaySelector.MeasurementOption.verification &&
                        meas.INCCAnalysisState.Methods.Has(AnalysisMethod.AddASource) &&
                        meas.AcquireState.well_config == WellConfiguration.Passive)
                    {
                        ctrllog.TraceEvent(LogLevels.Error, 440, "No add-a-source data processed because the implementation is incomplete. AAS");
                        //AddASourceSetup aass = IntegrationHelpers.GetCurrentAASSParams(meas.Detector);
                        //for (int n = 1; n <= aass.number_positions; n++)
                        //{
                        //    /* number of good runs */
                        //    string l = td.reader.ReadLine();
                        //    if (td.reader.EndOfStream)
                        //    {
                        //        ctrllog.TraceEvent(LogLevels.Error, 440, "No add-a-source data found in disk file. " + "AAS p" + n.ToString());

                        //    }
                        //}
                    }
                }
                catch (Exception e)
                {
                    NC.App.Opstate.SOH = OperatingState.Trouble;
                    ctrllog.TraceException(e, true);
                    ctrllog.TraceEvent(LogLevels.Error, 437, "NCC file processing stopped with error: '" + e.Message + "'");
                }
                finally
                {
                    NC.App.Loggers.Flush();
                }
                FireEvent(EventType.ActionInProgress, this);
                ComputeFromINCC5SRData(meas);
                FireEvent(EventType.ActionInProgress, this);
            }


            NC.App.Opstate.ResetTokens();
            NC.App.Opstate.SOH = OperatingState.Stopping;
            NC.App.Opstate.StampOperationStopTime();
            FireEvent(EventType.ActionFinished, this);
        }
Beispiel #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!SessionManager.SessionReadyForApiIntegration(Session))
            {
                ErrorMessage.Text = "Improper launch information supplied.";
                return;
            }
            var labIdString = Request[Constants.QueryStringLabId];

            if (string.IsNullOrWhiteSpace(labIdString))
            {
                ErrorMessage.Text = "Missing or empty lab profile id.";
                return;
            }
            int labProfileId;

            if (!int.TryParse(labIdString, out labProfileId))
            {
                ErrorMessage.Text = "Improper lab profile id.";
                return;
            }
            Tracing.WriteTraceMessage("Profile id : {0}", labProfileId);
            var client = IntegrationHelpers.GetLabOnDemandApiClientForSession(Session);

            var allowAnonymousLaunch = SessionManager.SessionAllowsAnonymous(Session);

            if (!Request.IsAuthenticated && !allowAnonymousLaunch)
            {
                throw new HttpException(403, "You must be signed in to continue.");
            }

            try {
                LaunchResponse launchResponse;
                string         userExternalId = string.Empty;
                if (Request.IsAuthenticated)
                {
                    userExternalId = SessionManager.GetActiveUserName(Session);
                    var userFirstName = "SharePoint";
                    var userLastName  = "User";
                    var userEmail     = IdentityHelpers.GetUsedEmail(Page.User as IClaimsPrincipal);
                    Tracing.WriteTraceMessage("Identifiers : \"{0}\" \"{1}\" \"{2}\" \"{3}\"", userExternalId,
                                              userFirstName, userLastName, userEmail);
                    launchResponse = client.Launch(labProfileId, userExternalId, userFirstName, userLastName, userEmail,
                                                   false);
                }
                else
                {
                    launchResponse = client.LaunchAnonymous(labProfileId);
                }
                switch (launchResponse.Result)
                {
                case LaunchResult.Success:
                    Response.Redirect(launchResponse.Url, true);
                    return;

                case LaunchResult.SavedInstanceExists:
                    if (string.IsNullOrWhiteSpace(userExternalId))
                    {
                        throw new HttpException(500, "Anonymous launch call returned saved instance response");
                    }
                    var savedSessionResponse = client.UserRunningAndSavedLabs(userExternalId);
                    var savedSession         = savedSessionResponse.SavedLabs.First(s => s.LabProfileId == labProfileId);
                    var resumeResponse       = client.Resume(savedSession.LabInstanceId);
                    Response.Redirect(resumeResponse.Url, true);
                    return;

                case LaunchResult.InsufficientResources:
                    // On the hosting side, resources necessary to launch the lab were unavailable.  This generally means
                    // a configuration error in the lab.
                    throw new LodInsufficientResourcesException();

                case LaunchResult.ApiIntegrationMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the INTEGRATION (across all users and labs) has been reached.
                    throw new LodIntegrationMaxActiveLabInstancesReachedException();

                case LaunchResult.ApiIntegrationMaxRamUsageReached:
                    // The memory limit for all running instances across the INTEGRATION (across all users and labs) has been reached.
                    throw new LodIntegrationMaxRamUsageReachedException();

                case LaunchResult.UserMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the USER has been reached... note that as of when this code was
                    // written, users are only allowed to have one instance per user, so the error message in the exception assumes
                    // that is the case.  In production, you may want to be less specific about this as a futureproofing decision;
                    // however, you would also know what the maximum per user is allowed to be if it's not "one," so you can
                    // do the right thing.
                    throw new LodUserMaxActiveLabInstancesReachedException();

                case LaunchResult.UserMaxRamUsageReached:
                    // The memory limit for all running instances for the USER been reached
                    throw new LodUserMaxRamUsageReachedException();

                case LaunchResult.LabSeriesMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the LAB SERIES (across all users and integrations) has been reached.
                    throw new LodLabSeriesMaxActiveLabInstancesReachedException();

                case LaunchResult.LabSeriesMaxRamUsageReached:
                    // The memory limit for all running instances for the LAB SERIES (across all users and integrations) has been reached.
                    throw new LodLabSeriesMaxRamUsageReachedException();

                case LaunchResult.LabOrganizationMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the LAB OWNER ORGANIZATION (PUBLISHER) (across all users and integrations) has been reached.
                    throw new LodLabOrganizationMaxActiveLabInstancesReachedException();

                case LaunchResult.LabOrganizationMaxRamUsageReached:
                    // The memory limit for all running instances for the LAB OWNER ORGANIZATION (PUBLISHER) (across all users and integrations) has been reached.
                    throw new LodLabOrganizationMaxRamUsageReachedException();

                case LaunchResult.LabProfileMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the LAB PROFILE (across all users and integrations) has been reached.
                    throw new LodLabProfileMaxActiveLabInstancesReachedException();

                case LaunchResult.UserOrganizationMaxActiveLabInstancesReached:
                    // The maximum number of lab instances possible for the USER'S ORGANIZATION (across all users and integrations) has been reached.
                    throw new LodUserOrganizationMaxActiveLabInstancesReachedException();

                case LaunchResult.UserOrganizationMaxRamUsageReached:
                    // The memory limit for all running instances for the USER'S ORGANIZATION (across all users and integrations) has been reached.
                    throw new LodUserOrganizationMaxRamUsageReachedException();

                case LaunchResult.Error:
                    // A non-specific error occurred creating the lab instance.  This is not expected to be reported.
                    throw new LodLabLaunchErrorException(launchResponse.Error);

                default:
                    // There are no other response codes.  This is here to keep the compiler happy, as well as making sure that
                    // we are somewhat future-proofed.  Perhaps throwing a generic launch exception would be better.
                    throw new HttpException(404, "The launch failed - profile not found?");
                }
            }
            catch (Exception ex) {
                ErrorMessage.Text = ex.Message;
            }
        }
Beispiel #8
0
    private void LoadOppCompanies()
    {
        lbxSystems.Items.Clear();
        bool   mapped   = false;
        string linkedTo = String.Empty;
        bool   restrict = IntegrationManager.SourceMapping.RestrictToSingleAccount.HasValue &&
                          IntegrationManager.SourceMapping.RestrictToSingleAccount.Value &&
                          IntegrationManager.SourceAccount.GlobalSyncId != null;

        if (!restrict)
        {
            IList    mappings = IntegrationHelpers.GetAccountingFeeds();
            ListItem item;
            foreach (IAppIdMapping map in mappings)
            {
                bool addMapping = true;
                if (map.Enabled.HasValue && map.Enabled.Value)
                {
                    foreach (IAccountOperatingCompany oppCompany in IntegrationManager.SourceAccount.AccountOperatingCompanies)
                    {
                        if (map.Equals(oppCompany.IntegrationApplication))
                        {
                            linkedTo  += String.Format("{0}, ", map.Name);
                            mapped     = true;
                            addMapping = false;
                            break;
                        }
                    }
                    if (addMapping)
                    {
                        item       = new ListItem();
                        item.Text  = map.Name;
                        item.Value = map.Id.ToString();
                        lbxSystems.Items.Add(item);
                    }
                }
            }
        }
        if (lbxSystems.Items.Count <= 0)
        {
            if (!String.IsNullOrEmpty(linkedTo))
            {
                linkedTo = linkedTo.Substring(0, linkedTo.Length - 2);
            }
            lblSearchMsg.Text = restrict
                                    ? String.Format(GetLocalResourceObject("error_RestrictToSingleAccount").ToString(),
                                                    IntegrationManager.SourceAccount.AccountName,
                                                    IntegrationManager.SourceAccount.OperatingCompany != null
                                                        ? IntegrationManager.SourceAccount.OperatingCompany.Name
                                                        : String.Empty)
                                    : (mapped
                                           ? String.Format(GetLocalResourceObject("error_AlreadyMapped").ToString(),
                                                           IntegrationManager.SourceAccount.AccountName, linkedTo)
                                           : GetLocalResourceObject("error_NoAccountingFeeds").ToString());
            lblSystem.Visible     = false;
            lbxSystems.Visible    = false;
            lblCreateLink.Visible = false;
            btnNext.Visible       = false;
            btnCancel.Text        = GetLocalResourceObject("Close.Caption").ToString();
        }
        else if (lbxSystems.Items.Count.Equals(1))
        {
            btnNext.Visible    = true;
            lblSystem.Visible  = true;
            lbxSystems.Visible = true;
            lblSearchMsg.Text  = GetLocalResourceObject("lblSearchMsg_SingleFeed.Caption").ToString();
        }
        else
        {
            lblSearchMsg.Text  = GetLocalResourceObject("lblSearchMsg.Caption").ToString();
            btnNext.Visible    = true;
            lblSystem.Visible  = true;
            lbxSystems.Visible = true;
        }
    }
    private void LoadAccountTasks(EntityPage page)
    {
        var canPromote = RoleSecurityService.HasAccess("Entities/Account/PromoteAccount");
        var integrated = BusinessRuleHelper.IsIntegrationContractEnabled();

        if (page.IsDetailMode)
        {
            divEntityAccountList.Style.Add("display", "none");
            divEntityAccountDetails.Style.Add("display", "block");
            if (integrated)
            {
                IAccount account = EntityFactory.GetRepository <IAccount>().Get(page.EntityContext.EntityID);
                if (account == null)
                {
                    hideIntegration();
                    return;
                }
                lblLinkAccount.Visible = canPromote;
                imgLinkAccount.Visible = canPromote;
                if (account.PromotedToAccounting ?? false)
                {
                    IAppIdMapping slxFeed = IntegrationHelpers.GetSlxAccountingFeed();
                    lblLinkAccount.Text        = GetLocalResourceObject("lblLinkAnotherAccount.Caption").ToString();
                    lblNotLinkedStatus.Visible = false;
                    lblLinkedStatus.Visible    = true;
                    updateAccountPanel.Update();
                    lblLinkAccount.Visible = canPromote && !(slxFeed.RestrictToSingleAccount ?? false);
                    imgLinkAccount.Visible = canPromote && !(slxFeed.RestrictToSingleAccount ?? false);
                }
                else
                {
                    lblLinkAccount.Text        = GetLocalResourceObject("lblLinkAccount.Caption").ToString();
                    lblNotLinkedStatus.Visible = true;
                    lblLinkedStatus.Visible    = false;
                }
                lblLastUpdate.Text = String.Format(GetLocalResourceObject("lblLastUpdate.Caption").ToString(),
                                                   TimeZone.UTCDateTimeToLocalTime((DateTime)account.ModifyDate));
            }
            else
            {
                hideIntegration();
            }
            if (page.IsNewEntity)
            {
                updateAccountPanel.Update();
            }
        }
        else
        {
            if (!integrated)
            {
                hideIntegration();
            }
            else if (!canPromote)
            {
                rowlnkLinkAccount_List.Style.Add("display", "none");
            }
            divEntityAccountList.Style.Add("display", "block");
            divEntityAccountDetails.Style.Add("display", "none");
            lblLinkStatus.Visible = false;
        }
    }
Beispiel #10
0
        void DatazFileAssay()
        {
            List <string> exts = new List <string>()
            {
                ".dataz"
            };
            FileList <DatazFile> hdlr = new FileList <DatazFile>();

            hdlr.Init(exts, ctrllog);
            FileList <DatazFile> files = null;

            // initialize operation timer here
            NC.App.Opstate.ResetTimer(filegather, files, 170, (int)NC.App.AppContext.StatusTimerMilliseconds);
            FireEvent(EventType.ActionPrep, this);
            NC.App.Opstate.StampOperationStartTime();

            if (NC.App.AppContext.FileInputList == null)
            {
                files = (FileList <DatazFile>)hdlr.BuildFileList(NC.App.AppContext.FileInput, NC.App.AppContext.Recurse, true);
            }
            else
            {
                files = (FileList <DatazFile>)hdlr.BuildFileList(NC.App.AppContext.FileInputList);
            }
            if (files == null || files.Count < 1)
            {
                NC.App.Opstate.StopTimer();
                NC.App.Opstate.StampOperationStopTime();
                FireEvent(EventType.ActionStop, this);
                ctrllog.TraceEvent(LogLevels.Warning, 33085, "No usable Dataz files found");
                return;
            }

            AssaySelector.MeasurementOption mo = NC.App.Opstate.Measurement.MeasOption;

            foreach (DatazFile mc in files)
            {
                Measurement meas = null;

                try
                {
                    if (!mc.OpenForReading())
                    {
                        continue;
                    }
                    if (NC.App.Opstate.IsQuitRequested)
                    {
                        break;
                    }

                    mc.ScanSections();
                    mc.ProcessSections();
                    if (mc.Cycles.Count == 0)
                    {
                        ctrllog.TraceEvent(LogLevels.Error, 404, "This Dataz file has no good cycles.");
                    }
                    if (mc.Plateaux.Count == 0)
                    {
                        ctrllog.TraceEvent(LogLevels.Error, 404, $"This Dataz file has no defined sequences, over {mc.Cycles.Count} cycles.");
                    }
                    else
                    {
                        AcquireParameters orig_acq = new AcquireParameters(NC.App.Opstate.Measurement.AcquireState);
                        Detector          curdet   = NC.App.Opstate.Measurement.Detector;
                        if (mc.AcquistionStateChanged)
                        {
                            orig_acq = new AcquireParameters(NC.App.Opstate.Measurement.AcquireState);
                            curdet   = mc.DataZDetector;
                            if (curdet.AB.Unset)
                            {
                                ABKey abkey = new ABKey(curdet.MultiplicityParams, mc.MaxBins);
                                LMRawAnalysis.SDTMultiplicityCalculator.SetAlphaBeta(abkey, curdet.AB);
                            }
                        }

                        ctrllog.TraceInformation($"{mc.Cycles.Count} cycles and {mc.Plateaux.Count} sequences encountered in Dataz file {mc.Filename}");
                        System.Collections.IEnumerator iter = mc.GetSequences();
                        while (iter.MoveNext())
                        {
                            DatazFile.Plateau pla = (DatazFile.Plateau)iter.Current;
                            ResetMeasurement();
                            // update acq and then meas here
                            AcquireParameters newacq = ConfigureAcquireState(curdet, orig_acq, pla.Cycles[0].DTO, (ushort)pla.Num, mc.Filename);
                            newacq.data_src = ConstructedSource.DatazFile;
                            IntegrationHelpers.BuildMeasurement(newacq, curdet, mo);
                            meas          = NC.App.Opstate.Measurement;
                            meas.MeasDate = newacq.MeasDateTime;
                            meas.Persist();  // preserve the basic results record
                            meas.RequestedRepetitions = (ushort)pla.Num;
                            for (int i = 0; i < meas.RequestedRepetitions; i++)
                            {
                                /* run date and time (IAEA format) */
                                AddMCSRDataCycle(i, pla.Cycles[i], meas, mc.Filename);
                                if (i % 8 == 0)
                                {
                                    FireEvent(EventType.ActionInProgress, this);
                                }
                            }
                            FireEvent(EventType.ActionInProgress, this);
                            ComputeFromINCC5SRData(meas);
                            FireEvent(EventType.ActionInProgress, this);
                        }
                    }
                }
                catch (Exception e)
                {
                    NC.App.Opstate.SOH = OperatingState.Trouble;
                    ctrllog.TraceException(e, true);
                    ctrllog.TraceEvent(LogLevels.Error, 437, "Dataz data file processing stopped with error: '" + e.Message + "'");
                }
                finally
                {
                    mc.CloseReader();
                    NC.App.Loggers.Flush();
                }
            }

            NC.App.Opstate.ResetTokens();
            NC.App.Opstate.SOH = OperatingState.Stopping;
            NC.App.Opstate.StampOperationStopTime();
            FireEvent(EventType.ActionFinished, this);
        }
Beispiel #11
0
            bool SetNewAcquireState(Detector det0, string mtl, string fac, string mba, string msg)
            {
                AcquireParameters acq = NC.App.DB.LastAcquire();
                Detector          det = NC.App.DB.Detectors.GetItByDetectorId(det0.Id.DetectorName);

                if (det == null)
                {
                    det = det0;
                    NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Warning, 32441, "Creating new detector " + det.Id.DetectorName + " now");
                    // add fresh param instances to in-memory maps
                    NC.App.DB.NormParameters.Map.Add(det, new NormParameters());
                    NC.App.DB.UnattendedParameters.Map.Add(det, new UnattendedParameters());
                    NC.App.DB.BackgroundParameters.Map.Add(det, new BackgroundParameters());
                    NC.App.DB.AASSParameters.Map.Add(det, new AddASourceSetup());
                    NC.App.DB.HVParameters.Map.Add(det, new HVCalibrationParameters());
                    NC.App.DB.Detectors.Add(det); // add detector to in-memory list

                    IntegrationHelpers.PersistDetectorAndAssociations(det);
                }
                else
                {
                    // Apply any changes to GL, PD, HV (but not FA) to existing detector
                    if (SRParamUpdateNeeded(det.MultiplicityParams, det0.MultiplicityParams))
                    {
                        NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Warning, 32441, $"Modifying detector {det.Id.DetectorName} SR params");
                        det.SRParams.highVoltage  = det0.SRParams.highVoltage;
                        det.SRParams.predelayMS   = det0.SRParams.predelayMS;
                        det.SRParams.gateLengthMS = det0.SRParams.gateLengthMS;
                        NC.App.DB.UpdateDetectorParams(det);
                    }
                }
                INCCDB.Descriptor facdesc = null, mbadesc = null, mtldesc = null;
                if (!string.IsNullOrEmpty(fac))
                {
                    facdesc = NC.App.DB.Facilities.Get(fac);
                    if (facdesc == null)
                    {
                        NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Warning, 32441, "Creating " + fac + " facility");
                        facdesc = new INCCDB.Descriptor(fac, "Dataz creation source");
                        NC.App.DB.Facilities.Update(facdesc);
                    }
                }
                if (!string.IsNullOrEmpty(mba))
                {
                    mbadesc = NC.App.DB.MBAs.Get(mba);
                    if (mbadesc == null)
                    {
                        NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Warning, 32441, "Creating " + mba + " MBA");
                        mbadesc = new INCCDB.Descriptor(mba, "Dataz creation source");
                        NC.App.DB.MBAs.Update(mbadesc);
                    }
                }
                if (!string.IsNullOrEmpty(mtl))
                {
                    mtldesc = NC.App.DB.Materials.Get(mtl);
                    if (mtldesc == null)
                    {
                        NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Warning, 32441, "Creating " + mtl + " material type");
                        mtldesc = new INCCDB.Descriptor(mtl, "Dataz creation source");
                        NC.App.DB.Materials.Update(mtldesc);
                    }
                }
                acq.MeasDateTime        = DateTimeOffset.Now;
                DataZDetector           = NC.App.DB.Detectors.Find(d => string.Compare(d.Id.DetectorName, det0.Id.DetectorName, true) == 0);
                DataZDetector.Id.source = ConstructedSource.DatazFile;
                acq.data_src            = ConstructedSource.DatazFile;
                if (!string.IsNullOrEmpty(msg))
                {
                    acq.ending_comment     = true;
                    acq.ending_comment_str = msg;
                }
                if (AcquistionChangeNeeded(acq, det.Id.DetectorName, mtl, fac, mba))
                {
                    acq.detector_id      = string.Copy(det.Id.DetectorName);
                    acq.meas_detector_id = string.Copy(det.Id.DetectorName);
                    if (!string.IsNullOrEmpty(mtl))
                    {
                        acq.item_type = string.Copy(mtl);
                    }
                    if (facdesc != null)
                    {
                        acq.facility = facdesc;
                    }
                    if (mbadesc != null)
                    {
                        acq.mba = mbadesc;
                    }
                    INCCDB.AcquireSelector sel = new INCCDB.AcquireSelector(det, acq.item_type, acq.MeasDateTime);
                    NC.App.DB.AddAcquireParams(sel, acq);
                }
                else    // update existing entry
                {
                    NC.App.DB.UpdateAcquireParams(acq, det.ListMode);
                }

                AcquistionStateChanged = true;

                NC.App.Loggers.ControlLogger.TraceEvent(LogLevels.Info, 32444, $"The current detector/material now {acq.detector_id},{acq.item_type}");
                return(true);
            }