Esempio n. 1
0
    public Node(string nodeText)
    {
        this.tag      = nodeText.Between("[<tag>]", "[/<tag>]").Trim();
        this.title    = nodeText.Between("[<title>]", "[/<title>]").Trim();
        this.iconName = nodeText.Between("[<icon>]", "[/<icon>]").Trim();
        this.color    = nodeText.Between("[<color>]", "[/<color>]").Trim();
        this.text     = nodeText.Between("[<text>]", "[/<text>]").Trim('\n');
        this.optional = nodeText.Contains("[<optional>]");

        string dataFileName = nodeText.Between("[<fdata>]", "[/<fdata>]").Trim();

        if (dataFileName != "")
        {
            this.data = Import.ReadFile(dataFileName);
        }
        else
        {
            this.data = nodeText.Between("[<data>]", "[/<data>]").Trim('\n');
        }
        string pramText = nodeText.Between("[<pram>]", "[/<pram>]").Trim('\n');

        this.parameters = ParameterCreator.GetParameters(pramText);

        this.nodeText = nodeText;
    }
Esempio n. 2
0
        public void SingleParameterTest_ParameterAlreadyExists_CreateNotCalled()
        {
            var p = new Mock <ISqlParameter>();//save should be called because there is no VAlue on the parameter

            p.Setup(m => m.SaveToDatabase());

            var existingParameter = Mock.Of <ISqlParameter>(x =>
                                                            x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper() &&
                                                            x.ParameterName == "@bob"
                                                            );

            var f = Mock.Of <IFilter>(x =>
                                      x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper() &&
                                      x.WhereSQL == "@bob = 'bob'" &&
                                      x.GetAllParameters() == new[] { existingParameter });

            var factory = new Mock <IFilterFactory>();

            var creator = new ParameterCreator(factory.Object, null, null);

            creator.CreateAll(f, null);
            creator.CreateAll(f, null);
            creator.CreateAll(f, null);//no matter how many times we call create it shouldn't make more because there is already one

            p.Verify(m => m.SaveToDatabase(), Times.Never);
            factory.Verify(m => m.CreateNewParameter(f, It.IsAny <string>()), Times.Never); //should never be called because the filter already has
        }
Esempio n. 3
0
        public void SequentialReplacementSQL()
        {
            var haystack =
                @"/*Paracetamol*/
[test]..[prescribing].[approved_name] LIKE @drugName
OR
/*Ketamine*/
[test]..[prescribing].[approved_name] LIKE @drugName2
OR
/*Approved Name Like*/
[test]..[prescribing].[approved_name] LIKE @drugName3";


            var newString = ParameterCreator.RenameParameterInSQL(haystack, "@drugName", "@drugName_2");

            newString = ParameterCreator.RenameParameterInSQL(newString, "@drugName2", "@drugName2_2");
            newString = ParameterCreator.RenameParameterInSQL(newString, "@drugName3", "@drugName3_2");


            var expectedoutput =
                @"/*Paracetamol*/
[test]..[prescribing].[approved_name] LIKE @drugName_2
OR
/*Ketamine*/
[test]..[prescribing].[approved_name] LIKE @drugName2_2
OR
/*Approved Name Like*/
[test]..[prescribing].[approved_name] LIKE @drugName3_2";


            Assert.AreEqual(expectedoutput, newString);
        }
Esempio n. 4
0
        public void SingleParameterTest_Template_TemplateValuesUsed()
        {
            //The constructor returns
            var pstub = Mock.Of <ISqlParameter>();

            //The filter that requires that the parameters be created
            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            f.WhereSQL = "@bob = 'bob'";

            //The template which is an existing known about parameter from the master filter that is being duplicated.  This template will be spotted and used to make the new parameter match the cloned filter's one
            var template = Mock.Of <ISqlParameter>(x => x.ParameterName == "@bob");

            template.ParameterSQL = "DECLARE @bob AS int";
            template.Value        = "5";
            template.Comment      = "fish";

            var factory = new Mock <IFilterFactory>();

            factory.Setup(m => m.CreateNewParameter(f, "DECLARE @bob AS int")).Returns(pstub);

            var creator = new ParameterCreator(factory.Object, null, new [] { template });

            creator.CreateAll(f, null);

            Assert.AreEqual("5", pstub.Value);
            Assert.AreEqual("fish", pstub.Comment);

            factory.Verify(m => m.CreateNewParameter(f, "DECLARE @bob AS int"), Times.Once);
        }
