Beispiel #1
0
 public Converter(Specification S, G25.CG.Shared.CGdata cgd, G25.fgs F)
 {
     m_specification = S;
     m_cgd = cgd;
     m_fgs = F;
     m_fgs.InitArgumentPtrFromTypeNames(S);
 }
Beispiel #2
0
        public static Specification ReadHeaderInformation(XmlDocument document)
        {
            var spec = new Specification();
            var top = document.DocumentElement;
            spec.name = top.GetAttribute("name");

            var lifecycle = top.GetAttribute(LifecycleAtt);
            spec.Lifecycle = lifecycle.AsLifecycle();

            spec.id = top.ReadId();
            var maxRetries = top.GetAttribute(MaxRetries);
            spec.MaxRetries = maxRetries.IsEmpty() ? 0 : int.Parse(maxRetries);

            try
            {
                var lastUpdatedString = top.GetAttribute(LastUpdated);
                var lastUpdated = !lastUpdatedString.IsEmpty() ? DateTime.Parse(top.GetAttribute(LastUpdated)) : DateTime.Now;
                spec.LastUpdated = lastUpdated;
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error trying to read the last updated date\n {e}");
            }


            spec.name = top.GetAttribute(Name);

            var tags = top.GetAttribute(TagsAtt);
            if (tags.IsNotEmpty())
            {
                spec.Tags.AddRange(tags.ToDelimitedArray());
            }
            return spec;
        }
Beispiel #3
0
        public static void Run(Configuration config, Specification spec)
        {
            var syntax = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(config.Namespace));
            syntax = syntax.WithLeadingTrivia(syntax.GetLeadingTrivia()
                .Add(SyntaxFactory.Comment($"//{Messages.VersionIdentifierPrefix}:{Configuration.nSwaggerVersion}"))
                .Add(SyntaxFactory.Comment($"// {Messages.Notice}"))
                .Add(SyntaxFactory.Comment($"// {Messages.LastGenerated} {DateTime.UtcNow:o}")));

            syntax = syntax.AddUsings(Using("System"),
                                      Using("System.Collections.Generic"),
                                      Using("System.Diagnostics"),
                                      Using("System.IO"),
                                      Using("System.Linq"),
                                      Using("System.Net"),
                                      Using("System.Net.Http"),
                                      Using("System.Net.Http.Headers"),
                                      Using("System.Threading"),
                                      Using("System.Threading.Tasks"),
                                      Using("Newtonsoft.Json"));

            if (config.IncludeHTTPClientForCSharp)
            {
                httpCode = File.ReadAllText(Path.Combine(config.HTTPCSPath, "HTTPClient.cs"));
            }

            syntax = Go(syntax, config, spec);
            End(config, syntax);
        }
Beispiel #4
0
        protected G25.SMV m_smv2 = null; ///< if function over SMV, type goes here

        #endregion Fields

        #region Methods

        /// <summary>
        /// Checks if this FunctionGenerator can implement a certain function.
        /// </summary>
        /// <param name="S">The specification of the algebra.</param>
        /// <param name="F">The function to be implemented.</param>
        /// <returns>true if 'F' can be implemented</returns>
        public override bool CanImplement(Specification S, G25.fgs F)
        {
            //String type F.GetArgumentTypeName(0, S.m_GMV.Name);
            return ((F.Name == "equals") && (F.MatchNbArguments(NB_ARGS)) &&
                G25.CG.Shared.Functions.NotMixSmvGmv(S, F, NB_ARGS, S.m_GMV.Name) &&
                G25.CG.Shared.Functions.NotUseOm(S, F, NB_ARGS, S.m_GMV.Name));
        }
        public Specification GetSpecification()
        {
            if (_resolvedSpecification == null)
            {
                //Lazy Load Specification
                if (String.IsNullOrEmpty(_specificationType))
                {
                    //No Specification specified, so get Default Specification For Type from Validation Catalog
                    _resolvedSpecification = ValidationCatalog.SpecificationContainer.TryGetSpecification(GetTypeToValidate());
                }
                else
                {
                    //Get Specification from Type
                    //Create type from string
                    var specType = System.Type.GetType(_specificationType);

                    if (specType == null)
                    {
                        //Type creation failed
                        return null;
                    }
                    else
                    {
                        //Query the Validation Catalog from the specification that matches type in the Catalog
                        _resolvedSpecification = ValidationCatalog.SpecificationContainer.GetAllSpecifications().Where(
                            x => x.GetType() == specType).FirstOrDefault();
                    }
                }
            }

            return _resolvedSpecification;
        }
Beispiel #6
0
        public void Should_build_predicate_from_lambda()
        {
            Expression<Func<string, bool>> expected = x => string.IsNullOrEmpty(x);
            var target = new Specification<string>(expected);

            Assert.That(target.Predicate, Is.SameAs(expected));
        }
        public MarkdownReader(TextReader reader)
        {
            _reader = reader;
            _spec = new Specification();

            _modes.Push(new HeaderMode(_spec));
        }
Beispiel #8
0
 /// <summary>
 /// Returns the code for dualization wrt to whole space using metric <c>M</c>.
 /// The code is composed of calls to functions generated by <c>WriteGmvDualParts()</c>.
 /// 
 /// This function uses <c>cdg.m_gmvDualPartFuncNames</c>, but only to check whether a
 /// geometric product of some group with the pseudoscalar will get non-zero results in some
 /// other group.
 /// 
 /// The returned code is only the body. The function declaration is not included.
 /// </summary>
 /// <param name="S">Specification of algebra (used for general multivector type, output language).</param>
 /// <param name="cgd">Used for <c>m_gmvDualPartFuncNames</c>.</param>
 /// <param name="FT">Floating point type.</param>
 /// <param name="M">The metric of the dual.</param>
 /// <param name="FAI">Info about function arguments</param>
 /// <param name="resultName">Name of variable where the result goes (in the generated code).</param>
 /// <param name="dual">When true, 'dual' is generated, otherwise, 'undual' is generated.</param>
 /// <returns>code for the requested product type.</returns>
 public static string GetDualCode(Specification S, G25.CG.Shared.CGdata cgd, G25.FloatType FT, 
     G25.Metric M, G25.CG.Shared.FuncArgInfo[] FAI, string resultName, bool dual)
 {
     if (S.OutputCppOrC())
         return GetDualCodeCppOrC(S, cgd, FT, M, FAI, resultName, dual);
     else return GetDualCodeCSharpOrJava(S, cgd, FT, M, FAI, resultName, dual);
 }
Beispiel #9
0
        private static void WriteDefinition(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, G25.Constant C)
        {
            // assume only SMV constants for now
            G25.SMV smv = C.Type as G25.SMV;
            ConstantSMV Csmv = C as ConstantSMV;

            // MANGLED_TYPENAME MANGLED_CONSTANT_NAME = {...}
            SB.Append(FT.GetMangledName(S, C.Type.GetName()));
            SB.Append(" ");
            SB.Append(FT.GetMangledName(S, C.Name));
            SB.Append(" = {");

            if (smv.NbNonConstBasisBlade == 0)
            {
                // 'C' does not allow empty structs, so there is a filler that must be initialized
                SB.Append("0");
            }
            else
            {
                if (S.m_coordStorage == COORD_STORAGE.ARRAY)
                    SB.Append("{");

                for (int c = 0; c < smv.NbNonConstBasisBlade; c++)
                {
                    if (c > 0) SB.Append(", ");
                    SB.Append(FT.DoubleToString(S, Csmv.Value[c]));
                }

                if (S.m_coordStorage == COORD_STORAGE.ARRAY)
                    SB.Append("}");
            }

            SB.AppendLine("};");
        }
