public void RemoveLastEmptyInstance()
        {
            StringBuilder sb = new StringBuilder();

            string expected = "";

            sb.RemoveLast("!");

            Assert.AreEqual(expected, sb.ToString());
        }
        public void RemoveLastExactMatch()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("!");

            string expected = "";

            sb.RemoveLast("!");

            Assert.AreEqual(expected, sb.ToString());
        }
        public void RemoveLast()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Something awesome!!");

            string expected = "Something awesome!";

            sb.RemoveLast("!");

            Assert.AreEqual(expected, sb.ToString());
        }
Example #4
0
 static object Print(object x)
 {
     var ie = x as System.Collections.IEnumerable;
     if (ie != null)
     {
         var sb = new StringBuilder("[");
         foreach (var y in ie) sb.AppendFormat("{0}, ", Print(y));
         return sb.RemoveLast(2).Append("]").ToString();
     }
     return x;
 }
Example #5
0
        private void AddIndexes(List<IndexDefinition> indexes)
        {
            var sb=new StringBuilder();

            indexes.ForEach(idx =>
            {
                sb.Clear();
                sb.Append("create ");
                if (idx.IsUnique) sb.Append("unique ");
                sb.Append("index ");
                sb.Append(idx.Name ?? "ix_" + _data.TableName.DDLUsableString + "_" + StringUtils.CreateRandomString(7));
                sb.Append($" on {_tableName}(");
                idx.Columns.ForEach(n =>
                {
                    sb.Append(n + ",");
                });
                sb.RemoveLast().Append(")");
                sb.AppendLine(";");
                _sb.Append(_provider.FormatIndexOptions(sb.ToString(), idx.Options));
            });
        }
        public void FactMethodName()
        {
            Expression<Func<Test, bool>> data = t => new[] {1, 2}.Contains(t.Id);
            var meth = ObjectExtend.CastAs<MethodCallExpression>(data.Body);
            
            Assert.Equal("Contains",meth.Method.Name);

            var param = ObjectExtend.CastAs<MemberExpression>(meth.Arguments[1]);
            Assert.True(param.BelongsToParameter());
            var sb = new StringBuilder();
            
            sb.Append(param.Member.Name).Append(" in (");
            
            var list = ObjectExtend.CastAs<IEnumerable>(meth.Arguments[0].GetValue());
            var en=list.GetEnumerator();
            while (en.MoveNext())
            {
                sb.Append(en.Current).Append(",");
            }
            sb.RemoveLast();
            sb.Append(")");
            Write(sb.ToString());
        }
Example #7
0
        private void AddConstraints(PKData primaryKey)
        {
            if (primaryKey == null) return;
            var sb=new StringBuilder();

            var name = primaryKey.Name.IsNullOrEmpty()?"pk_" + _data.TableName.DDLUsableString:primaryKey.Name;

            sb.Append($"constraint {name} primary key (");
            primaryKey.Columns.ForEach(c =>
            {
                sb.Append(_provider.EscapeIdentifier(c) + ",");
            });
            sb.RemoveLast();
            sb.AppendLine(")");

            _sb.AppendLine(","+_provider.FormatIndexOptions(sb.ToString(), primaryKey.Options));
        }
Example #8
0
 public string GetColumnsSql(params Expression[] columns)
 {
     var sb=new StringBuilder();
     columns.ForEach(d=>sb.Append($"{_results["col"].Dequeue()},"));
     return sb.RemoveLast().ToString();
 }
Example #9
0
        string BuildArguments(string[] targets)
        {
            var sb = new StringBuilder();
            sb.Append(_projFile);
            sb.AppendFormat(" /m:{0}",_count<=1?1:_count);
            sb.Append(" /v:" + Parse(_verbosity));
            if (Properties != null)
            {
                sb.Append(" /p:");
                foreach (var name in Properties.AllKeys)
                {
                    sb.AppendFormat("{0}={1};", name, Properties[name]);
                }
                sb.RemoveLast();
            }

            if (targets.Length > 0)
            {
                sb.Append(" /t:");
                foreach (var t in targets)
                {
                    sb.Append(t + ";");
                }
                sb.RemoveLast();
            }

            sb.Append(" /clp:ErrorsOnly;PerformanceSummary");
            return sb.ToString();
        }