Esempio n. 5
0
        private void CreateParameters(string param1Value, string param2Value)
        {
            container1 = new AggregateFilterContainer(CatalogueRepository, FilterContainerOperation.AND);
            acDataset.RootFilterContainer_ID = container1.ID;
            acDataset.SaveToDatabase();

            AggregateFilter filter1 = new AggregateFilter(CatalogueRepository, "Filter1", container1);

            filter1.WhereSQL = "@bob = 'bob'";
            filter1.SaveToDatabase();

            var paramCreator = new ParameterCreator(filter1.GetFilterFactory(), null, null);

            paramCreator.CreateAll(filter1, null);

            container2 = new AggregateFilterContainer(CatalogueRepository, FilterContainerOperation.AND);
            acCohort.RootFilterContainer_ID = container2.ID;
            acCohort.SaveToDatabase();

            AggregateFilter filter2 = new AggregateFilter(CatalogueRepository, "Filter2", container2);

            filter2.WhereSQL = "@bob = 'fish'";
            filter2.SaveToDatabase();

            paramCreator.CreateAll(filter2, null);

            parama1       = filter1.GetAllParameters()[0];
            parama1.Value = param1Value;
            parama1.SaveToDatabase();

            parama2       = filter2.GetAllParameters()[0];
            parama2.Value = param2Value;
            parama2.SaveToDatabase();
        }
Esempio n. 6
0
        public void AddParameters()
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("---------\nCreating Parameters:");
            IFix parameterCreator = new ParameterCreator(ConnectionString);

            parameterCreator.SaveToDatabaseSequentially();
            Console.ResetColor();
        }
Esempio n. 7
0
        public void Create_ReferenceType_ReturnNull()
        {
            var creator = new ParameterCreator();

            var parameter = typeof(ObjectA).GetMethod("MethodObject").GetParameters().First();

            //act
            var result = creator.Create(parameter);

            //assert
            Assert.Null(result);
        }
Esempio n. 8
0
        /// <summary>
        /// 只能加一次
        /// </summary>
        /// <param name="doc"></param>
        public void AddElement(Document doc)
        {
            var element = new UserElement();

            element.SetName(Text);
            element.SetSchemaName("TextSceneNode");
            Id = doc.AddElement(element);

            element.AddParameter("PositionX", ParameterCreator.Create(Position.x));
            element.AddParameter("PositionY", ParameterCreator.Create(Position.y));
            element.AddParameter("PositionZ", ParameterCreator.Create(Position.z));
        }
Esempio n. 9
0
        public void Create_StringType_ReturnNotNull()
        {
            var creator = new ParameterCreator();

            var parameter = typeof(ObjectA).GetMethod("MethodString").GetParameters().First();

            //act
            var result = creator.Create(parameter);

            //assert
            Assert.NotNull(result);
            Assert.Equal("value - Test", result);
        }
Esempio n. 10
0
        private bool BeforeSave(DatabaseEntity databaseEntity)
        {
            SubstituteQueryEditorTextIfContainsLineComments();
            OfferWrappingIfUserIncludesANDOrOR();

            //update SQL
            _extractionFilter.WhereSQL = QueryEditor.Text.TrimEnd();

            var creator = new ParameterCreator(_extractionFilter.GetFilterFactory(), GlobalFilterParameters, null);

            creator.CreateAll(_extractionFilter, null);

            return(true);
        }
Esempio n. 11
0
        public void SingleParameterTest_NullReturnFromConstruct_Throws()
        {
            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            f.WhereSQL = "@bob = 'bob'";

            var factory = Mock.Of <IFilterFactory>(m => m.CreateNewParameter(f, "DECLARE @bob AS varchar(50);") == null);

            var creator = new ParameterCreator(factory, null, null);

            var ex = Assert.Throws <NullReferenceException>(() => creator.CreateAll(f, null));

            Assert.IsTrue(ex.Message.StartsWith("Parameter construction method returned null"));
        }
Esempio n. 12
0
        public void NoParametersTest_CreateNotCalled()
        {
            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            var factory = new Mock <IFilterFactory>();

            factory.Verify(m => m.CreateNewParameter(It.IsAny <IFilter>(), It.IsAny <string>()), Times.Never);

            var creator = new ParameterCreator(factory.Object, new ISqlParameter[0], null);

            creator.CreateAll(f, null);

            factory.Verify();
        }
