protected override Task Context()
        {
            _parameterMapper       = A.Fake <ParameterMapper>();
            _formulationRepository = A.Fake <IFormulationRepository>();
            _cloner = A.Fake <ICloner>();

            sut = new FormulationMapper(_parameterMapper, _formulationRepository, _cloner);

            _parameter1 = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: false)
                          .WithName("Param1");

            _parameter2 = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: true)
                          .WithName("Param2");

            _hiddenParameter = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: false)
                               .WithName("Param3");
            _hiddenParameter.Visible = false;

            _formulation = new Formulation
            {
                Name            = "Form",
                FormulationType = "Weibul",
                Description     = "Amazing formulation"
            };

            _formulation.Add(_parameter1);
            _formulation.Add(_parameter2);
            _formulation.Add(_hiddenParameter);

            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter1)).Returns(new Parameter().WithName(_parameter1.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter2)).Returns(new Parameter().WithName(_parameter2.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_hiddenParameter)).Returns(new Parameter().WithName(_hiddenParameter.Name));

            return(Task.FromResult(true));
        }
Esempio n. 2
0
        protected override Task Context()
        {
            _parameterMapper  = A.Fake <ParameterMapper>();
            _schemaItemMapper = A.Fake <SchemaItemMapper>();
            _schemaFactory    = A.Fake <ISchemaFactory>();

            sut = new SchemaMapper(_parameterMapper, _schemaItemMapper, _schemaFactory);

            _schemaItem = new SchemaItem().WithName("Item1");
            _schema     = new Schema
            {
                Description = "Hello",
                Name        = "Tralala"
            };
            _schema.AddSchemaItem(_schemaItem);

            _parameter = DomainHelperForSpecs.ConstantParameterWithValue(3).WithName("Param1");
            //Schema item parameters that have a value IsDefault true should still be saved to snapshot
            _parameter1 = DomainHelperForSpecs.ConstantParameterWithValue(1, isDefault: true).WithName(Constants.Parameters.START_TIME);
            _parameter2 = DomainHelperForSpecs.ConstantParameterWithValue(2, isDefault: true).WithName(CoreConstants.Parameters.NUMBER_OF_REPETITIONS);
            _parameter3 = DomainHelperForSpecs.ConstantParameterWithValue(3, isDefault: true).WithName(CoreConstants.Parameters.TIME_BETWEEN_REPETITIONS);
            _schema.Add(_parameter);
            _schema.Add(_parameter1);
            _schema.Add(_parameter2);
            _schema.Add(_parameter3);

            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter)).Returns(new Snapshots.Parameter().WithName(_parameter.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter1)).Returns(new Snapshots.Parameter().WithName(_parameter1.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter2)).Returns(new Snapshots.Parameter().WithName(_parameter2.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter3)).Returns(new Snapshots.Parameter().WithName(_parameter3.Name));

            A.CallTo(() => _schemaItemMapper.MapToSnapshot(_schemaItem)).Returns(new Snapshots.SchemaItem().WithName(_schemaItem.Name));

            return(Task.FromResult(true));
        }
Esempio n. 3
0
        protected override void Context()
        {
            _parameterMapper = A.Fake <ParameterMapper>();
            _eventFactory    = A.Fake <IEventFactory>();

            sut = new EventMapper(_parameterMapper, _eventFactory);

            _parameter1 = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: false)
                          .WithName("Param1");

            _parameter2 = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: true)
                          .WithName("Param2");

            _hiddenParameter = DomainHelperForSpecs.ConstantParameterWithValue(5, isDefault: false)
                               .WithName("Param3");
            _hiddenParameter.Visible = false;

            _event = new PKSimEvent
            {
                Name         = "Event",
                TemplateName = "TemplateEventName",
                Description  = "Amazing event"
            };

            _event.Add(_parameter1);
            _event.Add(_parameter2);
            _event.Add(_hiddenParameter);

            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter1)).Returns(new Parameter().WithName(_parameter1.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter2)).Returns(new Parameter().WithName(_parameter2.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_hiddenParameter)).Returns(new Parameter().WithName(_hiddenParameter.Name));
        }
Esempio n. 4
0
        protected override Task Context()
        {
            _parameterMapper          = A.Fake <ParameterMapper>();
            _advancedParameterFactory = A.Fake <IAdvancedParameterFactory>();
            _logger = A.Fake <ILogger>();

            _advancedParameter = new AdvancedParameter
            {
                DistributedParameter = DomainHelperForSpecs.NormalDistributedParameter(10, 5),
                ParameterPath        = "ParameterPath",
                Name = "ParameterName"
            };

            _originalSeed = _advancedParameter.Seed;
            sut           = new AdvancedParameterMapper(_parameterMapper, _advancedParameterFactory, _entityPathResolver, _logger);

            _meanSnapshot = new Parameter
            {
                Name = _advancedParameter.DistributedParameter.MeanParameter.Name,
            };

            _deviationSnapshot = new Parameter
            {
                Name = _advancedParameter.DistributedParameter.DeviationParameter.Name,
            };

            A.CallTo(() => _parameterMapper.MapToSnapshot(_advancedParameter.DistributedParameter.MeanParameter)).Returns(_meanSnapshot);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_advancedParameter.DistributedParameter.DeviationParameter)).Returns(_deviationSnapshot);
            return(Task.FromResult(true));
        }