Beispiel #10
0
        public static G25.VariableType CreateSyntheticSMVtype(Specification S, CGdata cgd, FloatType FT, RefGA.Multivector value)
        {
            // make up list of basis blades
            rsbbp.BasisBlade[] L = new rsbbp.BasisBlade[value.BasisBlades.Length];
            for (int i = 0 ; i < value.BasisBlades.Length; i++)
            {
                RefGA.BasisBlade B = value.BasisBlades[i];
                if (B.symScale == null) L[i] = new rsbbp.BasisBlade(new RefGA.BasisBlade(B.bitmap), B.scale); // constant value
                else L[i] = new rsbbp.BasisBlade(new RefGA.BasisBlade(B.bitmap)); // non-const value
            }

            // get other required info
            String name = "nameOfType";
            SMV.MULTIVECTOR_TYPE mvType = SMV.MULTIVECTOR_TYPE.MULTIVECTOR;
            String comment = "MISSING; PLEASE ADD TO SPECIFICATION";
            //String constantName = null;

            // create the type
            G25.SMV synSMV = new G25.SMV(name, L, mvType, comment);

            // throw exception
            throw new G25.UserException("Missing specialized multivector type.\n" +
                "Please add the following XML to the specification to fix the dependency:\n" +
                XML.SMVtoXmlString(S, synSMV));
        }
        public void AddOrganizationHierarchy(Organization parent,Organization child,OrganizationHierarchyType organizationHierarchyType)
        {
            Guard.Against<ArgumentNullException>(_organizationHierarchyRepository == null, "建構式需指定repository");

            OrganizationHierarchy organizationHierarchy =
                new OrganizationHierarchy()
                {
                    Level = 1,
                    ParentOrganizationId = parent.Id,
                    ChildOrganizationId = child.Id,
                    OrganizationHierarchyType = organizationHierarchyType
                };
            _organizationHierarchyRepository.SaveOrUpdate(organizationHierarchy);

            ISpecification<OrganizationHierarchy> specFindParents =
                new Specification<OrganizationHierarchy>(
                    s => s.ChildOrganizationId == parent.Id && s.OrganizationHierarchyType == organizationHierarchyType);

            IList<OrganizationHierarchy> allParents = _organizationHierarchyRepository.Query(specFindParents);

            foreach(var up in allParents)
            {
                OrganizationHierarchy hierarchy =
                   new OrganizationHierarchy()
                   {
                       Level = up.Level + 1,
                       ParentOrganizationId = up.ParentOrganizationId,
                       ChildOrganizationId = child.Id,
                       OrganizationHierarchyType = organizationHierarchyType
                   };
                _organizationHierarchyRepository.SaveOrUpdate(hierarchy);
            }
        }
Beispiel #12
0
        public static void GenerateBasicInfo(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd)
        {
            string accessModifier = Keywords.ConstAccessModifier(S);
            string accessModifierArr = Keywords.ConstArrayAccessModifier(S);
            string stringType = Keywords.StringType(S);
            string boolType = G25.CG.Shared.CodeUtil.GetBoolType(S);

            // dimension of space
            new G25.CG.Shared.Comment("The dimension of the space").Write(SB, S, 1);
            SB.AppendLine("\tpublic " + accessModifier + " int SpaceDim = " + S.m_dimension + ";");

            // number of groups in general multivector
            new G25.CG.Shared.Comment("Number of groups/grades of coordinates in a multivector").Write(SB, S, 1);
            SB.AppendLine("\tpublic " + accessModifier + " int NbGroups = " + S.m_GMV.NbGroups + ";");

            // Euclidean metric?
            new G25.CG.Shared.Comment("Is the metric of the space Euclidean? (false or true)").Write(SB, S, 1);
            SB.AppendLine("\tpublic " + accessModifier + " " + boolType + " MetricEuclidean = " +
                (S.GetMetric("default").m_metric.IsEuclidean() ? "true" : "false") + ";");

            // basis vector names
            new G25.CG.Shared.Comment("Names of the basis vectors.").Write(SB, S, 1);
            SB.AppendLine("\tpublic " + accessModifierArr + " " + stringType + "[] BasisVectorNames = new " + stringType + "[] {");
            SB.Append("\t\t");
            for (int i = 0; i < S.m_dimension; i++)
            {
                if (i > 0) SB.Append(", ");
                SB.Append("\"" + S.m_basisVectorNames[i] + "\"");
            }
            SB.AppendLine("");
            SB.AppendLine("\t};");
        }
Beispiel #13
0
        /// <summary>
        /// Writes a shortcut for 'type', 'fgs'.
        /// </summary>
        /// <param name="SB">Where the code goes.</param>
        /// <param name="S">Used for basis vector names and output language.</param>
        /// <param name="cgd">Not used yet.</param>
        /// <param name="FT">Float point type of 'type'.</param>
        /// <param name="type">The type for which shortcuts should be written.</param>
        /// <param name="fgs"></param>
        /// <param name="FAI"></param>
        public static void WriteFunctionShortcut(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, G25.VariableType type,
            G25.fgs fgs, FuncArgInfo[] FAI)
        {
            int nbTabs = 1;

            FuncArgInfo[] tailFAI = getTail(FAI);

            string shortcutCall = getShortcutCall(S, fgs, tailFAI);

            SB.AppendLine("");

            // output comment
            new Comment("shortcut to " + shortcutCall).Write(SB, S, nbTabs);

            bool inline = false;
            bool staticFunc = false;
            string returnType = FT.GetMangledName(S, fgs.ReturnTypeName);
            FuncArgInfo returnArgument = null;

            SB.Append('\t', nbTabs);
            Functions.WriteDeclaration(SB, S, cgd,
                inline, staticFunc, returnType, fgs.OutputName,
                returnArgument, tailFAI);
            SB.AppendLine(" {");

            SB.Append('\t', nbTabs+1);
            SB.Append("return ");
            SB.Append(shortcutCall);
            SB.AppendLine(";");

            SB.Append('\t', nbTabs);
            SB.AppendLine("}");
        }
 public void Complex_Specification_Should_Eval_ToTrue()
 {
     var testObject = new TestObject { FirstName = "John", LastName = "Doe", Age = 20 };
     var testSpec = new Specification<TestObject>(x => x.Age < 30) &
                    new Specification<TestObject>(x => x.FirstName.StartsWith("J"));
     Assert.That(testSpec.IsSatisfiedBy(testObject));
 }
Beispiel #15
0
        public static Dictionary<string, int> GetSpecializedTypeDictionary(Specification S)
        {
            Dictionary<string, int> D = new Dictionary<string, int>();

            int idx = 0;

            // gmv
            D[S.m_GMV.Name] = idx;
            idx++;

            // float types
            foreach (FloatType FT in S.m_floatTypes)
            {
                D[FT.GetName()] = idx;
                idx++;
            }

            // specialized types
            foreach (G25.SMV smv in S.m_SMV)
            {
                D[smv.GetName()] = idx;
                idx++;
            }

            return D;
        }
Beispiel #16
0
        /// <summary>
        /// Generates a source file with the GOM class definition.
        /// </summary>
        /// <param name="S"></param>
        /// <param name="cgd"></param>
        /// <param name="FT"></param>
        /// <returns></returns>
        public static string GenerateCode(Specification S, G25.CG.Shared.CGdata cgd, FloatType FT)
        {
            G25.GOM gom = S.m_GOM;
            string className = FT.GetMangledName(S, gom.Name);

            // get range vector type
            G25.SMV rangeVectorType = G25.CG.Shared.OMinit.GetRangeVectorType(S, FT, cgd, gom);
            string rangeVectorSMVname = FT.GetMangledName(S, rangeVectorType.Name);

            // get filename, list of generated filenames
            List<string> generatedFiles = new List<string>();
            string sourceFilename = MainGenerator.GetClassOutputPath(S, className);
            generatedFiles.Add(sourceFilename);

            // get StringBuilder where all generated code goes
            StringBuilder SB = new StringBuilder();

            // get a new 'cgd' where all ouput goes to the one StringBuilder SB
            cgd = new G25.CG.Shared.CGdata(cgd, SB, SB, SB);

            // output license, copyright
            G25.CG.Shared.Util.WriteCopyright(SB, S);
            G25.CG.Shared.Util.WriteLicense(SB, S);

            // open namespace
            G25.CG.Shared.Util.WriteOpenNamespace(SB, S);

            // write class comment
            G25.CG.CSJ.GOM.WriteComment(SB, S, cgd, FT, gom);

            // open class
            G25.CG.Shared.Util.WriteOpenClass(SB, S, G25.CG.Shared.AccessModifier.AM_public, className, null, null);

            // write member variables
            G25.CG.CSJ.GOM.WriteMemberVariables(SB, S, cgd, FT, gom);

            // write constructors
            G25.CG.CSJ.GOM.WriteConstructors(SB, S, cgd, FT, gom, className, rangeVectorSMVname);

            // write set functions
            G25.CG.CSJ.GOM.WriteSetIdentity(SB, S, cgd, FT);
            G25.CG.CSJ.GOM.WriteSetCopy(SB, S, cgd, FT);
            G25.CG.CSJ.GOM.WriteSetVectorImages(S, cgd, FT, false, false); // false, false = matrixMode, transpose
            G25.CG.CSJ.GOM.WriteSetVectorImages(S, cgd, FT, true, false); // true, false = matrixMode, transpose
            G25.CG.CSJ.GOM.WriteSOMtoGOMcopy(S, cgd, FT);

            // write shortcuts for functions
            G25.CG.Shared.Shortcut.WriteFunctionShortcuts(SB, S, cgd, FT, gom);

            // close class
            G25.CG.Shared.Util.WriteCloseClass(SB, S, className);

            // close namespace
            G25.CG.Shared.Util.WriteCloseNamespace(SB, S);

            // write all to file
            G25.CG.Shared.Util.WriteFile(sourceFilename, SB.ToString());

            return sourceFilename;
        }