Esempio n. 13
0
        private IFilter CreateFilter(Catalogue cata, string name, string parentExtractionInformation, string whereSql, string desc)
        {
            var filter = new ExtractionFilter(_repos.CatalogueRepository, name, GetExtractionInformation(cata, parentExtractionInformation));

            filter.WhereSQL    = whereSql;
            filter.Description = desc;
            filter.SaveToDatabase();

            var parameterCreator = new ParameterCreator(filter.GetFilterFactory(), null, null);

            parameterCreator.CreateAll(filter, null);

            return(filter);
        }
Esempio n. 14
0
        public void SingleParameterTest_GlobalButNotSameName_CreateCalled()
        {
            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            f.WhereSQL = "@bob = 'bob'";

            var global = Mock.Of <ISqlParameter>(x => x.ParameterName == "@bob");

            var factory = new Mock <IFilterFactory>();

            factory.Setup <ISqlParameter>(m => m.CreateNewParameter(f, "DECLARE @bob AS varchar(50);")).Returns(Mock.Of <ISqlParameter>);

            var creator = new ParameterCreator(factory.Object, null, null);

            creator.CreateAll(f, null);

            factory.Verify <ISqlParameter>(m => m.CreateNewParameter(f, "DECLARE @bob AS varchar(50);"), Times.Once);
        }
Esempio n. 15
0
        public void SingleParameterTest_GlobalOverrides_CreateNotCalled()
        {
            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            f.WhereSQL = "@bob = 'bob'";

            var global = Mock.Of <ISqlParameter>(x => x.ParameterName == "@bob");

            var factory = new Mock <IFilterFactory>();

            factory
            .Setup(m => m.CreateNewParameter(It.IsAny <IFilter>(), It.IsAny <string>()))
            .Throws <InvalidOperationException>();

            var creator = new ParameterCreator(factory.Object, new[] { global }, null);

            creator.CreateAll(f, null);

            factory.Verify();
        }
Esempio n. 16
0
        public void SingleParameterTest_OneParameter_CreateCalled()
        {
            var p = new Mock <ISqlParameter>();//save should be called because there is no VAlue on the parameter

            p.Setup(m => m.SaveToDatabase());

            var f = Mock.Of <IFilter>(x => x.GetQuerySyntaxHelper() == new MicrosoftQuerySyntaxHelper());

            f.WhereSQL = "@bob = 'bob'";

            var factory = new Mock <IFilterFactory>();

            factory.Setup(m => m.CreateNewParameter(f, "DECLARE @bob AS varchar(50);")).Returns(p.Object);

            var creator = new ParameterCreator(factory.Object, null, null);

            creator.CreateAll(f, null);

            p.Verify(m => m.SaveToDatabase(), Times.Once);
            p.Verify();
            factory.Verify(m => m.CreateNewParameter(f, "DECLARE @bob AS varchar(50);"), Times.Once);
        }
        /// <summary>
        /// Can only be called once, updates the <see cref="Sql"/> to resolve parameter naming collisions with the larger query
        /// (see <paramref name="compositeLevelParameterManager"/>.  Returns the updated <see cref="Sql"/> (for convenience)
        /// </summary>
        /// <param name="compositeLevelParameterManager">
        /// <see cref="ParameterManager"/> that reflects this aggregates location within a larger composite query (e.g. with UNION / INTERSECT / EXCEPT)
        /// containers.  This manager may include non global parameters that have been used to satisfy previously written SQL and new parameters
        /// discovered may be subject to rename operations (which can break caching).</param>
        /// <returns></returns>
        public string Use(ParameterManager compositeLevelParameterManager)
        {
            if (_hasBeenUsed)
            {
                throw new InvalidOperationException("Block can only be used once");
            }

            //import parameters unless caching was used
            Dictionary <string, string> renameOperations;

            compositeLevelParameterManager.ImportAndElevateResolvedParametersFromSubquery(ParametersUsed, out renameOperations);

            //rename in the SQL too!
            foreach (KeyValuePair <string, string> kvp in renameOperations)
            {
                Sql = ParameterCreator.RenameParameterInSQL(Sql, kvp.Key, kvp.Value);
            }

            _hasBeenUsed = true;

            return(Sql);
        }