Esempio n. 5
0
        /// <summary>
        ///     <para>Executes a stored procedure on the specified database.</para>
        /// </summary>
        /// <param name="database">
        ///     <para>The <see cref="Database"/> on which the sproc should be executed.</para>
        /// </param>
        /// <param name="procedureName">
        ///     <para>The name of the sproc to execute.</para>
        /// </param>
        /// <param name="parameterMapper">
        ///     <para>A delegate that will populate the parameters in the sproc call.
        ///     Specify <see langword="null"/> if the sproc does not require parameters.</para>
        /// </param>
        /// <param name="outputMapper">
        ///     <para>A delegate that will read the value of the parameters returned
        ///     by the sproc call.  Specify <see langword="null"/> if no output parameters
        ///     have been provided by the <paramref name="parameterMapper"/> delegate.</para>
        /// </param>
        /// <returns>
        ///     <para>The value returned by as part of the result set.</para>
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <para>The argument <paramref name="database"/> is <see langword="null"/>.</para>
        ///     <para>-or-</para>
        ///     <para>The argument <paramref name="procedureName"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="SafeProcedureException">
        ///     <para>An unexpected exception has been encountered during the sproc call.</para>
        /// </exception>
        public static object ExecuteScalar(Database database, string procedureName, ParameterMapper parameterMapper, OutputParameterMapper outputMapper)
        {
            if (database == null)
            {
                throw new ArgumentNullException("database");
            }
            if (procedureName == null)
            {
                throw new ArgumentNullException("procedureName");
            }

            object result;

            try
            {
                using (SqlConnection connection = database.GetOpenConnection())
                {
                    result = ExecuteScalar(database, connection, procedureName, parameterMapper, outputMapper);
                }
            }
            catch (SafeProcedureException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new SafeProcedureException(database, procedureName, e);
            }

            return(result);
        }
Esempio n. 6
0
        /// <summary>
        /// Executes and returns an open IRecordSet, which encapsulates an OPEN DATAREADER.  DISPOSE IN FINALLY CLAUSE.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <returns></returns>
        /// <param name="objectInstance"></param>
        public static IRecordSet Execute <T>(Database database, string procedureName,
                                             ParameterMapper <T> parameterMapper, T objectInstance)
        {
            MySqlConnection connection = database.GetConnection();
            MySqlCommand    command    = CommandFactory.CreateParameterMappedCommand <T>(
                connection, database.InstanceName, procedureName, parameterMapper, objectInstance);

            if (log.IsDebugEnabled)
            {
                log.MethodDebugFormat(LOG_PREFIX, "Database: {0}, Procedure: {1}, Parameters: {2}", database.InstanceName, procedureName, DebugUtil.GetParameterString(command));
            }

            try
            {
                command.Connection.Open();
                IRecordSet record = new DataRecord(command.ExecuteReader(CommandBehavior.CloseConnection));
                return(record);
            }
            catch (Exception exc)
            {
                command.Connection.Close();

                throw new Dongbo.Data.Exceptions.DatabaseExecutionException(database, procedureName, command, exc);
            }
        }
Esempio n. 7
0
        protected override Task Context()
        {
            _parameterMapper  = A.Fake <ParameterMapper>();
            _schemaItemMapper = A.Fake <SchemaItemMapper>();
            _schemaFactory    = A.Fake <ISchemaFactory>();

            sut = new SchemaMapper(_parameterMapper, _schemaItemMapper, _schemaFactory);

            _schemaItem = new SchemaItem().WithName("Item1");
            _schema     = new Schema
            {
                Description = "Hello",
                Name        = "Tralala"
            };
            _schema.AddSchemaItem(_schemaItem);

            _parameter = DomainHelperForSpecs.ConstantParameterWithValue(3).WithName("Param1");
            _schema.Add(_parameter);

            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter)).Returns(new Snapshots.Parameter().WithName(_parameter.Name));

            A.CallTo(() => _schemaItemMapper.MapToSnapshot(_schemaItem)).Returns(new Snapshots.SchemaItem().WithName(_schemaItem.Name));

            return(Task.FromResult(true));
        }
        protected override Task Context()
        {
            _parameterMapper       = A.Fake <ParameterMapper>();
            _outputIntervalFactory = A.Fake <IOutputIntervalFactory>();
            sut = new OutputIntervalMapper(_parameterMapper, _outputIntervalFactory);

            _outputInterval = new OutputInterval
            {
                Name = "Interval"
            };
            _endTimeParameter    = DomainHelperForSpecs.ConstantParameterWithValue(1, isDefault: true).WithName(Constants.Parameters.END_TIME);
            _resolutionParameter = DomainHelperForSpecs.ConstantParameterWithValue(1, isDefault: true).WithName(Constants.Parameters.RESOLUTION);
            _anotherParameter    = DomainHelperForSpecs.ConstantParameterWithValue(1, isDefault: false).WithName("Another");
            _outputInterval.Add(_endTimeParameter);
            _outputInterval.Add(_anotherParameter);
            _outputInterval.Add(_resolutionParameter);

            _endTimeSnapshotParameter    = new Parameter().WithName(_endTimeParameter.Name);
            _anotherSnapshotParameter    = new Parameter().WithName(_anotherParameter.Name);
            _resolutionSnapshotParameter = new Parameter().WithName(_resolutionParameter.Name);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_endTimeParameter)).Returns(_endTimeSnapshotParameter);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_anotherParameter)).Returns(_anotherSnapshotParameter);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_resolutionParameter)).Returns(_resolutionSnapshotParameter);

            return(_completed);
        }
        protected override Task Context()
        {
            _parameterMapper     = A.Fake <ParameterMapper>();
            _eventMappingFactory = A.Fake <IEventMappingFactory>();
            sut = new EventMappingMapper(_parameterMapper, _eventMappingFactory);

            _event = new PKSimEvent()
                     .WithName("E1")
                     .WithId("EventId");

            _eventMapping = new EventMapping
            {
                TemplateEventId = _event.Id,
                StartTime       = DomainHelperForSpecs.ConstantParameterWithValue(1)
            };

            _snapshotEventStartTime1 = new Parameter {
                Name = "P1"
            };

            _project = new PKSimProject();
            _project.AddBuildingBlock(_event);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_eventMapping.StartTime)).Returns(_snapshotEventStartTime1);

            return(_completed);
        }