Beispiel #17
0
        public static List<string> GenerateCode(Specification S, G25.CG.Shared.CGdata cgd)
        {
            // get filename, list of generated filenames
            List<string> generatedFiles = new List<string>();

            if (!S.m_reportUsage) return generatedFiles;

            string sourceFilename = S.GetOutputPath(GetRawSourceFilename(S));
            generatedFiles.Add(sourceFilename);

            // get StringBuilder where all generated code goes
            StringBuilder SB = new StringBuilder();

            // output license, copyright
            G25.CG.Shared.Util.WriteCopyright(SB, S);
            G25.CG.Shared.Util.WriteLicense(SB, S);

            // using ...
            Util.WriteGenericUsing(SB, S);
            SB.AppendLine("using System.Collections.Generic;");
            SB.AppendLine("using System.Text;");

            // open namespace
            G25.CG.Shared.Util.WriteOpenNamespace(SB, S);

            cgd.m_cog.EmitTemplate(SB, "reportUsage");

            // close namespace
            G25.CG.Shared.Util.WriteCloseNamespace(SB, S);

            // write all to file
            G25.CG.Shared.Util.WriteFile(sourceFilename, SB.ToString());

            return generatedFiles;
        }
Beispiel #18
0
        /// <summary>
        /// Writes a function to copy an GOM struct
        /// </summary>
        /// <param name="S">Used for basis vector names and output language.</param>
        /// <param name="cgd">Results go here. Also intermediate data for code generation. Also contains plugins and cog.</param>
        public static void WriteCopy(Specification S, G25.CG.Shared.CGdata cgd)
        {
            StringBuilder declSB = cgd.m_declSB;
            StringBuilder defSB = (S.m_inlineSet) ? cgd.m_inlineDefSB : cgd.m_defSB;
            declSB.AppendLine("");
            defSB.AppendLine("");

            string dstName = "dst";
            string srcName = "src";
            string matrixName = "m";

            foreach (G25.FloatType FT in S.m_floatTypes)
            {
                String typeName = FT.GetMangledName(S, S.m_GOM.Name);
                String funcName = typeName + "_copy";
                //string comment = "/** Copies " + typeName + " */";
                declSB.AppendLine("void " + funcName + "(" + typeName + "*" + dstName + ", const " + typeName + "*" + srcName + ");");
                defSB.AppendLine("void " + funcName + "(" + typeName + "*" + dstName + ", const " + typeName + "*" + srcName + ") {");
                for (int g = 1; g < S.m_GOM.Domain.Length; g++)
                {
                    int s = S.m_GOM.Domain[g].Length * S.m_GOM.Range[g].Length;
                    defSB.AppendLine("\t" + G25.CG.Shared.Util.GetCopyCode(S, FT, srcName + "->" + matrixName + g, dstName + "->" + matrixName + g, s));
                } // end of loop over all grades of the OM
                defSB.AppendLine("}");
            }
        }
Beispiel #19
0
        /// <summary>
        /// Writes any addition or subtraction function for general multivectors,
        /// based on CASN parts code.
        /// </summary>
        /// <param name="S"></param>
        /// <param name="cgd"></param>
        /// <param name="FT"></param>
        /// <param name="FAI"></param>
        /// <param name="F"></param>
        /// <param name="comment"></param>
        /// <param name="funcType">ADD, SUB or HP</param>
        /// <returns>Full name of generated function.</returns>
        public static string WriteAddSubHpFunction(Specification S, G25.CG.Shared.CGdata cgd, FloatType FT,
            G25.CG.Shared.FuncArgInfo[] FAI, G25.fgs F,
            Comment comment, G25.CG.Shared.CANSparts.ADD_SUB_HP_TYPE funcType)
        {
            // setup instructions
            System.Collections.Generic.List<G25.CG.Shared.Instruction> I = new System.Collections.Generic.List<G25.CG.Shared.Instruction>();
            int nbTabs = 1;

            // write this function:
            string code = G25.CG.Shared.CANSparts.GetAddSubtractHpCode(S, cgd, FT, funcType, FAI, fgs.RETURN_ARG_NAME);

            // add one instruction (verbatim code)
            I.Add(new G25.CG.Shared.VerbatimCodeInstruction(nbTabs, code));

            // because of lack of overloading, function names include names of argument types
            G25.fgs CF = G25.CG.Shared.Util.AppendTypenameToFuncName(S, FT, F, FAI);

            // setup return type and argument:
            string returnTypeName = FT.GetMangledName(S, S.m_GMV.Name);
            G25.CG.Shared.FuncArgInfo returnArgument = null;
            if (S.OutputC())
                returnArgument = new G25.CG.Shared.FuncArgInfo(S, CF, -1, FT, S.m_GMV.Name, false); // false = compute value

            string funcName = CF.OutputName;
            //if (S.OutputC())
              //  funcName = FT.GetMangledName(S, funcName);

            // write function
            bool inline = false; // never inline GMV functions
            bool staticFunc = Functions.OutputStaticFunctions(S);
            G25.CG.Shared.Functions.WriteFunction(S, cgd, F, inline, staticFunc, returnTypeName, funcName, returnArgument, FAI, I, comment);

            return funcName;
        }
Beispiel #20
0
 /// <summary>
 /// Checks if this FunctionGenerator can implement a certain function.
 /// </summary>
 /// <param name="S">The specification of the algebra.</param>
 /// <param name="F">The function to be implemented.</param>
 /// <returns>true if 'F' can be implemented</returns>
 public override bool CanImplement(Specification S, G25.fgs F)
 {
     return (((F.Name == "hp") || (F.Name == "ihp")) && (F.MatchNbArguments(NB_ARGS)) &&
         G25.CG.Shared.Functions.NotMixScalarGmv(S, F, NB_ARGS, S.m_GMV.Name) &&
         G25.CG.Shared.Functions.NotMixSmvGmv(S, F, NB_ARGS, S.m_GMV.Name) &&
         G25.CG.Shared.Functions.NotUseOm(S, F, NB_ARGS, S.m_GMV.Name));
 }