Example #10
0
 public static void WriteColumnsNames(ICollection<string> columns, StringBuilder builder,
                                      Func<string, string> formatter)
 {
     columns.MustNotBeNull();
     formatter.MustNotBeNull();
     foreach (var column in columns)
     {
         builder.Append(formatter(column.Trim())).Append(",");
     }
     builder.RemoveLast();
 }
Example #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idCda"></param>
        /// <param name="cdaVersion"></param>
        /// <param name="cdaXml"></param>
        /// <param name="otherQueries"></param>
        /// <param name="rootPath"></param>
        /// <param name="queryName"></param>
        /// <param name="queryReturnType"></param>
        /// <param name="entityCodeWithPrefix"></param>
        /// <returns></returns>
        public static async Task<FromXmlTransformationsResult> FromXmlTransformations(
            int idCda,
            int cdaVersion,
            XNode cdaXml,
            string rootPath,
            string queryName,
            IList<XElement> otherQueries = null,
            QueryReturnTypes queryReturnType = QueryReturnTypes.XPathBoolean | QueryReturnTypes.XPathInt | QueryReturnTypes.XQueryFlwrInt,
            bool entityCodeWithPrefix = true
            )
        {
            if (cdaXml == null)
            {
                throw new ArgumentNullException(nameof(cdaXml));
            }

            if (string.IsNullOrWhiteSpace(rootPath))
            {
                throw new ArgumentNullException(nameof(rootPath));
            }

            if (string.IsNullOrWhiteSpace(queryName))
            {
                throw new ArgumentNullException(nameof(queryName));
            }

            Dictionary<QueryReturnTypes, string> queryContainers = new Dictionary<QueryReturnTypes, string>()
            {
                { QueryReturnTypes.XPathBoolean, @"boolean(/" + rootPath + "[{0}])"  },
                { QueryReturnTypes.XPathInt, @"count(/" + rootPath + "[{0}])"  },
                { QueryReturnTypes.XQueryFlwrInt, @"for $x in /" + rootPath + " let $where := ({0}) return if ($where) then 1 else 0"  },
            };

            XDocument QueryTransformations = new XDocument(new XElement("QUERIES"));
            List<Rule> rules = new List<Rule>();
            List<CdaTag> cdaTags = new List<CdaTag>();
            List<QueryReturnTypes> returnTypes = new List<QueryReturnTypes>();
            Condition conditionObj = null;
            Operator operatorObj = null;

            bool tryGet = false;

            XElement conditionsRoot = ((XElement)cdaXml).FirstNode as XElement;
            var cdaBuilderXPath = new StringBuilder();
            var cdaBuilderXQuery = new StringBuilder();
            char openGroupChar = '(';
            char closeGroupChar = ')';

            if (queryReturnType.HasFlag(QueryReturnTypes.XPathBoolean))
                returnTypes.Add(QueryReturnTypes.XPathBoolean);
            if (queryReturnType.HasFlag(QueryReturnTypes.XPathInt))
                returnTypes.Add(QueryReturnTypes.XPathInt);
            if (queryReturnType.HasFlag(QueryReturnTypes.XQueryFlwrInt))
                returnTypes.Add(QueryReturnTypes.XQueryFlwrInt);

            foreach (var group in conditionsRoot.Descendants("GROUP"))
            {
                var conditionSymbol = group.Attribute("CONDITION").Value;

                cdaBuilderXPath.AppendFormat(@"{0}", openGroupChar);
                cdaBuilderXQuery.AppendFormat(@"{0}", openGroupChar);

                foreach (var ruleElement in group.Elements("RULE"))
                {
                    var entityCode = ruleElement.Attribute("ENTITYCODE").Value;
                    var entityType = ruleElement.Attribute("ENTITYTYPE").Value;
                    var operatorSymbol = ruleElement.Attribute("OPERATOR").Value;
                    var value = ruleElement.Attribute("VALUE").Value;

                    Rule rule = new Rule
                    {
                        EntityCode = entityCode,
                        Operator = operatorSymbol,
                        Value = value,
                        EntityType = entityCode.Substring(0, 3),
                        GroupCondition = conditionSymbol
                    };

                    var cdaTag = await CreateCdaTags(rule);

                    rules.Add(rule);
                    cdaTags.Add(cdaTag);

                    if (entityCodeWithPrefix)
                    {
                        entityCode = AddPrefixToEntityCode(rule);
                    }

                    cdaBuilderXPath.AppendFormat(XPathEntityPrefix, entityCode);
                    cdaBuilderXQuery.AppendFormat(XQueryEntityPrefix, entityCode);

                    tryGet = Operators.ListKeyValue.TryGetValue(operatorSymbol.ToLower(), out operatorObj);

                    if (tryGet)
                    {
                        cdaBuilderXPath.AppendFormat(@" {0}", string.Format(operatorObj.XPathValue, value));
                        cdaBuilderXQuery.AppendFormat(@" {0}", string.Format(operatorObj.XPathValue, value));
                    }

                    tryGet = Conditions.ListKeyValue.TryGetValue(conditionSymbol.ToLower(), out conditionObj);

                    if (tryGet)
                    {
                        cdaBuilderXPath.AppendFormat(@" {0} ", conditionObj.Value);
                        cdaBuilderXQuery.AppendFormat(@" {0} ", conditionObj.Value);
                    }
                }

                cdaBuilderXPath.RemoveLast($" {conditionObj.Value} ");
                cdaBuilderXQuery.RemoveLast($" {conditionObj.Value} ");

                cdaBuilderXPath.AppendFormat(@"{0}", closeGroupChar);
                cdaBuilderXQuery.AppendFormat(@"{0}", closeGroupChar);

                tryGet = Conditions.ListKeyValue.TryGetValue(conditionSymbol.ToLower(), out conditionObj);

                if (tryGet)
                {
                    cdaBuilderXPath.AppendFormat(@" {0} ", conditionObj.Value);
                    cdaBuilderXQuery.AppendFormat(@" {0} ", conditionObj.Value);
                }
            }

            cdaBuilderXPath.RemoveLast($" {conditionObj.Value} ");
            cdaBuilderXQuery.RemoveLast($" {conditionObj.Value} ");

            var internalCode = await CreateCdaInternalCode(rules);

            if (otherQueries?.Count > 0)
            {
                QueryTransformations.Element("QUERIES").Add(otherQueries);
            }

            var cdaBuilderXPathEscaped = cdaBuilderXPath.ToString().EscapeString();
            var cdaBuilderXQueryEscaped = cdaBuilderXPath.ToString().EscapeString();

            returnTypes.ForEach(type =>
            {
                var queryElement = new XElement("QUERY", new XAttribute("NAME", queryName));

                switch (type)
                {
                    case QueryReturnTypes.XPathInt:
                        queryElement.Add(
                            new XAttribute("TYPE", "xpath"),
                            new XAttribute("EXPRESSIONTYPE", string.Empty),
                            new XAttribute("RETURNTYPE", "int"),
                            new XAttribute("WHERECLAUSE", string.Format(queryContainers[QueryReturnTypes.XPathInt], cdaBuilderXPathEscaped)),
                            new XAttribute("IDCDA", idCda),
                            new XAttribute("CDAVERSION", cdaVersion)
                            );
                        break;
                    case QueryReturnTypes.XPathBoolean:
                        queryElement.Add(
                            new XAttribute("TYPE", "xpath"),
                            new XAttribute("EXPRESSIONTYPE", string.Empty),
                            new XAttribute("RETURNTYPE", "bool"),
                            new XAttribute("WHERECLAUSE", string.Format(queryContainers[QueryReturnTypes.XPathBoolean], cdaBuilderXPathEscaped)),
                            new XAttribute("IDCDA", idCda),
                            new XAttribute("CDAVERSION", cdaVersion)
                            );
                        break;
                    case QueryReturnTypes.XQueryFlwrInt:
                        queryElement.Add(
                            new XAttribute("TYPE", "xquery"),
                            new XAttribute("EXPRESSIONTYPE", "flwr"),
                            new XAttribute("RETURNTYPE", "int"),
                            new XAttribute("WHERECLAUSE", string.Format(queryContainers[QueryReturnTypes.XQueryFlwrInt], cdaBuilderXQueryEscaped)),
                            new XAttribute("IDCDA", idCda),
                            new XAttribute("CDAVERSION", cdaVersion)
                            );
                        break;
                    default:
                        break;
                }

                QueryTransformations.Root.Add(queryElement);

            });

            FromXmlTransformationsResult result = new FromXmlTransformationsResult()
            {
                QueryTransformations = new QueryTransformation() { ResultValue = QueryTransformations, Success = true },
                TagsTransformation = new TagsTransformation() { ResultValue = cdaTags, Success = true },
                InternalCode = new InternalCode() { ResultValue = internalCode, Success = true }
            };

            return await Task.FromResult(result);
        }