Esempio n. 10
0
        protected override Task Context()
        {
            _parameterMapper     = A.Fake <ParameterMapper>();
            _moleculeMapper      = A.Fake <MoleculeMapper>();
            _dimensionRepository = A.Fake <IDimensionRepository>();
            _individualFactory   = A.Fake <IIndividualFactory>();
            _originDataMapper    = A.Fake <OriginDataMapper>();

            sut = new IndividualMapper(_parameterMapper, _moleculeMapper, _originDataMapper, _individualFactory);

            _individual             = DomainHelperForSpecs.CreateIndividual();
            _individual.Name        = "Ind";
            _individual.Description = "Model Description";

            _parameterLiver  = _individual.EntityAt <IParameter>(Constants.ORGANISM, CoreConstants.Organ.Liver, "PLiver");
            _parameterKidney = _individual.EntityAt <IParameter>(Constants.ORGANISM, CoreConstants.Organ.Kidney, "PKidney");

            _parameterLiver.ValueDiffersFromDefault().ShouldBeFalse();
            _parameterKidney.ValueDiffersFromDefault().ShouldBeFalse();

            _parameterKidney.Value = 40;
            _parameterKidney.ValueDiffersFromDefault().ShouldBeTrue();

            _enzyme = new IndividualEnzyme
            {
                Name = "Enz",
            };
            _individual.AddMolecule(_enzyme);

            _transporter = new IndividualTransporter
            {
                Name = "Trans",
            };

            _individual.AddMolecule(_transporter);

            _enzymeSnapshot = new Molecule {
                Type = QuantityType.Enzyme
            };
            _transporterSnapshot = new Molecule {
                Type = QuantityType.Transporter
            };

            A.CallTo(() => _moleculeMapper.MapToSnapshot(_enzyme)).Returns(_enzymeSnapshot);
            A.CallTo(() => _moleculeMapper.MapToSnapshot(_transporter)).Returns(_transporterSnapshot);

            _originDataSnapshot = new OriginData();
            A.CallTo(() => _originDataMapper.MapToSnapshot(_individual.OriginData)).Returns(_originDataSnapshot);

            _localizedParameterKidney = new LocalizedParameter {
                Path = "Organism|Kidney|PKidney"
            };
            A.CallTo(() => _parameterMapper.LocalizedParametersFrom(A <IEnumerable <IParameter> > .That.Contains(_parameterKidney))).Returns(new[] { _localizedParameterKidney });

            return(_completed);
        }
Esempio n. 11
0
        protected InputSourceStatementProcessor()
        {
            sinMapper   = new ParameterMapper <SinusoidalBehavior>();
            expMapper   = new ParameterMapper <ExponentialBehavior>();
            pulseMapper = new ParameterMapper <PulseBehavior>();
            amMapper    = new ParameterMapper <AmBehavior>();
            sffmMapper  = new ParameterMapper <SffmBehavior>();
            dcMapper    = new ParameterMapper <ConstantBehavior>();

            InitMappers();

            MinArgs = 3;
        }
Esempio n. 12
0
        public void MapsProperties()
        {
            var mapper = new ParameterMapper <DiodeParams>();

            mapper.Target = DiodeParams.Default;
            mapper.Map(p => p.SaturationCurrent, "IS");
            mapper.Map(p => p.SaturationCurrent, 0);

            mapper.Set("IS", 1);
            Assert.Equal(1, mapper.Target.SaturationCurrent);

            mapper.Set(0, 45);
            Assert.Equal(45, mapper.Target.SaturationCurrent);
        }