Beispiel #21
0
        private static string GetComment(Specification S, bool declOnly, G25.fgs FGS, G25.Operator op, G25.FloatType FT, bool assign)
        {
            StringBuilder SB = new StringBuilder();

            if ((S.OutputCpp()) && op.IsUnaryInPlace())
            {
                if (op.IsPrefix)
                {
                    SB.Append("returns (" + FGS.ArgumentVariableNames[0] + " = " + FGS.OutputName + "(" + FGS.ArgumentVariableNames[0] + "))");
                }
                else
                {
                    SB.Append("returns input value of " + FGS.ArgumentVariableNames[0] + ", but sets " + FGS.ArgumentVariableNames[0] + " to " + FGS.OutputName + "(" + FGS.ArgumentVariableNames[0] + ")");
                }
            }
            else if (assign)
            {
                SB.Append("returns (" + FGS.ArgumentVariableNames[0] + " = " + FGS.OutputName + "(" + FGS.ArgumentVariableNames[0]);
                SB.Append(", " + FGS.ArgumentVariableNames[1]);
                SB.Append("))");
            }
            else {
                SB.Append("returns " + FGS.OutputName + "(" + FGS.ArgumentVariableNames[0]);
                if (op.IsBinary())
                    SB.Append(", " + FGS.ArgumentVariableNames[1]);
                SB.Append(")");
            }

            return SB.ToString();
        }
Beispiel #22
0
        public static Specification ReadSpecHeader(string filename)
        {
            using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                var reader = System.Xml.XmlReader.Create(stream);
                /* TODO: on mono you need to Read otherwise the XmlReader
                 * is in an Initial state, which msdn says means you shouldn't call
                 * ReadToNextSibling. But calling Read progresses the reader forward so
                 * that ReadToNextSibling skips the test without a <?xml> first line...
                 */
                reader.Read();
                if (!(reader.IsStartElement() || reader.Name == "Test" || reader.Name == "Spec"))
                {
                    reader.ReadToNextSibling("*");
                }

                var spec = new Specification
                {
                    id = reader.GetAttribute("id") ?? Guid.NewGuid().ToString(),
                    name = reader.GetAttribute("name"),
                    Lifecycle = reader.GetAttribute("lifecycle").AsLifecycle(),
                    Filename = filename,
                    SpecType = SpecType.header
                };

                var maxRetries = reader.GetAttribute(XmlConstants.MaxRetries);
                spec.MaxRetries = maxRetries.IsEmpty() ? 0 : int.Parse(maxRetries);

                return spec;
            }
        }
Beispiel #23
0
        private static void WriteDefinition(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, G25.Constant C)
        {
            // assume only SMV constants for now
            G25.SMV smv = C.Type as G25.SMV;
            ConstantSMV Csmv = C as ConstantSMV;

            string className = FT.GetMangledName(S, smv.Name);

            // MANGLED_TYPENAME MANGLED_CONSTANT_NAME = {...}
            SB.Append(className);
            SB.Append(" ");
            SB.Append(FT.GetMangledName(S, C.Name));

            if (smv.NbNonConstBasisBlade > 0) {
                // MANGLED_TYPENAME MANGLED_CONSTANT_NAME(...)
                SB.Append("(" + className + "::" + G25.CG.Shared.SmvUtil.GetCoordinateOrderConstant(S, smv));

                for (int c = 0; c < smv.NbNonConstBasisBlade; c++)
                {
                    SB.Append(", ");
                    SB.Append(FT.DoubleToString(S, Csmv.Value[c]));
                }

                SB.Append(")");
            }

            SB.AppendLine(";");
        }
Beispiel #24
0
        private MessageFormatter getFormatter(Specification spec)
        {
            if (_formatters.ContainsKey(spec.SpecificationCategory))
                return _formatters[spec.SpecificationCategory];

            return MessageFormatterRegistry.GetFormatter(spec.SpecificationCategory);
        }
Beispiel #25
0
        public static Specification ReadHeaderInformation(XmlDocument document)
        {
            var spec = new Specification();
            var top = document.DocumentElement;
            spec.name = top.GetAttribute("name");

            var lifecycle = top.GetAttribute(LifecycleAtt);
            spec.Lifecycle = lifecycle.AsLifecycle();

            spec.id = top.ReadId();
            var maxRetries = top.GetAttribute(MaxRetries);
            spec.MaxRetries = maxRetries.IsEmpty() ? 0 : int.Parse(maxRetries);

            var lastUpdatedString = top.GetAttribute(LastUpdated);
            var lastUpdated = !lastUpdatedString.IsEmpty() ? DateTime.Parse(top.GetAttribute(LastUpdated)) : DateTime.Now;
            spec.LastUpdated = lastUpdated;

            var expirationPeriodString = top.GetAttribute(ExpirationPeriod);
            var expirationPeriod = expirationPeriodString.IsEmpty() ? 0 : int.Parse(expirationPeriodString);
            spec.ExpirationPeriod = expirationPeriod;

            spec.name = top.GetAttribute(Name);

            var tags = top.GetAttribute(TagsAtt);
            if (tags.IsNotEmpty())
            {
                spec.Tags.AddRange(tags.ToDelimitedArray());
            }
            return spec;
        }