Esempio n. 18
0
    private List <AnimatorControllerParameter> GetAnimatorControllerParameter()
    {
        if (_combo == null)
        {
            Debug.LogError("Combo is null.");
            return(null);
        }
        if (_CharacterAnimatorNamingList == null)
        {
            Debug.LogError("CharacterAnimatorNamingList is null.");
            return(null);
        }
        List <AnimatorControllerParameter> AnimatorControllerParameters = new List <AnimatorControllerParameter>();

        AnimatorControllerParameter _normalizedParam = ParameterCreator.CreateParameter(_CharacterAnimatorNamingList.NormalizedTimeParameterName, AnimatorControllerParameterType.Float);
        AnimatorControllerParameter _speedParam      = ParameterCreator.CreateParameter(_CharacterAnimatorNamingList.SpeedParameterName, AnimatorControllerParameterType.Float);


        AnimatorControllerParameters.Add(_combo.AnimatorControllerParameter);
        AnimatorControllerParameters.Add(_normalizedParam);
        AnimatorControllerParameters.Add(_speedParam);
        return(AnimatorControllerParameters);
    }
Esempio n. 19
0
        public void ReplaceParametersSQL(string haystack, string needle, string replacement, string expectedOutput)
        {
            var output = ParameterCreator.RenameParameterInSQL(haystack, needle, replacement);

            Assert.AreEqual(expectedOutput, output);
        }
Esempio n. 20
0
        public string GetSQLForAggregate(AggregateConfiguration aggregate, int tabDepth, bool isJoinAggregate = false, string overrideSelectList = null, string overrideLimitationSQL = null, int topX = -1)
        {
            string toReturn = "";

            CountOfSubQueries++;

            string tabs       = "";
            string tabplusOne = "";

            if (tabDepth != -1)
            {
                GetTabs(tabDepth, out tabs, out tabplusOne);
            }

            //make sure it is a valid configuration
            string reason;

            if (!aggregate.IsAcceptableAsCohortGenerationSource(out reason))
            {
                throw new QueryBuildingException("Cannot generate a cohort using AggregateConfiguration " + aggregate + " because:" + reason);
            }

            //get the extraction identifier (method IsAcceptableAsCohortGenerationSource will ensure this linq returns 1 so no need to check again)
            AggregateDimension extractionIdentifier = aggregate.AggregateDimensions.Single(d => d.IsExtractionIdentifier);

            //create a builder but do it manually, we care about group bys etc or count(*) even
            AggregateBuilder builder;

            //we are getting SQL for a cohort identification aggregate without a HAVING/count statement so it is actually just 'select patientIdentifier from tableX'
            if (string.IsNullOrWhiteSpace(aggregate.HavingSQL) && string.IsNullOrWhiteSpace(aggregate.CountSQL))
            {
                //select list is the extraction identifier
                string selectList;

                if (!isJoinAggregate)
                {
                    selectList = extractionIdentifier.SelectSQL + (extractionIdentifier.Alias != null ? " " + extractionIdentifier.Alias: "");
                }
                else
                {
                    //unless we are also including other columns because this is a patient index joinable inception query
                    selectList = string.Join("," + Environment.NewLine + tabs,
                                             aggregate.AggregateDimensions.Select(e => e.SelectSQL + (e.Alias != null ? " " + e.Alias : ""))); //joinable patient index tables have patientIdentifier + 1 or more other columns
                }
                if (overrideSelectList != null)
                {
                    selectList = overrideSelectList;
                }

                string limitationSQL = overrideLimitationSQL ?? "distinct";

                //select list is either [chi] or [chi],[mycolumn],[myexcitingcol] (in the case of a patient index table)
                builder = new AggregateBuilder(limitationSQL, selectList, aggregate, aggregate.ForcedJoins);

                //false makes it skip them in the SQL it generates (it uses them only in determining JOIN requirements etc but since we passed in the select SQL explicitly it should be the equivellent of telling the query builder to generate a regular select
                if (!isJoinAggregate)
                {
                    builder.AddColumn(extractionIdentifier, false);
                }
                else
                {
                    builder.AddColumnRange(aggregate.AggregateDimensions.ToArray(), false);
                }
            }
            else
            {
                if (overrideSelectList != null)
                {
                    throw new NotSupportedException("Cannot override Select list on aggregates that have HAVING / Count SQL configured in them");
                }

                builder = new AggregateBuilder("distinct", aggregate.CountSQL, aggregate, aggregate.ForcedJoins);

                //add the extraction information and do group by it
                if (!isJoinAggregate)
                {
                    builder.AddColumn(extractionIdentifier, true);
                }
                else
                {
                    builder.AddColumnRange(aggregate.AggregateDimensions.ToArray(), true);//it's a joinable inception query (See JoinableCohortAggregateConfiguration) - these are allowed additional columns
                }
                builder.DoNotWriteOutOrderBy = true;
            }

            if (topX != -1)
            {
                builder.AggregateTopX = new SpontaneouslyInventedAggregateTopX(new MemoryRepository(), topX, AggregateTopXOrderByDirection.Descending, null);
            }

            AddJoinablesToBuilder(builder, aggregate, tabDepth);

            //set the where container
            builder.RootFilterContainer = aggregate.RootFilterContainer;

            string builderSqlVerbatimForCheckingAgainstCache = null;

            if (CacheServer != null)
            {
                builderSqlVerbatimForCheckingAgainstCache = GetSqlForBuilderForCheckingAgainstCache(builder);
            }

            //we will be harnessing the parameters via ImportAndElevate so do not add them to the SQL directly
            builder.DoNotWriteOutParameters = true;
            var builderSqlWithoutParameters = builder.SQL;

            //if we have caching
            if (CacheServer != null)
            {
                CachedAggregateConfigurationResultsManager manager = new CachedAggregateConfigurationResultsManager(CacheServer);
                var existingTable = manager.GetLatestResultsTable(aggregate, isJoinAggregate? AggregateOperation.JoinableInceptionQuery: AggregateOperation.IndexedExtractionIdentifierList, builderSqlVerbatimForCheckingAgainstCache);

                //if we have the answer already
                if (existingTable != null)
                {
                    //reference the answer table
                    CountOfCachedSubQueries++;
                    toReturn += tabplusOne + CachedAggregateConfigurationResultsManager.CachingPrefix + aggregate.Name + @"*/" + Environment.NewLine;
                    toReturn += tabplusOne + "select * from " + existingTable.GetFullyQualifiedName() + Environment.NewLine;
                    return(toReturn);
                }

                //we do not have an uptodate answer available in the cache :(
            }

            //get the SQL from the builder (for the current configuration) - without parameters
            string currentBlock = builderSqlWithoutParameters;

            //import parameters unless caching was used
            Dictionary <string, string> renameOperations;

            ParameterManager.ImportAndElevateResolvedParametersFromSubquery(builder.ParameterManager, out renameOperations);

            //rename in the SQL too!
            foreach (KeyValuePair <string, string> kvp in renameOperations)
            {
                currentBlock = ParameterCreator.RenameParameterInSQL(currentBlock, kvp.Key, kvp.Value);
            }

            //tab in the current block
            toReturn += tabplusOne + currentBlock.Replace("\r\n", "\r\n" + tabplusOne);
            return(toReturn);
        }