Esempio n. 13
0
        /// <summary>
        ///     <para>Executes a SQL stored procedure on a provided connection.</para>
        /// </summary>
        /// <param name="database">
        ///     <para>The <see cref="Database"/> to which the specified connection
        ///     object belongs.  This object is for informational purposes only,
        ///     and will not be used to create new connections.</para>
        /// </param>
        /// <param name="connection">
        ///     <para>The <see cref="SqlConnection"/> on which to execute sproc.
        ///     If this connection is not yet open, it will be opened and closed.
        ///     If this connection is already open, it will NOT be closed.  In this case,
        ///     the caller is responsible for its disposal.</para>
        /// </param>
        /// <param name="procedureName">
        ///     <para>The name of the sproc to execute.</para>
        /// </param>
        /// <param name="parameterMapper">
        ///     <para>A delegate that will populate the parameters in the sproc call.
        ///     Specify <see langword="null"/> if the sproc does not require parameters.</para>
        /// </param>
        /// <param name="outputMapper">
        ///     <para>A delegate that will read the value of the parameters returned
        ///     by the sproc call.  Specify <see langword="null"/> if no output parameters
        ///     have been provided by the <paramref name="parameterMapper"/> delegate.</para>
        /// </param>
        /// <returns>
        ///     <para>An <see cref="Int32"/> value indicating the number of rows
        ///     affected by this sproc call.</para>
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <para>The argument <paramref name="database"/> is <see langword="null"/>.</para>
        ///     <para>-or-</para>
        ///     <para>The argument <paramref name="connection"/> is <see langword="null"/>.</para>
        ///     <para>-or-</para>
        ///     <para>The argument <paramref name="procedureName"/> is <see langword="null"/>.</para>
        /// </exception>
        /// <exception cref="SafeProcedureException">
        ///     <para>An unexpected exception has been encountered during the sproc call.</para>
        /// </exception>
        public static int ExecuteNonQuery(Database database, SqlConnection connection, string procedureName,
                                          ParameterMapper parameterMapper, OutputParameterMapper outputMapper)
        {
            if (database == null)
            {
                throw new ArgumentNullException("database");
            }
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            if (procedureName == null)
            {
                throw new ArgumentNullException("procedureName");
            }

            int result = 0;

            try
            {
                SqlCommand command = CommandFactory.CreateParameterMappedCommand(connection, procedureName, parameterMapper);


                bool doClose = false;
                if (connection.State != ConnectionState.Open)
                {
                    doClose = true;
                    connection.Open();
                }
                result = command.ExecuteNonQuery();
                if (doClose)
                {
                    connection.Close();
                }

                if (outputMapper != null)
                {
                    ParameterSet outputParams = new ParameterSet(command.Parameters);
                    outputMapper(outputParams);
                }
            }
            catch (Exception e)
            {
                throw new SafeProcedureException(database, procedureName, e);
            }

            return(result);
        }
Esempio n. 14
0
        protected override Task Context()
        {
            _parameterMapper         = A.Fake <ParameterMapper>();
            _expressionProfileMapper = A.Fake <ExpressionProfileMapper>();
            _dimensionRepository     = A.Fake <IDimensionRepository>();
            _individualFactory       = A.Fake <IIndividualFactory>();
            _originDataMapper        = A.Fake <OriginDataMapper>();
            _moleculeExpressionTask  = A.Fake <IMoleculeExpressionTask <ModelIndividual> >();

            sut = new IndividualMapper(_parameterMapper, _expressionProfileMapper, _originDataMapper, _individualFactory, _moleculeExpressionTask);

            _individual             = DomainHelperForSpecs.CreateIndividual();
            _individual.Name        = "Ind";
            _individual.Description = "Model Description";
            var kidney = _individual.EntityAt <IContainer>(Constants.ORGANISM, CoreConstants.Organ.KIDNEY);

            _parameterLiver        = _individual.EntityAt <IParameter>(Constants.ORGANISM, CoreConstants.Organ.LIVER, "PLiver");
            _parameterKidney       = _individual.EntityAt <IParameter>(Constants.ORGANISM, CoreConstants.Organ.KIDNEY, "PKidney");
            _parameterKidneyRelExp = DomainHelperForSpecs.ConstantParameterWithValue().WithName(CoreConstants.Parameters.REL_EXP);
            _parameterKidneyRelExp.DefaultValue = 10;
            kidney.Add(_parameterKidneyRelExp);

            _parameterLiver.ValueDiffersFromDefault().ShouldBeFalse();
            _parameterKidney.ValueDiffersFromDefault().ShouldBeFalse();

            _parameterKidney.Value = 40;
            _parameterKidney.ValueDiffersFromDefault().ShouldBeTrue();
            _parameterKidneyRelExp.Value = 50;
            _parameterKidneyRelExp.ValueDiffersFromDefault().ShouldBeTrue();

            _expressionProfile1 = DomainHelperForSpecs.CreateExpressionProfile <IndividualEnzyme>(moleculeName: "Enz");
            _expressionProfile2 = DomainHelperForSpecs.CreateExpressionProfile <IndividualTransporter>(moleculeName: "Trans");
            _individual.AddExpressionProfile(_expressionProfile1);
            _individual.AddExpressionProfile(_expressionProfile2);


            _originDataSnapshot = new OriginData();
            A.CallTo(() => _originDataMapper.MapToSnapshot(_individual.OriginData)).Returns(_originDataSnapshot);

            _localizedParameterKidney = new LocalizedParameter {
                Path = "Organism|Kidney|PKidney"
            };
            A.CallTo(() => _parameterMapper.LocalizedParametersFrom(A <IEnumerable <IParameter> > ._))
            .Invokes(x => _mappedParameters = x.GetArgument <IEnumerable <IParameter> >(0).ToList())
            .Returns(new[] { _localizedParameterKidney });

            return(_completed);
        }