Example #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jsonCda"></param>
        /// <param name="tagTextColumnName"></param>
        /// <param name="entityCodeColumnName"></param>
        /// <returns></returns>
        public static async Task<string> FromJsonToTagsSqlQuery(string jsonCda, string tagTextColumnName, string entityCodeColumnName)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(jsonCda), "jsonCda is null or empty");

            var fakeCdaMasterObj = new CdaMasterDto()
            {
                GlobalId = new Guid(),
                Id = -1,
                Version = 1,
                Name = string.Empty,
                Active = true,
                Cancelled = false,
                Code = string.Empty,
                CreationTime = DateTime.UtcNow,
                UpdatedTime = DateTime.UtcNow,
                Description = string.Empty,
                Domain = string.Empty,
                IdPlantCreator = 1,
                XsdVersion = string.Empty
            };
            XNode cdaXml = await FromJsonToXml(fakeCdaMasterObj, jsonCda);

            XElement conditionsRoot = ((XElement)cdaXml).FirstNode as XElement;
            var queryBuilder = new StringBuilder();
            char openGroupChar = '(';
            char closeGroupChar = ')';
            var conditionSymbol = string.Empty;

            foreach (var group in conditionsRoot.Descendants("GROUP"))
            {
                conditionSymbol = group.Attribute("CONDITION").Value;

                queryBuilder.AppendFormat(@"{0}", openGroupChar);

                foreach (var ruleElement in group.Elements("RULE"))
                {
                    var entityCode = ruleElement.Attribute("ENTITYCODE").Value;
                    var entityType = ruleElement.Attribute("ENTITYTYPE").Value;
                    var operatorSymbol = ruleElement.Attribute("OPERATOR").Value;
                    var value = ruleElement.Attribute("VALUE").Value;

                    if (!string.IsNullOrEmpty(value))
                    {
                        queryBuilder.AppendFormat(@"{0} = ""{1} {2} {3}""", tagTextColumnName, entityCode, operatorSymbol.ToLower(), value);
                    }
                    else
                    {
                        queryBuilder.AppendFormat(@"{0} = ""{1}""", entityCodeColumnName, entityCode);
                    }

                    queryBuilder.AppendFormat(@" {0} ", conditionSymbol);
                }

                queryBuilder.RemoveLast($" {conditionSymbol} ");

                queryBuilder.AppendFormat(@"{0}", closeGroupChar);

                queryBuilder.AppendFormat(@" {0} ", conditionSymbol);
            }

            queryBuilder.RemoveLast($" {conditionSymbol} ");

            return await Task.FromResult(queryBuilder.ToString());
        }