Esempio n. 21
0
 public SphereElementSchema()
     : base("Sphere")
 {
     //增加参数
     AddParameter("Radius", ParameterCreator.Create(5.0f));
 }
Esempio n. 22
0
        public bool HandleRename(ISqlParameter parameter, string oldName, string newName)
        {
            if (string.IsNullOrWhiteSpace(newName))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(oldName))
            {
                return(false);
            }

            //they are the same name!
            if (oldName.Equals(newName))
            {
                return(false);
            }

            if (!parameter.ParameterName.Equals(newName))
            {
                throw new ArgumentException("Expected parameter " + parameter + " to have name '" + newName + "' but it's value was " + parameter.ParameterName + ", this means someone was lying about the rename event");
            }

            var owner = parameter.GetOwnerIfAny();

            var filter = owner as IFilter;

            if (filter == null || filter is SpontaneousObject)
            {
                return(false);
            }

            //There is no WHERE SQL anyway
            if (string.IsNullOrWhiteSpace(filter.WhereSQL))
            {
                return(false);
            }

            if (_yesNoToAll.ShowDialog("Would you like to rename Parameter " + oldName + " to " + newName + " in Filter " + filter + "?",
                                       "Rename parameter") == DialogResult.Yes)
            {
                string before = filter.WhereSQL;
                string after  = ParameterCreator.RenameParameterInSQL(before, oldName, newName);

                //no change was actually made
                if (before.Equals(after))
                {
                    return(false);
                }

                filter.WhereSQL = after;
                filter.SaveToDatabase();

                if (!RefactoredFilters.Contains(filter))
                {
                    RefactoredFilters.Add(filter);
                }

                return(true);
            }

            return(false);
        }