Esempio n. 15
0
        protected override Task Context()
        {
            _alternativeMapper            = A.Fake <AlternativeMapper>();
            _parameterMapper              = A.Fake <ParameterMapper>();
            _calculationMethodCacheMapper = A.Fake <CalculationMethodCacheMapper>();
            _processMapper   = A.Fake <CompoundProcessMapper>();
            _compoundFactory = A.Fake <ICompoundFactory>();
            sut = new CompoundMapper(_parameterMapper, _alternativeMapper, _calculationMethodCacheMapper, _processMapper, _compoundFactory);

            _compound = new Model.Compound
            {
                Name        = "Compound",
                Description = "Description"
            };

            addPkAParameters(_compound, 0, 8, CompoundType.Base);
            addPkAParameters(_compound, 1, 4, CompoundType.Acid);
            addPkAParameters(_compound, 2, 7, CompoundType.Neutral);

            _compound.AddParameterAlternativeGroup(createParameterAlternativeGroup(CoreConstants.Groups.COMPOUND_LIPOPHILICITY));
            _compound.AddParameterAlternativeGroup(createParameterAlternativeGroup(CoreConstants.Groups.COMPOUND_FRACTION_UNBOUND));
            _compound.AddParameterAlternativeGroup(createParameterAlternativeGroup(CoreConstants.Groups.COMPOUND_SOLUBILITY));
            _compound.AddParameterAlternativeGroup(createParameterAlternativeGroup(CoreConstants.Groups.COMPOUND_INTESTINAL_PERMEABILITY));
            _compound.AddParameterAlternativeGroup(createParameterAlternativeGroup(CoreConstants.Groups.COMPOUND_PERMEABILITY));

            _compound.Add(DomainHelperForSpecs.ConstantParameterWithValue(1).WithName(CoreConstants.Parameters.IS_SMALL_MOLECULE));
            _compound.Add(DomainHelperForSpecs.ConstantParameterWithValue((int)PlasmaProteinBindingPartner.Glycoprotein).WithName(CoreConstants.Parameters.PLASMA_PROTEIN_BINDING_PARTNER));

            _partialProcess  = new EnzymaticProcess().WithName("EnzymaticProcess");
            _systemicProcess = new SystemicProcess().WithName("SystemicProcess");
            _compound.AddProcess(_partialProcess);
            _compound.AddProcess(_systemicProcess);

            _calculationMethodCacheSnapshot = new CalculationMethodCache();
            A.CallTo(() => _calculationMethodCacheMapper.MapToSnapshot(_compound.CalculationMethodCache)).Returns(_calculationMethodCacheSnapshot);

            _snapshotProcess1 = new CompoundProcess();
            _snapshotProcess2 = new CompoundProcess();
            A.CallTo(() => _processMapper.MapToSnapshot(_partialProcess)).Returns(_snapshotProcess1);
            A.CallTo(() => _processMapper.MapToSnapshot(_systemicProcess)).Returns(_snapshotProcess2);

            return(_completed);
        }
Esempio n. 16
0
        /// <summary>
        /// Executes and returns an open IRecordSet, which encapsulates an OPEN DATAREADER.  DISPOSE IN FINALLY CLAUSE.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <returns></returns>
        public static IRecordSet Execute(Database database, string procedureName, ParameterMapper parameterMapper)
        {
            SqlConnection connection = database.GetConnection();
            SqlCommand    command    = CommandFactory.CreateParameterMappedCommand(connection, procedureName, parameterMapper);


            try
            {
                command.Connection.Open();
                IRecordSet record = new DataRecord(command.ExecuteReader(CommandBehavior.CloseConnection));
                return(record);
            }
            catch (Exception exc)
            {
                command.Connection.Close();

                throw new Core.Data.Exceptions.DatabaseExecutionException(database, procedureName, command, exc);
            }
        }
        protected override Task Context()
        {
            _parameterMapper     = A.Fake <ParameterMapper>();
            _schemaMapper        = A.Fake <SchemaMapper>();
            _protocolFactory     = A.Fake <IProtocolFactory>();
            _dimensionRepository = A.Fake <IDimensionRepository>();

            sut = new ProtocolMapper(_parameterMapper, _protocolFactory, _schemaMapper, _dimensionRepository);

            _simpleProtocol = new SimpleProtocol
            {
                ApplicationType = ApplicationTypes.Intravenous,
                DosingInterval  = DosingIntervals.DI_6_6_12,
                Name            = "Simple Protocol",
                Description     = "Simple Protocol description",
            };
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(3).WithName(Constants.Parameters.START_TIME));
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(4).WithName(CoreConstants.Parameters.INPUT_DOSE));
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(5).WithName(Constants.Parameters.END_TIME));

            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.StartTime)).Returns(new Parameter().WithName(_simpleProtocol.StartTime.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.Dose)).Returns(new Parameter().WithName(_simpleProtocol.Dose.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.EndTimeParameter)).Returns(new Parameter().WithName(_simpleProtocol.EndTimeParameter.Name));

            _advancedProtocol = new AdvancedProtocol
            {
                Name        = "Advanced Protocol",
                Description = "Advanced Protocol description",
                TimeUnit    = DomainHelperForSpecs.TimeDimensionForSpecs().DefaultUnit,
            };
            _schema = new Schema().WithName("Schema1");
            _advancedProtocol.AddSchema(_schema);
            _advancedProtocolParameter = DomainHelperForSpecs.ConstantParameterWithValue(3).WithName("AdvancedProtocolParameter");
            _advancedProtocol.Add(_advancedProtocolParameter);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_advancedProtocolParameter)).Returns(new Parameter().WithName(_advancedProtocolParameter.Name));

            _snapshotSchema = new Snapshots.Schema().WithName(_schema.Name);
            A.CallTo(() => _schemaMapper.MapToSnapshot(_schema)).Returns(_snapshotSchema);

            A.CallTo(() => _dimensionRepository.Time).Returns(DomainHelperForSpecs.TimeDimensionForSpecs());

            return(Task.FromResult(true));
        }