Beispiel #26
0
        /// <summary>
        /// Writes a function to copy the value of one SMV struct to another, for all floating point types.
        /// </summary>
        /// <param name="S">Used for basis vector names and output language.</param>
        /// <param name="cgd">Intermediate data for code generation. Also contains plugins and cog.</param>
        public static void WriteCopy(Specification S, G25.CG.Shared.CGdata cgd)
        {
            StringBuilder declSB = cgd.m_declSB;
            StringBuilder defSB = (S.m_inlineSet) ? cgd.m_inlineDefSB : cgd.m_defSB;
            declSB.AppendLine("");
            defSB.AppendLine("");

            foreach (G25.FloatType FT in S.m_floatTypes)
            {
                foreach (G25.SMV smv in S.m_SMV)
                {
                    if (smv.NbNonConstBasisBlade == 0) continue;

                    String typeName = FT.GetMangledName(S, smv.Name);
                    String funcName = typeName + "_copy";
                    bool mustCast = false;

                    G25.fgs F = new G25.fgs(funcName, funcName, "", new String[] { smv.Name }, null, new String[] { FT.type }, null, null, null); // null, null, null = metricName, comment, options
                    F.InitArgumentPtrFromTypeNames(S);
                    bool computeMultivectorValue = false;
                    G25.CG.Shared.FuncArgInfo returnArgument = new G25.CG.Shared.FuncArgInfo(S, F, -1, FT, smv.Name, computeMultivectorValue);
                    int nbArgs = 1;
                    G25.CG.Shared.FuncArgInfo[] FAI = G25.CG.Shared.FuncArgInfo.GetAllFuncArgInfo(S, F, nbArgs, FT, null, computeMultivectorValue);

                    declSB.AppendLine("/** Copies " + typeName + ": " + FAI[0].Name + " = " + returnArgument.Name + " */");

                    RefGA.Multivector value = G25.CG.Shared.Symbolic.SMVtoSymbolicMultivector(S, smv, FAI[0].Name, FAI[0].Pointer);

                    bool staticFunc = false;
                    G25.CG.Shared.Functions.WriteAssignmentFunction(S, cgd,
                        S.m_inlineSet, staticFunc, "void", null, funcName, returnArgument, FAI, FT, mustCast, smv, returnArgument.Name, returnArgument.Pointer, value);
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Resolves a converter (underscore constructor) dependency.
        /// Searches for a converter from 'fromType' to 'toType'.
        /// 
        /// If the function is not found, this is also enlisted in cgd.m_missingDependencies.
        /// Call cgd.PrintMissingDependencies() should be called to report the missing dependencies
        /// to the end-user.
        /// </summary>
        /// <param name="S">The spec.</param>
        /// <param name="cgd">Missing dependencies go into cgd.m_missingDependencies.</param>
        /// <param name="fromType"></param>
        /// <param name="toType"></param>
        /// <param name="FT"></param>
        /// <returns></returns>
        public static string GetConverterDependency(Specification S, CGdata cgd, string fromType, string toType, G25.FloatType FT)
        {
            // look for 'funcName' in all G25.fgs in the spec
            //                    string funcName = "_" + FT.GetMangledName(S, toType);
            string funcName = "_" + toType;
            foreach (G25.fgs F in S.m_functions)
            {
                if (F.IsConverter(S)) // is 'F' a converter (underscore constructor)?
                {
                    if ((F.Name == funcName) &&
                        (F.ArgumentTypeNames[0] == fromType))
                    {
                        return G25.CG.Shared.Converter.GetConverterName(S, F, FT.GetMangledName(S, fromType), FT.GetMangledName(S, toType));
                    }
                }
            }

            // converter not found: add it to missing deps:
            {
                // add dependency to list of missing deps:
                string outputName = null;
                string[] argumentTypes = new string[] { fromType };
                string[] argVarNames = null;
                string returnTypeName = null;
                string metricName = null;
                string comment = null;
                Dictionary<string, string> options = null;
                G25.fgs F = new G25.fgs(funcName, outputName, returnTypeName, argumentTypes, argVarNames, new string[] { FT.type }, metricName, comment, options);
                cgd.AddMissingDependency(S, F);
            }

            // return fictional name:
            G25.fgs tmpF = null;
            return "missingFunction_" + G25.CG.Shared.Converter.GetConverterName(S, tmpF, FT.GetMangledName(S, fromType), FT.GetMangledName(S, toType));
        }
		private void DownloadJsonDefinitions(Specification spec, IProgressBar pbar)
		{
			using (var client = new WebClient())
			{
				var html = client.DownloadString(spec.GithubListingUrl);
				FindJsonFilesOnListing(spec, html, pbar);
			}
		}
 public SpecificationToRun(Specification specification, string reason, Exception exception, MemberInfo foundOn)
 {
     FoundOn = foundOn;
     Specification = specification;
     Exception = exception;
     Reason = reason;
     IsRunnable = false;
 }
 public SpecificationToRun(Specification specification, MemberInfo foundOn)
 {
     IsRunnable = true;
     Reason = "";
     Exception = null;
     Specification = specification;
     FoundOn = foundOn;
 }
Beispiel #31
0
        public void EntityFrameworkRepositoryTests_RetrieveByOrSpecificationTest()
        {
            List <EFCustomer> customers = new List <EFCustomer> {
                new EFCustomer
                {
                    Address  = new EFAddress("China", "SH", "SH", "A street", "12345"),
                    UserName = "******",
                    Password = "******"
                },
                new EFCustomer
                {
                    Address  = new EFAddress("China", "SH", "SH", "A street", "12345"),
                    UserName = "******",
                    Password = "******"
                },
                new EFCustomer
                {
                    Address  = new EFAddress("China", "SH", "SH", "A street", "12345"),
                    UserName = "******",
                    Password = "******"
                },
                new EFCustomer
                {
                    Address  = new EFAddress("China", "SH", "SH", "A street", "12345"),
                    UserName = "******",
                    Password = "******"
                },
                new EFCustomer
                {
                    Address  = new EFAddress("China", "SH", "SH", "A street", "12345"),
                    UserName = "******",
                    Password = "******"
                }
            };
            IRepository <EFCustomer> repository = ServiceLocator.Instance.GetService <IRepository <EFCustomer> >();

            foreach (var cust in customers)
            {
                repository.Add(cust);
            }
            repository.Context.Commit();
            ISpecification <EFCustomer> spec = Specification <EFCustomer> .Eval(p => p.UserName.StartsWith("d")).Or(Specification <EFCustomer> .Eval(p => p.UserName == "cc"));

            var c = repository.FindAll(spec).Count();

            repository.Context.Dispose();
            Assert.IsNotNull(c);
            Assert.AreEqual(3, c);
        }
Beispiel #32
0
 private static char SeperatorOrSpace(this Specification spec)
 {
     return((spec as OptionSpecification).ToMaybe()
            .MapValueOrDefault(o => o.Separator != '\0' ? o.Separator : ' ', ' '));
 }
Beispiel #33
0
        public static List <IFramingElement> CompatibleObjects(HashSet <IFramingElement> objects, List <Specification> specifications, out List <Specification> compatibleSpecs, int limit = 1, bool sortDirection = true)
        {
            List <IFramingElement> res = new List <IFramingElement>();

            compatibleSpecs = new List <Specification>();
            List <string> valueCondPropName = new List <string>();

            // Only use specifications that are "applied" Zone Specifications.
            var appliedZoneSpecs = specifications.Where(s => s.IsAppliedZoneSpec()).ToList();

            if (appliedZoneSpecs.Count == 0)
            {
                BH.Engine.Reflection.Compute.RecordError($"No Applied Zone Specification found. The input Zone specifications do not have any {nameof(IsInZone)} condition, or do not have their {nameof(IsInZone.ClosedVolumes)} populated.");
                return(new List <IFramingElement>());
            }

            foreach (var obj in objects)
            {
                foreach (var spec in appliedZoneSpecs)
                {
                    // Remove any IsInZone condition from the specs.
                    // The kit of parts objects are just "archetypes" - not placed in a meaningful location of the model space.
                    Specification specCopy = spec.DeepClone();

                    specCopy.FilterConditions.RemoveAll(fc => fc is IsInZone);
                    specCopy.CheckConditions.RemoveAll(fc => fc is IsInZone);

                    // The Part of the Kit (object archetype) must be moved in its final location,
                    // so we can make sure that all other conditions can be evaluated on the actual object.
                    // e.g. if there are conditions - that are not IsInZone - that are based on position properties.
                    var          allClosedVolumes     = spec.FilterConditions.OfType <IsInZone>().SelectMany(c => c.ClosedVolumes);
                    List <Point> closedVolumesCentres = allClosedVolumes.Select(cv => cv.IBounds().Centre()).ToList();

                    closedVolumesCentres = BH.Engine.Geometry.Compute.CullDuplicates(closedVolumesCentres.ToList());

                    foreach (var pt in closedVolumesCentres)
                    {
                        ICurve geom       = obj.Location;
                        var    moveVector = BH.Engine.Geometry.Create.Vector(geom.IBounds().Centre(), pt);

                        var movedGeom = BH.Engine.Geometry.Modify.ITranslate(geom, moveVector);

                        IFramingElement objCopy = obj.DeepClone();
                        objCopy.Location = movedGeom;

                        var specRes = VerifySpecification(new List <object>()
                        {
                            objCopy
                        }, specCopy);
                        if (specRes.PassedObjects.Count != 1)
                        {
                            continue;
                        }

                        valueCondPropName.AddRange(spec.CheckConditions.OfType <IValueCondition>().Select(c => c.PropertyName));

                        res.Add(obj);
                        compatibleSpecs.Add(spec);
                    }
                }
            }

            res = res.Distinct().ToList();
            valueCondPropName = valueCondPropName.Distinct().ToList();
            compatibleSpecs   = compatibleSpecs.Distinct().ToList();

            if (valueCondPropName.Count == 1)
            {
                res = res.OrderBy(obj => obj.ValueFromSource(valueCondPropName.First())).ToList();
            }

            if (!sortDirection)
            {
                res.Reverse();
            }

            if (res.Count() == 0)
            {
                BH.Engine.Reflection.Compute.RecordWarning("No compatible object found.");
                return(new List <IFramingElement>());
            }

            return(res.Take(limit).ToList());
        }
        public void TestNoCollectionFacet()
        {
            var facet = Specification.GetFacet(typeof(ICollectionFacet));

            Assert.IsNull(facet);
        }
        public void TestPluralFaced()
        {
            var facet = Specification.GetFacet(typeof(IPluralFacet));

            Assert.IsNotNull(facet);
        }
            public void Should_ThrowException_InfiniteReferencesLoopException_WithDetectedLoopInfo_When_ReferencesLoopDetected(string testId, Specification <TraversingTestCases.LoopClassA> specification, TraversingTestCases.LoopClassA model, string path, string infiniteLoopNestedPath, Type type)
            {
                _ = testId;
                _ = path;
                _ = infiniteLoopNestedPath;

                var modelScheme = ModelSchemeFactory.Create(specification);

                var context = new IsValidValidationContext(modelScheme, new ReferenceLoopProtectionSettings());

                Action action = () => context.EnterScope(modelScheme.RootSpecificationScopeId, model);

                var exception = action.Should().ThrowExactly <ReferenceLoopException>().And;

                exception.Path.Should().BeNull();
                exception.NestedPath.Should().BeNull();
                exception.Type.Should().Be(type);

                exception.Message.Should().Be($"Reference loop detected: object of type {type.GetFriendlyName()} has been detected twice in the reference graph, effectively creating the infinite references loop (where exactly, that information is not available - is that validation comes from IsValid method, please repeat it using the Validate method and examine the exception thrown)");
            }
Beispiel #37
0
        /// <summary>
        /// 分页获取文章
        /// </summary>
        /// <returns></returns>
        public List <Article_S> GetArticlesPaged(Article_S model, PageInfo pi)
        {
            using (var factory = new BaseAccess())
            {
                List <Orderby <ArticleEntity> > orders = new List <Orderby <ArticleEntity> >()
                {
                    new Orderby <ArticleEntity>(c => c.DT_ADD_TIME, SortOrder.Descending)
                };
                var spec = Specification <ArticleEntity> .Create(c => true);

                if (!string.IsNullOrEmpty(model.C_STATUS))
                {
                    spec &= Specification <ArticleEntity> .Create(c => c.C_STATUS == model.C_STATUS);
                }
                if (!string.IsNullOrEmpty(model.C_VERIFY_STATUS))
                {
                    spec &= Specification <ArticleEntity> .Create(c => c.C_VERIFY_STATUS == model.C_VERIFY_STATUS);
                }
                else
                {
                    spec &= Specification <ArticleEntity> .Create(c => c.C_VERIFY_STATUS == ((int)EMARTICLESTATUS.二级审核).ToString());
                }
                if (!string.IsNullOrEmpty(model.N_COLUMN_ID))
                {
                    if (model.N_COLUMN_ID == "999")
                    {
                        spec &= Specification <ArticleEntity> .Create(c => c.DT_ADD_TIME > DateTime.Now.AddDays(-7));

                        orders = new List <Orderby <ArticleEntity> >()
                        {
                            new Orderby <ArticleEntity>(c => c.N_HITS, SortOrder.Descending),
                            new Orderby <ArticleEntity>(c => c.DT_ADD_TIME, SortOrder.Descending)
                        };
                    }
                    else
                    {
                        spec &= Specification <ArticleEntity> .Create(c => c.N_COLUMN_ID.Contains(model.N_COLUMN_ID));
                    }
                }
                else if (!string.IsNullOrEmpty(model.VC_KEYWORDS))
                {
                    spec &= (Specification <ArticleEntity> .Create(c => c.VC_KEYWORDS.Contains(model.VC_KEYWORDS)) || Specification <ArticleEntity> .Create(c => c.VC_TITLE.Contains(model.VC_KEYWORDS)) || Specification <ArticleEntity> .Create(c => c.VC_CONTENT.Contains(model.VC_KEYWORDS)));
                }
                if (!string.IsNullOrEmpty(model.VC_TITLE))
                {
                    spec &= Specification <ArticleEntity> .Create(c => c.VC_TITLE.Contains(model.VC_TITLE));
                }

                var list = factory.GetPage <ArticleEntity>(pi, spec, orders);
                List <Article_S> modellist = new List <Article_S>();
                foreach (var item in list)
                {
                    if (item.N_COLUMN_ID == "0")
                    {
                        continue;
                    }
                    var modelitem = item.Adapter <Article_S>(new Article_S());
                    var column    = factory.GetSingle <MenuEntity>(Specification <MenuEntity> .Create(m => m.MenuCode == item.N_COLUMN_ID));
                    if (column != null)
                    {
                        modelitem.VC_COLUMN_NAME = column.MenuName;
                    }
                    modelitem.VC_ADD_OP_NAME    = item.OPADD == null ? "未知" : item.OPADD.UserDisplayName;
                    modelitem.VC_UPDATE_OP_NAME = item.OPUPDATE == null ? "未知" : item.OPUPDATE.UserDisplayName;
                    modelitem.VC_RECOMMEND_NAME = Enum.GetName(typeof(EMRECOMMENDLEVEL), (item.C_RECOMMEND_LEVEL).Convert <int>(1));
                    if (model.N_COLUMN_ID == "999")
                    {
                        modelitem.B_HOTPOINTS = true;
                    }
                    else
                    {
                        modelitem.B_HOTPOINTS = false;
                    }
                    modellist.Add(modelitem);
                }
                WriteLog("success");
                return(modellist);
            }
        }
Beispiel #38
0
 public static SpecificationToRun AsRunnable(this Specification specification)
 {
     return(new SpecificationToRun(specification, null));
 }
Beispiel #39
0
 /// <summary>
 /// Writes constructors of a GOM class to 'SB'.
 /// </summary>
 /// <param name="SB">Where the code goes.</param>
 /// <param name="S">Used for basis vector names and output language.</param>
 /// <param name="cgd">Intermediate data for code generation. Also contains plugins and cog.</param>
 /// <param name="FT">Float point type of 'GOM'.</param>
 /// <param name="gom">The general outermorphism for which the class should be written.</param>
 /// <param name="className">Mangled name of GOM class.</param>
 /// <param name="rangeVectorSMVname">The name of the SMV which can represent a column of the OM.</param>
 public static void WriteConstructors(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, G25.GOM gom, string className, string rangeVectorSMVname)
 {
     cgd.m_cog.EmitTemplate(SB, "GOMconstructors", "S=", S, "FT=", FT, "className=", className, "rangeVectorSMVname=", rangeVectorSMVname);
 }
Beispiel #40
0
 /// <summary>
 /// Writes comments of a GOM class to 'SB'.
 /// </summary>
 /// <param name="SB">Where the comment goes.</param>
 /// <param name="S">Used for basis vector names and output language.</param>
 /// <param name="cgd">Intermediate data for code generation. Also contains plugins and cog.</param>
 /// <param name="FT">Float point type of 'GOM'.</param>
 /// <param name="gom">The general outermorphism for which the class should be written.</param>
 public static void WriteComment(StringBuilder SB, Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, G25.GOM gom)
 {
     G25.CG.Shared.ClassComments.GetGomComment(S, cgd, FT, gom).Write(SB, S, 0);
 }
Beispiel #41
0
        } // end of WriteSetVectorImages()

        /// <summary>
        /// Writes functions to copy SOMs to GOM.
        /// </summary>
        /// <param name="S"></param>
        /// <param name="cgd">Results go here. Also intermediate data for code generation. Also contains plugins and cog.</param>
        /// <param name="FT">Float type</param>
        public static void WriteSOMtoGOMcopy(Specification S, G25.CG.Shared.CGdata cgd, FloatType FT)
        {
            G25.CG.Shared.OMinit.WriteSOMtoGOMcopy(S, cgd, FT);
        } // end of WriteSOMtoGOMcopy()
Beispiel #42
0
        }     // end of WriteCopy()

        /// <summary>
        /// Writes a function to set a GOM class according to vector images.
        /// Output goes into cdg.m_defSB
        /// </summary>
        /// <param name="S">Used for basis vector names and output language.</param>
        /// <param name="cgd">Results go here. Also intermediate data for code generation. Also contains plugins and cog.</param>
        /// <param name="FT">Float point type of 'GOM'.</param>
        /// <param name="matrixMode">When true, generates code for setting from matrix instead of vector images.</param>
        /// <param name="transpose">When this parameter is true and <c>matrixMode</c> is true, generates code for setting from transpose matrix.</param>
        public static void WriteSetVectorImages(Specification S, G25.CG.Shared.CGdata cgd, FloatType FT, bool matrixMode, bool transpose)
        {
            G25.CG.Shared.OMinit.WriteSetVectorImages(S, cgd, FT, matrixMode, transpose);
        } // end of WriteSetVectorImages()
Beispiel #43
0
 public IHttpActionResult GetRevisions()
 {
     return(this.Ok(
                this.noteRepository.FindAll(Specification <Note> .Eval(note => note.User.ID == this.CurrentLoginUser.ID))
                .Select(note => new { note.ID, note.Revision })));
 }
 public void Update(Specification specification)
 {
     _context.Entry(specification).State = EntityState.Modified;
     _context.SaveChanges();
 }
            public void Should_GetLoopProtectionReferencesStackCount_BeOne_BeforeAndAfterEnteringRootScope_When_RootModelReference_Exists(string id, Specification <TraversingTestCases.TestClassA> rootSpecification, TraversingTestCases.TestClassA model)
            {
                _ = id;

                var modelScheme = ModelSchemeFactory.Create(rootSpecification);

                var context = new IsValidValidationContext(modelScheme, new ReferenceLoopProtectionSettings(new object()));

                context.GetLoopProtectionReferencesStackCount().Should().Be(1);

                context.EnterScope(modelScheme.RootSpecificationScopeId, model);

                context.GetLoopProtectionReferencesStackCount().Should().Be(1);
            }
Beispiel #46
0
 public static Specification <Expression> CopySpecificationExpression(Specification <Expression> item)
 {
     return(new Specification <Expression>(CopyExpressionList(item.Expressions), item.Attributes));
 }
Beispiel #47
0
 protected EllipticFilter(double[] B, double[] A, Specification Spec) : base(B, A, Spec)
 {
 }
Beispiel #48
0
        /***************************************************/
        /**** Private Methods                           ****/
        /***************************************************/

        private static SpecificationResult VerifySpecification(List <object> objects, Specification specification)
        {
            // First apply filter to get relevant objects
            ConditionResult filterResult = VerifyConditions(objects, specification.FilterConditions);

            // Then apply the check to the filteredObject
            ConditionResult checkResult = VerifyConditions(filterResult.PassedObjects, specification.CheckConditions);


            return(PopulateSpecificationResult(specification, filterResult, checkResult));
        }
        public void TestNoTypeOfFacet()
        {
            var facet = (ITypeOfFacet)Specification.GetFacet(typeof(ITypeOfFacet));

            Assert.IsNull(facet);
        }
        public CalculationEditModelValidator(ISpecificationsRepository specificationsRepository, ICalculationsRepository calculationsRepository)
        {
            Guard.ArgumentNotNull(specificationsRepository, nameof(specificationsRepository));
            Guard.ArgumentNotNull(calculationsRepository, nameof(calculationsRepository));

            _specificationsRepository = specificationsRepository;
            _calculationsRepository   = calculationsRepository;

            RuleFor(model => model.Description)
            .NotEmpty()
            .WithMessage("You must give a description for the calculation");

            RuleFor(model => model.SpecificationId)
            .NotEmpty()
            .WithMessage("Null or empty specification Id provided")
            .CustomAsync(async(name, context, cancellationToken) =>
            {
                CalculationEditModel model = context.ParentContext.InstanceToValidate as CalculationEditModel;
                if (model != null && !string.IsNullOrWhiteSpace(model.SpecificationId))
                {
                    Specification specification = await _specificationsRepository.GetSpecificationById(model.SpecificationId);
                    if (specification == null)
                    {
                        context.AddFailure("Specification not found");
                        return;
                    }
                }
            });

            RuleFor(model => model.PolicyId)
            .NotEmpty()
            .WithMessage("You must select a policy or a sub policy");

            RuleFor(model => model.CalculationType)
            .IsInEnum()
            .WithMessage("You must specify a valid calculation type");

            RuleFor(model => model.Name)
            .NotEmpty()
            .WithMessage("You must give a unique calculation name")
            .Custom((name, context) =>
            {
                CalculationEditModel model = context.ParentContext.InstanceToValidate as CalculationEditModel;

                if (string.IsNullOrWhiteSpace(model.CalculationId))
                {
                    context.AddFailure("Calculation ID not specified on the model");
                    return;
                }

                if (!_calculationsRepository.IsCalculationNameValid(model.SpecificationId, model.Name, model.CalculationId).Result)
                {
                    context.AddFailure("Calculation with the same generated source code name already exists in this specification");
                }
            });

            RuleFor(model => model.AllocationLineId)
            .CustomAsync(async(name, context, cancellationToken) =>
            {
                CalculationEditModel model          = context.ParentContext.InstanceToValidate as CalculationEditModel;
                bool checkForDuplicateBaselineCalcs = false;
                bool requireAllocationLine          = false;

                if (model.CalculationType == CalculationType.Baseline)
                {
                    checkForDuplicateBaselineCalcs = true;
                    requireAllocationLine          = true;
                }


                if (model.CalculationType == CalculationType.Baseline || model.CalculationType == CalculationType.Number)
                {
                    if (requireAllocationLine && string.IsNullOrWhiteSpace(model.AllocationLineId))
                    {
                        context.AddFailure("Select an allocation line to create this calculation specification");
                        return;
                    }

                    if (!string.IsNullOrWhiteSpace(model.SpecificationId) && !string.IsNullOrWhiteSpace(model.AllocationLineId))
                    {
                        IEnumerable <FundingStream> fundingStreams = await _specificationsRepository.GetFundingStreams();
                        if (fundingStreams == null)
                        {
                            context.AddFailure("Unable to query funding streams, result returned null");
                            return;
                        }

                        bool foundFundingStream = false;

                        foreach (FundingStream fundingStream in fundingStreams)
                        {
                            foreach (AllocationLine allocationLine in fundingStream.AllocationLines)
                            {
                                if (allocationLine.Id == model.AllocationLineId)
                                {
                                    foundFundingStream = true;
                                    break;
                                }
                            }

                            if (foundFundingStream)
                            {
                                break;
                            }
                        }

                        if (!foundFundingStream)
                        {
                            context.AddFailure("Unable to find Allocation Line with provided ID");
                            return;
                        }

                        if (checkForDuplicateBaselineCalcs)
                        {
                            Specification specification = await _specificationsRepository.GetSpecificationById(model.SpecificationId);
                            if (specification == null)
                            {
                                context.AddFailure("Specification not found");
                                return;
                            }

                            bool existingBaselineSpecification = specification.Current.GetAllCalculations().Any(c => c.CalculationType == CalculationType.Baseline && string.Equals(c.AllocationLine?.Id, model.AllocationLineId, StringComparison.InvariantCultureIgnoreCase) && !string.Equals(model.CalculationId, c.Id, StringComparison.InvariantCultureIgnoreCase));
                            if (existingBaselineSpecification)
                            {
                                context.AddFailure("This specification already has an existing Baseline calculation associated with it. Please choose a different allocation line ID to create a Baseline calculation for.");
                                return;
                            }
                        }
                    }
                }
            });
        }
        public void TestDescriptionFaced()
        {
            var facet = Specification.GetFacet(typeof(IDescribedAsFacet));

            Assert.IsNotNull(facet);
        }
Beispiel #52
0
 private async Task DoUpdateAsync <TTableObject>(DbConnection connection, DbTransaction transaction, UpdateCriteria <TTableObject> updateCriteria, Specification <TTableObject> specification) where TTableObject : class, new()
 {
     try
     {
         var whereClauseBuilder = this.CreateWhereClauseBuilder <TTableObject>();
         var sql = $"UPDATE {GetTableName<TTableObject>()} SET {GetUpdateCriteriaParameterNameList<TTableObject>(whereClauseBuilder, updateCriteria)}";
         WhereClauseBuildResult whereClauseBuildResult = null;
         if (specification != null)
         {
             whereClauseBuildResult = whereClauseBuilder.BuildWhereClause(specification);
             sql = $"{sql} WHERE {whereClauseBuildResult.WhereClause}";
         }
         using (var command = this.CreateCommand(sql, connection))
         {
             if (transaction != null)
             {
                 command.Transaction = transaction;
             }
             command.Parameters.Clear();
             var updateParameters = GetUpdateCriteriaParameterList <TTableObject>(updateCriteria);
             foreach (var parameter in updateParameters)
             {
                 command.Parameters.Add(parameter);
             }
             if (whereClauseBuildResult != null)
             {
                 foreach (var kvp in whereClauseBuildResult.ParameterValues)
                 {
                     var parameter = this.CreateParameter();
                     parameter.ParameterName = kvp.Key;
                     parameter.Value         = kvp.Value;
                     command.Parameters.Add(parameter);
                 }
             }
             await command.ExecuteNonQueryAsync();
         }
     }
     catch (Exception)
     {
         //log.Error("Failed to update.", ex);
     }
 }
Beispiel #53
0
        public static List <IFramingElement> ConfigureAgainstSpecifications(HashSet <IFramingElement> objs, List <Specification> specifications)
        {
            List <IFramingElement> res = new List <IFramingElement>();
            List <string>          valueCondPropName = new List <string>();

            // Only use specifications that are "applied" Zone Specifications.
            var appliedZoneSpecs = specifications.Where(s => s.IsAppliedZoneSpec()).ToList();

            if (appliedZoneSpecs.Count == 0)
            {
                BH.Engine.Reflection.Compute.RecordError($"No Applied Zone Specification found. The input Zone specifications do not have any {nameof(IsInZone)} condition, or do not have their {nameof(IsInZone.ClosedVolumes)} populated.");
                return(new List <IFramingElement>());
            }

            Dictionary <object, List <IFramingElement> > compatibleObjsPerZone = new Dictionary <object, List <IFramingElement> >();

            foreach (var spec in appliedZoneSpecs)
            {
                // Remove any IsInZone condition from the specs.
                // The kit of parts objects are just "archetypes" - not placed in a meaningful location of the model space.
                Specification specCopy = spec.DeepClone();

                specCopy.FilterConditions.RemoveAll(fc => fc is IsInZone);
                specCopy.CheckConditions.RemoveAll(fc => fc is IsInZone);

                // The Part of the Kit (object archetype) must be moved in its final location,
                // so we can make sure that all other conditions can be evaluated on the actual object.
                // e.g. if there are conditions - that are not IsInZone - that are based on position properties.
                var          allClosedVolumes     = spec.FilterConditions.OfType <IsInZone>().SelectMany(c => c.ClosedVolumes);
                List <Point> closedVolumesCentres = allClosedVolumes.Select(cv => cv.IBounds().Centre()).ToList();

                closedVolumesCentres = BH.Engine.Geometry.Compute.CullDuplicates(closedVolumesCentres.ToList());


                foreach (var pt in closedVolumesCentres)
                {
                    foreach (var obj in objs)
                    {
                        compatibleObjsPerZone[pt] = compatibleObjsPerZone.ContainsKey(pt) ? compatibleObjsPerZone[pt] : new List <IFramingElement>();

                        ICurve geom       = obj.Location;
                        var    moveVector = BH.Engine.Geometry.Create.Vector(geom.IBounds().Centre(), pt);

                        var movedGeom = BH.Engine.Geometry.Modify.ITranslate(geom, moveVector);

                        IFramingElement objCopy = obj.DeepClone();
                        objCopy.Location = movedGeom;

                        var specRes = VerifySpecification(new List <object>()
                        {
                            objCopy
                        }, specCopy);
                        if (specRes.PassedObjects.Count != 1)
                        {
                            continue;
                        }

                        valueCondPropName.AddRange(spec.CheckConditions.OfType <IValueCondition>().Select(c => c.PropertyName));

                        compatibleObjsPerZone[pt].Add(objCopy);
                    }
                }
            }

            List <IFramingElement> result = new List <IFramingElement>();

            foreach (var kv in compatibleObjsPerZone)
            {
                var ordered = kv.Value.OrderBy(v => v.ValueFromSource("Property.IAverageProfileArea")).ToList();

                if (ordered.FirstOrDefault() != null)
                {
                    result.Add(ordered.FirstOrDefault());
                }
            }


            return(result);
        }
Beispiel #54
0
 public async Task UpdateAsync <TTableObject>(UpdateCriteria <TTableObject> updateCriteria, Specification <TTableObject> specification) where TTableObject : class, new()
 {
     using (var connection = this.CreateDatabaseConnection())
     {
         await connection.OpenAsync();
         await DoUpdateAsync(connection, null, updateCriteria, specification);
     }
 }
Beispiel #55
0
        /// <summary>
        /// Format a command line argument string from a parsed instance.
        /// </summary>
        /// <typeparam name="T">Type of <paramref name="options"/>.</typeparam>
        /// <param name="parser">Parser instance.</param>
        /// <param name="options">A parsed (or manually correctly constructed instance).</param>
        /// <param name="configuration">The <see cref="Action{UnParserSettings}"/> lambda used to configure
        /// aspects and behaviors of the unparsersing process.</param>
        /// <returns>A string with command line arguments.</returns>
        public static string FormatCommandLine <T>(this Parser parser, T options, Action <UnParserSettings> configuration)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var settings = new UnParserSettings();

            configuration(settings);
            settings.Consumed = true;

            var type    = options.GetType();
            var builder = new StringBuilder();

            type.GetVerbSpecification()
            .MapValueOrDefault(verb => builder.Append(verb.Name).Append(' '), builder);

            var specs =
                (from info in
                 type.GetSpecifications(
                     pi => new
            {
                Specification = Specification.FromProperty(pi),
                Value = pi.GetValue(options, null).NormalizeValue(),
                PropertyValue = pi.GetValue(options, null)
            })
                 where !info.PropertyValue.IsEmpty(info.Specification, settings.SkipDefault)
                 select info)
                .Memoize();

            var allOptSpecs = from info in specs.Where(i => i.Specification.Tag == SpecificationType.Option)
                              let o = (OptionSpecification)info.Specification
                                      where o.TargetType != TargetType.Switch || (o.TargetType == TargetType.Switch && ((bool)info.Value))
                                      where !o.Hidden || settings.ShowHidden
                                      orderby o.UniqueName()
                                      select info;

            var shortSwitches = from info in allOptSpecs
                                let o = (OptionSpecification)info.Specification
                                        where o.TargetType == TargetType.Switch
                                        where o.ShortName.Length > 0
                                        orderby o.UniqueName()
                                        select info;

            var optSpecs = settings.GroupSwitches
                ? allOptSpecs.Where(info => !shortSwitches.Contains(info))
                : allOptSpecs;

            var valSpecs = from info in specs.Where(i => i.Specification.Tag == SpecificationType.Value)
                           let v = (ValueSpecification)info.Specification
                                   orderby v.Index
                                   select info;

            builder = settings.GroupSwitches && shortSwitches.Any()
                ? builder.Append('-').Append(string.Join(string.Empty, shortSwitches.Select(
                                                             info => ((OptionSpecification)info.Specification).ShortName).ToArray())).Append(' ')
                : builder;
            optSpecs.ForEach(
                opt =>
                builder
                .Append(FormatOption((OptionSpecification)opt.Specification, opt.Value, settings))
                .Append(' ')
                );

            builder.AppendWhen(valSpecs.Any() && parser.Settings.EnableDashDash, "-- ");

            valSpecs.ForEach(
                val => builder.Append(FormatValue(val.Specification, val.Value)).Append(' '));

            return(builder
                   .ToString().TrimEnd(' '));
        }
        public void TestElementTypeFacet()
        {
            var facet = (IElementTypeFacet)Specification.GetFacet(typeof(IElementTypeFacet));

            Assert.IsNull(facet);
        }
Beispiel #57
0
 protected static void AssertSharedEntryValue(SharedEntry entry, int expected) =>
 Specification.Assert(entry.Value == expected, "Value is {0} instead of {1}.", entry.Value, expected);
            public void Should_GetLoopProtectionReferencesStackCount_BeNull_BeforeAndAfterEnteringRootScope_When_RootModelReference_IsNull(string id, Specification <TraversingTestCases.TestClassA> rootSpecification, TraversingTestCases.TestClassA model)
            {
                _ = id;

                var modelScheme = ModelSchemeFactory.Create(rootSpecification);

                var context = new IsValidValidationContext(modelScheme, default);

                context.GetLoopProtectionReferencesStackCount().Should().BeNull();

                context.EnterScope(modelScheme.RootSpecificationScopeId, model);

                context.GetLoopProtectionReferencesStackCount().Should().BeNull();
            }
 public void Delete(Specification specification)
 {
     _context.Specifications.Remove(specification);
     _context.SaveChanges();
 }
 public void Add(Specification specification)
 {
     _context.Specifications.Add(specification);
     _context.SaveChanges();
 }