Esempio n. 18
0
        protected override Task Context()
        {
            _parameterMapper = A.Fake <ParameterMapper>();
            _identificationParameterFactory = A.Fake <IIdentificationParameterFactory>();
            _logger = A.Fake <IOSPSuiteLogger>();
            _identificationParameterTask = A.Fake <IIdentificationParameterTask>();
            sut = new IdentificationParameterMapper(_parameterMapper, _identificationParameterFactory, _identificationParameterTask, _logger);

            _identificationParameter = new IdentificationParameter
            {
                IsFixed     = true,
                UseAsFactor = true,
                Scaling     = Scalings.Linear
            };


            _startValueParameter = DomainHelperForSpecs.ConstantParameterWithValue().WithName(Constants.Parameters.START_VALUE);

            _identificationParameter.Add(_startValueParameter);
            _identificationParameter.Name = "PARAM";
            _parameter1            = DomainHelperForSpecs.ConstantParameterWithValue().WithName("P1");
            _parameter2            = DomainHelperForSpecs.ConstantParameterWithValue().WithName("P2");
            _simulation            = A.Fake <Simulation>().WithName("S");
            _simulation.Model.Root = new Container {
                _parameter1, _parameter2
            };

            _identificationParameter.Scaling = Scalings.Linear;
            _parameterSelection1             = new ParameterSelection(_simulation, _parameter1.Name);
            _parameterSelection2             = new ParameterSelection(_simulation, _parameter2.Name);
            _identificationParameter.AddLinkedParameter(_parameterSelection1);
            _identificationParameter.AddLinkedParameter(_parameterSelection2);

            _snapshotStartValueParameter = new Parameter();
            A.CallTo(() => _parameterMapper.MapToSnapshot(_startValueParameter)).Returns(_snapshotStartValueParameter);

            _project = new PKSimProject();
            _project.AddBuildingBlock(_simulation);
            _snapshotContext                = new SnapshotContext(_project, ProjectVersions.Current);
            _parameterIdentification        = new ParameterIdentification();
            _parameterIdentificationContext = new ParameterIdentificationContext(_parameterIdentification, _snapshotContext);
            return(_completed);
        }
Esempio n. 19
0
        /// <summary>
        /// Call pseudo async NonQuery execution
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <param name="resultMapper"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(Database database, string procedureName, ParameterMapper parameterMapper)
        {
            SqlConnection connection  = database.GetAsyncConnection();
            SqlCommand    command     = CommandFactory.CreateParameterMappedCommand(connection, procedureName, parameterMapper);
            bool          isCompleted = false;
            int           result      = 0;

            try
            {
                connection.Open();

                command.BeginExecuteNonQuery(
                    //Begin delegate
                    delegate(IAsyncResult ar)
                {
                    SqlCommand locCommand = ar.AsyncState as SqlCommand;

                    try
                    {
                        result = locCommand.EndExecuteNonQuery(ar);
                    }
                    finally
                    {
                        CloseAsyncConnection(locCommand);
                        isCompleted = true;
                    }
                }
                    //End delegate
                    , command);
            }
            catch //If an exception is thrown during the connection
            {
                CloseAsyncConnection(command);
                throw;
            }
            while (!isCompleted)
            {
                Thread.Sleep(200);
            }

            return(result);
        }
Esempio n. 20
0
        /// <summary>Generic function for parsing simple transient function parameters.</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mapper"></param>
        /// <param name="paramTokens"></param>
        /// <param name="minArgc"></param>
        /// <returns></returns>
        private T GetParameterTokens <T>(ParameterMapper <T> mapper, List <Token> paramTokens, int minArgc) where T : new()
        {
            mapper.Target = new T();
            for (var i = 1;
                 i <= Math.Min(mapper.ByIndexCount, paramTokens.Count - 1);
                 i++)                // start from 1 bc. first is method identifier
            {
                mapper.Set(i - 1, GetValue(paramTokens[i]));
            }

            if (paramTokens.Count < minArgc || paramTokens.Count > mapper.ByIndexCount + 1)
            {
                Context.Errors.Add(paramTokens[0].ToError(SpiceParserErrorCode.InvalidNumberOfArguments));
            }

            var t = mapper.Target;

            mapper.Target = default(T);             // free memory
            return(t);
        }
Esempio n. 21
0
        /// <summary>
        /// Executes and returns an open IRecordSet, which encapsulates an OPEN DATAREADER.  DISPOSE IN FINALLY CLAUSE.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <returns></returns>
        public static IRecordSet Execute(Database database, string procedureName, ParameterMapper parameterMapper)
        {
            SqlConnection connection = database.GetConnection();
            SqlCommand command = CommandFactory.CreateParameterMappedCommand(connection, procedureName, parameterMapper);

            try
            {

                command.Connection.Open();
                IRecordSet record = new DataRecord(command.ExecuteReader(CommandBehavior.CloseConnection));
                return record;
            }
            catch(Exception exc)
            {
                command.Connection.Close();

                throw new Core.Data.Exceptions.DatabaseExecutionException(database, procedureName, command, exc);

            }
        }
Esempio n. 22
0
        public static IRecordSet Execute(Database database, string procedureName, ParameterMapper parameterMapper)
        {
            SqlConnection connection = database.GetConnection();
            SqlCommand    command    = CommandFactory.CreateParameterMappedCommand(connection, database.InstanceName, procedureName, parameterMapper);

            //if (log.IsDebugEnabled)
            //    log.MethodDebugFormat(LOG_PREFIX, "Database: {0}, Procedure: {1}, Parameters: {2}", database.InstanceName, procedureName, DebugUtil.GetParameterString(command));

            try
            {
                command.Connection.Open();
                IRecordSet record = new DataRecord(command.ExecuteReader(CommandBehavior.CloseConnection));
                return(record);
            }
            catch (Exception ex)
            {
                command.Connection.Close();

                throw new Exception();
            }
        }
Esempio n. 23
0
        protected override Task Context()
        {
            _parameterMapper = A.Fake <ParameterMapper>();
            _logger          = A.Fake <IOSPSuiteLogger>();

            sut = new ExpressionContainerMapper(_parameterMapper, _logger);

            _relativeExpressionParameter =
                DomainHelperForSpecs.ConstantParameterWithValue(0, isDefault: true).WithName(CoreConstants.Parameters.REL_EXP);
            _moleculeExpressionContainer = new MoleculeExpressionContainer().WithName("EXP");
            _moleculeExpressionContainer.Add(_relativeExpressionParameter);

            _transporterRelativeExpressionParameter =
                DomainHelperForSpecs.ConstantParameterWithValue(0, isDefault: true).WithName(CoreConstants.Parameters.REL_EXP);
            _transporterExpressionContainer = new TransporterExpressionContainer().WithName("TRANS");
            _transporterExpressionContainer.TransportDirection = TransportDirectionId.InfluxInterstitialToIntracellular;

            _bloodCellsExpressionContainer = new TransporterExpressionContainer().WithName(CoreConstants.Compartment.BLOOD_CELLS);
            _bloodCellsExpressionContainer.TransportDirection = TransportDirectionId.BiDirectionalBloodCellsPlasma;

            _transporterExpressionContainer.Add(_transporterRelativeExpressionParameter);

            _individual = new Individual {
                OriginData = new OriginData {
                    Species = new Species().WithName("Human")
                }
            };
            _expressionContainerMapperContext = new ExpressionContainerMapperContext(new SnapshotContext())
            {
            };

            _enzyme = new IndividualEnzyme {
                _moleculeExpressionContainer
            };
            _transporter = new IndividualTransporter {
                _transporterExpressionContainer, _bloodCellsExpressionContainer
            };
            return(_completed);
        }
Esempio n. 24
0
        //public static bool ExecuteAndHydrateInstance<T>(T objectInstance,Database database, string procedureName, ParameterMapper parameterMapper, RecordMapper<T> recordMapper)
        //{
        //    bool result = false;
        //    return result;
        //}
        public static bool ExecuteAndHydrateInstance <T>(T objectInstance, Database database,
                                                         string procedureName, ParameterMapper parameterMapper, RecordMapper <T> recordMapper)
        {
            bool result = false;

            try
            {
                using (IRecordSet reader = Procdure.Execute(database, procedureName, parameterMapper))
                {
                    if (reader.Read())
                    {
                        recordMapper(reader, objectInstance);
                        result = true;
                    }
                }
            }
            catch (Exception ex) // Procedure class already wrapped all necessary data
            {
                throw ex;
            }
            return(result);
        }
        protected override Task Context()
        {
            _parameterMapper = A.Fake <ParameterMapper>();
            _representationInfoRepository = A.Fake <IRepresentationInfoRepository>();
            _compoundProcessRepository    = A.Fake <ICompoundProcessRepository>();
            _cloner              = A.Fake <ICloner>();
            _speciesRepository   = A.Fake <ISpeciesRepository>();
            _compoundProcessTask = A.Fake <ICompoundProcessTask>();
            _logger              = A.Fake <IOSPSuiteLogger>();


            sut = new CompoundProcessMapper(_parameterMapper, _representationInfoRepository, _compoundProcessRepository, _cloner, _speciesRepository, _compoundProcessTask, _logger);

            _enzymaticProcess = new EnzymaticProcess
            {
                Name           = "Enzymatic Process",
                Description    = "Process description",
                InternalName   = "A",
                DataSource     = "B",
                MetaboliteName = "Meta"
            };

            //Same description as DB
            A.CallTo(() => _representationInfoRepository.DescriptionFor(RepresentationObjectType.PROCESS, _enzymaticProcess.InternalName)).Returns(_enzymaticProcess.Description);

            _enzymaticProcessWithSpecies = new EnzymaticProcessWithSpecies
            {
                Name         = "Enzymatic process with species",
                Description  = "toto",
                Species      = new Species().WithName("Human"),
                InternalName = "C",
                DataSource   = "D",
            };

            A.CallTo(() => _representationInfoRepository.DescriptionFor(RepresentationObjectType.PROCESS, _enzymaticProcessWithSpecies.InternalName)).Returns("Process description");

            return(Task.FromResult(true));
        }
        protected override Task Context()
        {
            _parameterMapper           = A.Fake <ParameterMapper>();
            _transportContainerUpdater = A.Fake <ITransportContainerUpdater>();
            _logger = A.Fake <ILogger>();

            sut = new ExpressionContainerMapper(_parameterMapper, _transportContainerUpdater, _logger);

            _relativeExpressionParameter = DomainHelperForSpecs.ConstantParameterWithValue(0, isDefault: true).WithName(CoreConstants.Parameters.REL_EXP);
            _moleculeExpressionContainer = new MoleculeExpressionContainer().WithName("EXP");
            _moleculeExpressionContainer.Add(_relativeExpressionParameter);

            _transporterRelativeExpressionParameter          = DomainHelperForSpecs.ConstantParameterWithValue(0, isDefault: true).WithName(CoreConstants.Parameters.REL_EXP);
            _transporterExpressionContainer                  = new TransporterExpressionContainer().WithName("TRANS");
            _transporterExpressionContainer.MembraneLocation = MembraneLocation.Apical;

            _transporterExpressionContainer.Add(_transporterRelativeExpressionParameter);

            _individual = new Individual {
                OriginData = new  Model.OriginData {
                    Species = new Species().WithName("Human")
                }
            };

            _expressionContainerMapperContext = new ExpressionContainerMapperContext
            {
                SimulationSubject = _individual
            };

            _enzyme = new IndividualEnzyme {
                _moleculeExpressionContainer
            };
            _transporter = new IndividualTransporter {
                _transporterExpressionContainer
            };
            return(_completed);
        }
Esempio n. 27
0
        protected override Task Context()
        {
            _parameterMapper   = A.Fake <ParameterMapper>();
            _schemaItemFactory = A.Fake <ISchemaItemFactory>();

            sut = new SchemaItemMapper(_parameterMapper, _schemaItemFactory);

            _schemaItem = new SchemaItem
            {
                Name              = "SchemaItem",
                Description       = "The schema item",
                ApplicationType   = ApplicationTypes.Intravenous,
                FormulationKey    = "F1",
                TargetCompartment = "Cells",
                TargetOrgan       = "Liver"
            };

            _parameter = DomainHelperForSpecs.ConstantParameterWithValue(1).WithName("Param1");
            _schemaItem.Add(_parameter);

            A.CallTo(() => _parameterMapper.MapToSnapshot(_parameter)).Returns(new Snapshots.Parameter().WithName(_parameter.Name));

            return(Task.FromResult(true));
        }
Esempio n. 28
0
        /// <summary>
        /// Executes a single-result procedure and loads the results into a DataTable named after the procedure.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <returns>A fully populated datatable</returns>
        /// <remarks>Will throw an exception if one occurs, but will close database connection.</remarks>
        public static DataTable Execute(Database database, string procedureName, ParameterMapper parameterMapper)
        {
            DataTable dt;

            try
            {
                dt = new DataTable(procedureName);

                using (IDataReader reader = Procedure.ExecuteReader(database, procedureName, parameterMapper))
                {
                    dt.Load(reader, LoadOption.OverwriteChanges);
                }
            }
            catch (Core.Data.Exceptions.DataException) // Procedure class already wrapped all necessary data
            {
                throw;
            }
            catch (Exception e)
            {
                throw new SafeProcedureException(database, procedureName, e);
            }

            return(dt);
        }
Esempio n. 29
0
        protected override Task Context()
        {
            _parameterMapper             = A.Fake <ParameterMapper>();
            _parameterAlternativeFactory = A.Fake <IParameterAlternativeFactory>();
            _speciesRepository           = A.Fake <ISpeciesRepository>();
            _compoundAlternativeTask     = A.Fake <ICompoundAlternativeTask>();

            sut = new AlternativeMapper(_parameterMapper, _parameterAlternativeFactory, _compoundAlternativeTask, _speciesRepository);

            _parameterGroup = new ParameterAlternativeGroup {
                Name = "ParameterGroup"
            };
            _alternative = new ParameterAlternative
            {
                Name        = "Alternative1",
                IsDefault   = true,
                Description = "Hello"
            };

            _species = new Species {
                Name = "Hello"
            };
            _alternativeWithSpecies = new ParameterAlternativeWithSpecies
            {
                Name        = "Alternative2",
                IsDefault   = false,
                Description = "Hello",
                Species     = _species
            };

            _parameterGroup.AddAlternative(_alternativeWithSpecies);
            A.CallTo(() => _speciesRepository.All()).Returns(new[] { _species });


            return(_completed);
        }
Esempio n. 30
0
        /// <summary>
        /// Executes a single-result procedure and fires a mapping delegate for each row that is returned and then fires a parameter mapping delegate for output params.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="procedureName"></param>
        /// <param name="parameterMapper"></param>
        /// <param name="recordMapper"></param>
        /// <param name="outputMapper"></param>
        public static void ExecuteAndMapRecords(Database database, string procedureName, ParameterMapper parameterMapper, RecordMapper recordMapper, OutputParameterMapper outputMapper)
        {
            try
            {
                using (SqlConnection connection = database.GetConnection())
                {
                    SqlCommand command = CommandFactory.CreateParameterMappedCommand(connection, procedureName, parameterMapper);


                    connection.Open();
                    IRecordSet reader = new DataRecord(command.ExecuteReader(CommandBehavior.CloseConnection));
                    while (reader.Read())
                    {
                        recordMapper(reader);
                    }
                    connection.Close();

                    if (outputMapper != null)
                    {
                        outputMapper(new ParameterSet(command.Parameters));
                    }
                }
            }
            catch (Exception e)
            {
                throw new SafeProcedureException(database, procedureName, e);
            }
        }
Esempio n. 31
0
 /// <summary>
 /// Executes a single-result procedure and fires a mapping delegate for each row that is returned.
 /// </summary>
 /// <param name="database"></param>
 /// <param name="procedureName"></param>
 /// <param name="parameterMapper"></param>
 /// <param name="recordMapper"></param>
 public static void ExecuteAndMapRecords(Database database, string procedureName, ParameterMapper parameterMapper, RecordMapper recordMapper)
 {
     try
     {
         using (IRecordSet reader = Procedure.Execute(database, procedureName, parameterMapper))
         {
             while (reader.Read())
             {
                 recordMapper(reader);
             }
         }
     }
     catch (Exception e)
     {
         throw new SafeProcedureException(database, procedureName, e);
     }
 }