Esempio n. 1
0
        /// <summary>
        /// To insure that a CSV files headers are all unique and simple, propertyesque, names.
        /// </summary>
        /// <param name="someStrings"></param>
        /// <returns></returns>
        public static string[] FormatCsvHeaders(string[] someStrings)
        {
            var newNames    = new List <string>();
            var names2Count = new Dictionary <string, int>();

            foreach (var s in someStrings)
            {
                if (names2Count.ContainsKey(s))
                {
                    names2Count[s] += 1;
                }
                else
                {
                    names2Count.Add(s, 1);
                }
            }

            foreach (var k in names2Count.Keys)
            {
                var repeated = names2Count[k];
                var newName  = NfString.SafeDotNetIdentifier(k);
                if (repeated > 1)
                {
                    for (var i = 0; i < names2Count[k]; i++)
                    {
                        newNames.Add(String.Format("{0}{1:00}", newName, i + 1));
                    }
                }
                else
                {
                    newNames.Add(newName);
                }
            }
            return(newNames.ToArray());
        }
Esempio n. 2
0
        internal static XElement GetSimplePropertyHbmXml(ColumnMetadata entry, string xElementName)
        {
            if (entry == null)
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(xElementName))
            {
                xElementName = Globals.HbmXmlNames.PROPERTY;
            }
            if (string.IsNullOrWhiteSpace(entry.data_type) &&
                Sorting.DbContainers.AllColumns.Data.Any(
                    x => string.Equals(x.column_name, entry.constraint_name, Sorting.C)))
            {
                var acEntry =
                    Sorting.DbContainers.AllColumns.Data.First(
                        x => string.Equals(x.column_name, entry.constraint_name, Sorting.C));
                entry.CopyFrom(acEntry);
            }
            else
            {
                entry.CopyFrom(Sorting.GetFromAllColumnMetadata(entry));
            }

            var simplePropName   = Compose.PropertyName(entry.column_name);
            var simplePropColumn = NfString.ExtractLastWholeWord(entry.column_name, null);

            var simplePropDataType = Globals.HbmXmlNames.ANSI_STRING;

            if (!Util.Lexicon.DotNet2HbmTypes.ContainsKey(string.Format("{0}", entry.data_type)) &&
                !Util.Lexicon.Mssql2HbmTypes.ContainsKey(string.Format("{0}", entry.data_type)))
            {
                Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss.ffff} '{1}' has no matching type in the Lexicon [{2}].",
                                  DateTime.Now,
                                  entry.data_type, entry.ToJsonString());
            }
            else
            {
                simplePropDataType = entry.data_type.StartsWith("System.")
                    ? Util.Lexicon.DotNet2HbmTypes[entry.data_type]
                    : Util.Lexicon.Mssql2HbmTypes[entry.data_type];
            }

            var simplePropLen = simplePropDataType == Globals.HbmXmlNames.ANSI_STRING
                ? entry.string_length == null || entry.string_length <= 0 ? Globals.MSSQL_MAX_VARCHAR : entry.string_length
                : null;

            if (simplePropDataType == typeof(Boolean).Name)
            {
                if (simplePropName.StartsWith(NfString.DefaultNamePrefix))
                {
                    simplePropName = simplePropName.Remove(0, NfString.DefaultNamePrefix.Length);
                }
                simplePropName = "Is" + simplePropName;
            }

            return(XeFactory.PropertyNode(xElementName, simplePropName, simplePropColumn,
                                          simplePropDataType, simplePropLen.ToString(), entry.is_nullable.HasValue && entry.is_nullable == true,
                                          entry.ToJsonString()));
        }
Esempio n. 3
0
        private EfSimpleProp GetSimpleProp(string propName)
        {
            var propColMetadataList = GetColumnDataByPropertyName(propName);

            if (propColMetadataList == null || propColMetadataList.Length <= 0)
            {
                return(null);
            }
            var propColMetadata = propColMetadataList.First();

            var isString = false;

            if (!_efProperties.ContainsKey(propName) && Util.Lexicon.Mssql2HbmTypes.ContainsKey(propColMetadata.data_type))
            {
                isString = Util.Lexicon.Mssql2HbmTypes[propColMetadata.data_type] == "AnsiString";
            }
            else
            {
                isString = _efProperties[propName] == "string";
            }
            var efsprop = new EfSimpleProp {
                IsString = isString
            };

            efsprop.IsUnicode         = efsprop.IsString && propColMetadata.data_type.StartsWith("n");
            efsprop.ColumnName        = NfString.ExtractLastWholeWord(propColMetadata.column_name.Replace("[", string.Empty).Replace("]", string.Empty), null);
            efsprop.RequiresPrecision = Globals.MssqlTypesWithPrecision.Contains(propColMetadata.data_type);
            //this exports doubled when it is unicode
            efsprop.StringLength = GetStringLength(propColMetadata.string_length, efsprop.IsUnicode);
            efsprop.Precision    = propColMetadata.precision;
            efsprop.PropName     = propName;
            return(efsprop);
        }
Esempio n. 4
0
        /// <summary>
        /// Prints the address as it would appear as post marked.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var data = GetData();

            return(NfString.DistillSpaces(string.Join(" ", data.ThoroughfareNumber, data.ThoroughfareDirectional, data.ThoroughfareName,
                                                      data.ThoroughfareType, data.SecondaryUnitDesignator,
                                                      data.SecondaryUnitId).Trim()));
        }
Esempio n. 5
0
 public static string HbmFileName(string someName)
 {
     if (string.IsNullOrWhiteSpace(someName))
     {
         return(null);
     }
     someName = NfString.CapWords(someName, '.');
     return($"{someName}.hbm.xml");
 }
Esempio n. 6
0
        /// <summary>
        /// Gets the universities based on a US State
        /// </summary>
        /// <param name="state">Either the name or the postal code.</param>
        /// <returns></returns>
        public static AmericanUniversity[] GetUniversitiesByState(string state)
        {
            UnivXml = UnivXml ?? Core.XmlDocXrefIdentifier.GetEmbeddedXmlDoc(US_UNIVERSITY_DATA,
                                                                             Assembly.GetExecutingAssembly());
            //this will never pass so avoid the exception
            if (UnivXml == null)
            {
                return new AmericanUniversity[] { }
            }
            ;

            if (String.IsNullOrWhiteSpace(state))
            {
                _allStateAbbreviations = _allStateAbbreviations ?? GetAllXmlStateAbbreviations(UnivXml);

                state = GetRandomStateAbbrev(_allStateAbbreviations);
            }

            var qryBy = "name";

            if (state.Length == 2)
            {
                qryBy = "abbreviation";
            }
            else
            {
                state = string.Join(" ", NfString.DistillToWholeWords(state));
            }

            var elements =
                UnivXml.SelectSingleNode($"//state[@{qryBy}='{state}']");

            if (elements == null || !elements.HasChildNodes)
            {
                return new AmericanUniversity[] { }
            }
            ;

            var tempList = new List <AmericanUniversity>();

            foreach (var elem in elements)
            {
                if (TryParseXml(elem as XmlElement, out var univOut))
                {
                    univOut.StateName = state;
                    tempList.Add(univOut);
                }
            }

            if (tempList.Count == 0)
            {
                return new AmericanUniversity[] { }
            }
            ;

            return(tempList.ToArray());
        }
Esempio n. 7
0
            public AsmDiagramEdge(Tuple <FlattenedItem, FlattenedItem> f)
            {
                _node1Name = NfString.SafeDotNetIdentifier(f.Item1.TypeFullName.Replace(".", "_"), false, 128);
                _node2Name = NfString.SafeDotNetIdentifier(f.Item2.TypeFullName.Replace(".", "_"), false, 128);

                Node1 = f.Item1.TypeFullName;
                Node2 = f.Item2.TypeFullName;

                IsEnumerable = f.Item2.IsEnumerable;
            }
Esempio n. 8
0
        public static string ManyToOnePropertyName(string fullAssemblyQualTypeName, string[] fkColumnNames)
        {
            var fkPropertyType = new NfTypeName(fullAssemblyQualTypeName);

            var fkPropertyName = fkPropertyType.ClassName;

            fkColumnNames = fkColumnNames.Select(x => NfString.CapWords(NfString.ExtractLastWholeWord(x, '.'), null)).ToArray();
            return(string.Format("{0}By{1}", fkPropertyName,
                                 string.Join("And", fkColumnNames)));
        }
Esempio n. 9
0
        public override string GetRandomDriversLicense()
        {
            var dlVal    = base.GetRandomDriversLicense();
            var chkDigit = NfString.CalcLuhnCheckDigit(dlVal);
            var dlOut    = new StringBuilder();

            dlOut.Append(dlVal);
            dlOut.Append(chkDigit.ToString());
            return(dlOut.ToString());
        }
Esempio n. 10
0
        public TextCanvas ComposeArrow(Rule ruler, TextCanvas tc)
        {
            if (ruler == null)
            {
                throw new NoRuleSetException();
            }
            var arrowIdx = ruler.CalcEntryIndex(this);

            Width = tc.Width;

            //find the line on the text canvas
            var ti = tc.Items.FirstOrDefault(t => t.Index == arrowIdx.Item1);

            if (ti == null)
            {
                return(tc);
            }

            //scope in on the ranges for the located line
            TextRange fromTr;

            TryGetTextRange(ti.Ranges, FromBlock.Id, out fromTr);
            TextRange toTr;

            TryGetTextRange(ti.Ranges, ToBlock.Id, out toTr);

            if (fromTr == null || toTr == null)
            {
                return(tc);
            }
            var isOuterBlock = !string.IsNullOrWhiteSpace(tc.Id);

            System.Console.WriteLine(
                $"({(isOuterBlock ? "Outer Block" : "InnerBlock")}) {fromTr.Id} -> {toTr.Id}");

            var arrowText      = new StringBuilder();
            var arrowDirection = DetermineArrowDirection(fromTr.Id, toTr.Id, ti.Ranges);

            switch (arrowDirection)
            {
            case PrintLocation.Left:
                arrowText = GetLeftArrowStrBldr(fromTr, toTr, ti);
                break;

            case PrintLocation.Right:
                arrowText = GetRightArrowStrBldr(fromTr, toTr, ti);
                break;
            }

            tc.Items.First(t => t.Index == arrowIdx.Item1).Text =
                NfString.MergeString(arrowText.ToString(),
                                     new string(tc.Items.First(t => t.Index == arrowIdx.Item1).Text.ToArray())).ToCharArray().ToList();

            return(tc);
        }
Esempio n. 11
0
        /// <summary>
        /// Utility method to apply word-wrap to a text document.
        /// </summary>
        /// <param name="fileFullName"></param>
        /// <param name="lineLength"></param>
        public static void ToWordWrap(string fileFullName, int?lineLength = 80)
        {
            if (String.IsNullOrWhiteSpace(fileFullName) || !File.Exists(fileFullName))
            {
                return;
            }
            var content   = File.ReadAllText(fileFullName);
            var wwContent = NfString.ToWordWrap(content, lineLength);

            File.WriteAllText(fileFullName, wwContent);
        }
Esempio n. 12
0
 public static XElement IdNode(string name)
 {
     if (String.IsNullOrWhiteSpace(name))
     {
         name = String.Format("{0}__{1}", Globals.HbmXmlNames.ID, NfString.GetNfRandomName());
     }
     return(new XElement(Globals.HbmXmlNames.ID.ToLower(),
                         new XAttribute(Globals.HbmXmlNames.NAME, name),
                         new XAttribute(Globals.HbmXmlNames.TYPE, "Guid"),
                         new XAttribute(Globals.HbmXmlNames.GENERATOR, "guid")));
 }
Esempio n. 13
0
        protected internal virtual string DrawHeader()
        {
            var label      = NfString.PrintInCenter(Title, Width);
            var bar        = DrawBar();
            var strBuilder = new StringBuilder();

            for (var i = 0; i < Width; i++)
            {
                var headerChar = label[i] == (char)0x20 ? bar[i] : label[i];
                strBuilder.Append(headerChar);
            }
            strBuilder.AppendLine();
            return(strBuilder.ToStringUnixNewline());
        }
Esempio n. 14
0
        /// <summary>
        /// End-of-line conversion with specific encoding.
        /// </summary>
        /// <param name="somePath"></param>
        /// <param name="encoder"></param>
        public static void ConvertToCrLf(string somePath, Encoding encoder)
        {
            if (String.IsNullOrWhiteSpace(somePath))
            {
                return;
            }
            if (!File.Exists(somePath))
            {
                return;
            }

            var fileContent = File.ReadAllText(somePath);

            fileContent = NfString.ConvertToCrLf(fileContent);

            File.WriteAllText(somePath, fileContent, encoder);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates and XDocument in which child elements map to token-pair matches.
        /// </summary>
        /// <param name="inputString">The string upon which the XDocument frame will be derived.</param>
        /// <returns></returns>
        /// <remarks>
        /// Given a string arguement (or a path to a text file) the function will
        /// produce an XDocument where the nesting of child nodes represents
        /// the internal context of a matching pair of tokens.  Therefore the output
        /// will contian nodes and those nodes may contain furthere child nodes and
        /// so on down to an internal size that is at least the defined minimum token
        /// span.
        ///
        /// The string input will have all its concurrent occurances of spaces and
        /// tabs reduced to a single space.
        ///
        /// The result is simply a frame and does not contain any of the original string.
        /// </remarks>
        public XElement GetXDocFrame(string inputString)
        {
            if (string.IsNullOrWhiteSpace(inputString))
            {
                throw new ItsDeadJim("The input string arg is empty.");
            }

            inputString = NfString.DistillCrLf(inputString);
            inputString = NfString.DistillTabs(inputString);

            var tokens = GetTokens(inputString);
            var gaps   = GetGaps(tokens);
            var xDoc   = FrameTokensXDoc(tokens);

            xDoc = FrameGapsXDoc(xDoc, gaps);

            return(xDoc);
        }
Esempio n. 16
0
        /// <summary>
        /// Applies the results of Get-XDocFrame to the original content.
        /// </summary>
        /// <param name="xDoc"></param>
        /// <param name="inputString"></param>
        /// <remarks>
        /// Returns the XDocument with the inter-string spans applied as text data
        /// of each of the XDocument frame nodes.
        ///
        /// The input is again distilled of all concurrent occurances of tab and space
        /// characters.
        /// </remarks>
        public void ApplyXDocFrame(XElement xDoc, string inputString)
        {
            if (string.IsNullOrWhiteSpace(inputString))
            {
                throw new ItsDeadJim("The input string arg is empty.");
            }

            if (xDoc == null)
            {
                throw new ItsDeadJim("a XElement must be supplied, call GetXDocFrame prior to calling this member");
            }

            //crit - the indices must match the original so process like frame f(x) did
            inputString = NfString.DistillCrLf(inputString);
            inputString = NfString.DistillTabs(inputString);

            XDocIter(xDoc, inputString);
        }
Esempio n. 17
0
        protected internal string DrawHeader()
        {
            if (_width - 2 <= 0)
            {
                return(Name);
            }

            var title      = NfString.PrintInCenter(Name, (_width - 2));
            var strBuilder = new StringBuilder();

            if (_rulerWidth > 0)
            {
                strBuilder.Append(new string((char)0x20, _rulerWidth));
            }
            strBuilder.Append(Config.GraphChars.Bar);
            strBuilder.Append(title);
            strBuilder.Append(Config.GraphChars.Bar);
            return(strBuilder.ToStringUnixNewline());
        }
Esempio n. 18
0
        /// <summary>
        /// Gets a type&apos;s name less the namespace
        /// </summary>
        /// <param name="simplePropType"></param>
        /// <returns></returns>
        public static string GetTypeNameWithoutNamespace(string simplePropType)
        {
            if (String.IsNullOrWhiteSpace(simplePropType))
            {
                return(null);
            }

            if (!simplePropType.Contains(NfSettings.DefaultTypeSeparator))
            {
                return(simplePropType);
            }

            if (simplePropType.Contains(Constants.TYPE_METHOD_NAME_SPLIT_ON))
            {
                simplePropType = simplePropType.Substring(0,
                                                          simplePropType.IndexOf(Constants.TYPE_METHOD_NAME_SPLIT_ON, StringComparison.Ordinal));
            }

            return(NfString.ExtractLastWholeWord(simplePropType, NfSettings.DefaultTypeSeparator));
        }
Esempio n. 19
0
            public override string ToString()
            {
                if (_nsNodes == null || _nsNodes.Count <= 0)
                {
                    return(string.Empty);
                }
                var graphViz = new StringBuilder();

                graphViz.Append($"subgraph cluster_{NfString.SafeDotNetIdentifier(_ns)}");
                graphViz.AppendLine("{");
                graphViz.AppendLine("\tlabel=\"\";");
                graphViz.AppendLine("\tcolor=red;");
                foreach (var item in _nsNodes)
                {
                    graphViz.AppendLine($"\t{item}");
                }
                graphViz.AppendLine("}");

                return(graphViz.ToString());
            }
Esempio n. 20
0
        internal static void GetSimpleId(ColumnMetadata pkId, XElement classXe)
        {
            pkId.CopyFrom(Sorting.GetFromAllColumnMetadata(pkId));
            var fullColumnName = pkId.column_name;

            Compose.ValidSplit(fullColumnName, 3);
            var          columnName   = NfString.ExtractLastWholeWord(fullColumnName, null);
            const string propertyName = Globals.HbmXmlNames.ID;
            var          type         = Util.Lexicon.Mssql2HbmTypes[(pkId.data_type)];
            var          length       = pkId.string_length ?? Globals.MSSQL_MAX_VARCHAR;
            XElement     idXe;

            //don't let the '-1' from the database make it to the hbm.xml's
            if (string.Equals(type, Globals.HbmXmlNames.ANSI_STRING))
            {
                if (length <= 0)
                {
                    length = Globals.MSSQL_MAX_VARCHAR;
                }
                idXe = XeFactory.IdNode(propertyName, columnName, type,
                                        length.ToString(CultureInfo.InvariantCulture), pkId.ToJsonString());
            }
            else
            {
                idXe = XeFactory.IdNode(propertyName, columnName, type, pkId.ToJsonString());
            }

            //simple split of assigned or is_identity
            XElement generatorXe;

            if (pkId.is_auto_increment.HasValue && pkId.is_auto_increment.Value)
            {
                generatorXe = XeFactory.GeneratorId(Globals.HbmXmlNames.IDENTITY);
            }
            else
            {
                generatorXe = XeFactory.GeneratorId(Globals.HbmXmlNames.ASSIGNED);
            }
            idXe.Add(generatorXe);
            classXe.Add(idXe);
        }
Esempio n. 21
0
        public string GetDotNetPropertyName()
        {
            if (string.IsNullOrWhiteSpace(ParamName))
            {
                return(null);
            }
            var cName = ParamName.StartsWith("@") ? ParamName.Substring(1, ParamName.Length - 1) : ParamName;

            cName = NfString.SafeDotNetIdentifier(cName);
            cName = NfString.CapWords(cName, null);
            if (GetSqlDataType() == SqlDbType.Bit && !cName.StartsWith("Is"))
            {
                cName = string.Format("Is{0}", cName);
            }
            if (cName.EndsWith("ID"))
            {
                cName = string.Format("{0}Id", cName.Substring(0, cName.Length - 2));
            }

            return(cName);
        }
Esempio n. 22
0
        public override bool ValidDriversLicense(string dlnumber)
        {
            if (string.IsNullOrWhiteSpace(dlnumber))
            {
                return(false);
            }
            //all but last digit
            var dlVal = dlnumber.Substring(0, dlnumber.Length - 1);

            var dlLastChar = dlnumber.Substring(dlnumber.Length - 1, 1);
            var dlChkDigit = 0;

            if (!int.TryParse(dlLastChar, out dlChkDigit))
            {
                return(false);
            }

            var calcChkDigit = NfString.CalcLuhnCheckDigit(dlVal);

            return(base.ValidDriversLicense(dlVal) && dlChkDigit == calcChkDigit);
        }
Esempio n. 23
0
        public Ef35PropertyAttr(ColumnMetadata md, bool addUpdateCheckNever)
        {
            Name          = NfString.ExtractLastWholeWord(md.column_name, Shared.Core.NfSettings.DefaultTypeSeparator);
            _composedName = Compose.PropertyName(md.column_name);
            DbType        = md.data_type.ToUpper();

            if (Lexicon.Mssql2HbmTypes.ContainsKey(md.data_type) && Lexicon.Mssql2HbmTypes[md.data_type] == "AnsiString")
            {
                if (md.string_length != null && md.string_length < 0)
                {
                    DbType = string.Format("{0}(MAX)", DbType);
                }
                else
                {
                    DbType = string.Format("{0}({1})", DbType, md.string_length);
                }
            }
            if (Globals.MssqlTypesWithPrecision.Contains(md.data_type))
            {
                DbType = string.Format("{0}({1})", DbType, md.precision);
            }

            if (md.is_nullable != null && md.is_nullable.Value == false)
            {
                DbType    = string.Format("{0} NOT NULL", DbType);
                CanBeNull = false;
            }
            else
            {
                CanBeNull = true;
            }

            if (md.is_auto_increment != null && md.is_auto_increment.Value)
            {
                DbType        = string.Format("{0} IDENTITY", DbType);
                IsPrimaryKey  = true;
                IsDbGenerated = true;
            }
            IsUpdateCheckNever = addUpdateCheckNever;
        }
Esempio n. 24
0
        public static string ClassName(string name, string outputNamespace)
        {
            var asmQualifiedName = new StringBuilder();

            if (name.Split(Shared.Core.NfSettings.DefaultTypeSeparator).Length > 1)
            {
                var nameParts       = name.Split(Shared.Core.NfSettings.DefaultTypeSeparator);
                var actualClassName = nameParts[(nameParts.Length - 1)].Replace(" ", Globals.REPLACE_SPACE_WITH_SEQUENCE);
                nameParts[(nameParts.Length - 1)] = NfString.SafeDotNetTypeName(actualClassName);
                name = string.Join(Shared.Core.NfSettings.DefaultTypeSeparator.ToString(CultureInfo.InvariantCulture), nameParts);
            }

            //remove any chars not allowed in C# ids
            name = NfString.SafeDotNetTypeName(name);

            //capitalize first letter of whole word to avoid conflict with C# reserved words
            name = NfString.CapWords(name, Shared.Core.NfSettings.DefaultTypeSeparator);

            if (!String.IsNullOrWhiteSpace(outputNamespace))
            {
                outputNamespace = NfString.CapWords(outputNamespace, Shared.Core.NfSettings.DefaultTypeSeparator);
                asmQualifiedName.AppendFormat("{0}{1}", outputNamespace, Shared.Core.NfSettings.DefaultTypeSeparator);
            }

            asmQualifiedName.Append(name);

            if (!String.IsNullOrWhiteSpace(outputNamespace))
            {
                asmQualifiedName.AppendFormat(", {0}", NfReflect.DraftCscExeAsmName(outputNamespace));
            }

            var typeName = new NfTypeName(asmQualifiedName.ToString());

            if (!String.IsNullOrWhiteSpace(outputNamespace))
            {
                return(typeName.AssemblyQualifiedName);
            }

            return(typeName.FullName);
        }
Esempio n. 25
0
        public static TextCanvas Merge(this TextCanvas entry1Tc, TextCanvas entry2Tc, Rule ruler)
        {
            //check for null args
            if (ruler == null || entry2Tc == null)
            {
                throw new DrawingException("A merge requires a source, a candidate and a ruler");
            }

            //validate args have something to work with
            if (entry1Tc.IsEmptyItems() && entry2Tc.IsEmptyItems())
            {
                return(new TextCanvas());
            }

            if (entry2Tc.IsEmptyItems() && !entry1Tc.IsEmptyItems())
            {
                return(entry1Tc);
            }

            if (entry1Tc.IsEmptyItems() && !entry2Tc.IsEmptyItems())
            {
                return(entry2Tc);
            }


            //determine total edges for the whole
            var entriesMin = entry1Tc.MinIndex < entry2Tc.MinIndex ? entry1Tc.MinIndex : entry2Tc.MinIndex;
            var entriesMax = entry1Tc.MaxIndex > entry2Tc.MaxIndex ? entry1Tc.MaxIndex : entry2Tc.MaxIndex;

            Func <TextItem, bool> tti = ti1 => ti1 != null && !ti1.IsEmptyText();

            var textCanvas = new TextCanvas
            {
                Ruler    = ruler,
                Items    = new List <TextItem>(),
                MaxIndex = entriesMax,
                MinIndex = entriesMin,
                Width    = entry1Tc.Width > entry2Tc.Width ? entry1Tc.Width : entry2Tc.Width
            };

            for (var i = entriesMin; i <= entriesMax; i++)
            {
                var entry1i = entry1Tc.Items.FirstOrDefault(item => item.Index == i);
                var entry2i = entry2Tc.Items.FirstOrDefault(item => item.Index == i);

                if (entry1i == null && entry2i == null)
                {
                    continue;
                }

                //merge line
                if (tti(entry1i) && tti(entry2i))
                {
                    var newEntry = entry1i.Copy();
                    newEntry.Ranges.AddRange(entry2i.Ranges);
                    newEntry.Text =
                        NfString.MergeString(new string(entry1i.Text.ToArray()), new string(entry2i.Text.ToArray()))
                        .ToCharArray().Where(c => Convert.ToInt32(c) >= 0x20)
                        .ToList();
                    textCanvas.Items.Add(newEntry);

                    continue;
                }

                if (tti(entry1i))
                {
                    textCanvas.Items.Add(entry1i.Copy());
                    continue;
                }
                textCanvas.Items.Add(entry2i.Copy());
            }
            return(textCanvas);
        }
Esempio n. 26
0
        public AsmDiagram(Assembly asm, bool withNamespaceSubGraphs = false)
        {
            if (asm == null)
            {
                throw new ArgumentNullException(nameof(asm));
            }

            _targetedNs = asm.GetName().Name;

            _withNsSubgraphs = withNamespaceSubGraphs;
            _asmName         = NfString.SafeDotNetIdentifier(asm.GetName().Name);
            foreach (
                var asmType in
                asm.NfGetExportedTypes()
                .Where(x => !string.IsNullOrWhiteSpace(x.Namespace) &&
                       AssemblyName.ReferenceMatchesDefinition(asm.GetName(), x.Assembly.GetName())))
            {
                var item1 = new FlattenedItem(asmType)
                {
                    FlName = asmType.Name
                };
                if (item1.IsTerminalNode || NfReflect.IsEnumType(asmType))
                {
                    continue;
                }

                foreach (
                    var p in
                    asmType.NfGetProperties(NfSettings.DefaultFlags, false)
                    .Where(
                        x => x != null &&
                        !string.IsNullOrWhiteSpace(x.NfPropertyType(false)?.Namespace) &&
                        AssemblyName.ReferenceMatchesDefinition(x.NfPropertyType(false)?.Assembly.GetName(), asm.GetName()))
                    )
                {
                    if (NfReflect.IsEnumType(p.PropertyType))
                    {
                        continue;
                    }
                    var item2 = new FlattenedItem(p.PropertyType)
                    {
                        FlName = p.Name
                    };
                    if (item2.IsTerminalNode)
                    {
                        continue;
                    }
                    var tupleOfItems = new Tuple <FlattenedItem, FlattenedItem>(item1, item2);
                    var itemEv       = new AsmDiagramEdge(tupleOfItems);
                    if (Edges.Any(x => x.AreSame(itemEv)))
                    {
                        continue;
                    }
                    Edges.Add(itemEv);
                }
            }

            Edges = RemoveDuplicates(Edges);

            var names   = Edges.SelectMany(x => x.NodeName).ToList();
            var uqNames = names.Distinct().OrderBy(x => x).ToList();

            _nodes = uqNames.Select(x => new AsmDiagramNode(x, GetCountOfEdgesOn(x))).ToList();

            if (_withNsSubgraphs)
            {
                var uqNamespaces = _nodes.Select(x => x.NodeNamespace).Distinct().ToList();
                foreach (var ns in uqNamespaces)
                {
                    _nsSubGraphs.Add(new AsmDiagramSubGraph(ns, _nodes));
                }
            }
        }
Esempio n. 27
0
        public override string ToString()
        {
            if (string.IsNullOrEmpty(Text))
            {
                return(string.Empty);
            }
            if (Width == 0)
            {
                _width = Config.Numerics.DefaultWidth;
            }
            if (_height == 0)
            {
                _height = CalcHeight();
            }

            Func <int, string> sfOpL = i => "{0,-" + i + "}";
            Func <int, string> sfOpR = i => "{0," + i + "}";

            var strBuilder = new StringBuilder();

            switch (Location)
            {
            case PrintLocation.Center:
                strBuilder.AppendLine(NfString.PrintInCenter(Text, Width));
                break;

            case PrintLocation.Left:
                strBuilder.AppendLine(string.Format(sfOpL(Width), Text));
                break;

            case PrintLocation.Right:
                strBuilder.AppendLine(string.Format(sfOpR(Width), Text.Trim()));
                break;
            }

            if (_height <= 1)
            {
                return(strBuilder.ToStringUnixNewline());
            }

            for (var i = 0; i < _height - 1; i++)
            {
                switch (Location)
                {
                case PrintLocation.Center:
                    strBuilder.AppendLine(NfString.PrintInCenter(Config.GraphChars.LifeLine.ToString(), Width));
                    break;

                case PrintLocation.Left:
                    strBuilder.AppendLine(string.Format(sfOpL(Width), Config.GraphChars.LifeLine));
                    break;

                case PrintLocation.Right:
                    strBuilder.AppendLine(string.Format(sfOpR(Width), Config.GraphChars.LifeLine));
                    break;
                }
            }
            switch (Location)
            {
            case PrintLocation.Center:
                strBuilder.AppendLine(NfString.PrintInCenter(new string(Config.GraphChars.Rail, 3), Width));
                break;

            case PrintLocation.Left:
                strBuilder.AppendLine(string.Format(sfOpL(Width), new string(Config.GraphChars.Rail, 3)));
                break;

            case PrintLocation.Right:
                strBuilder.AppendLine(string.Format(sfOpR(Width), new string(Config.GraphChars.Rail, 3)));
                break;
            }
            return(strBuilder.ToStringUnixNewline());
        }
Esempio n. 28
0
        /// <summary>
        /// Produces a single hbm.xml for the given <see cref="tbl"/>
        /// </summary>
        /// <param name="outputNamespace"></param>
        /// <param name="tbl"></param>
        /// <returns>The path the generated hbm.xml file</returns>
        public static string GetSingleHbmXml(string outputNamespace, string tbl)
        {
            if (HbmKeys == null || HbmOneToMany == null || HbmBags == null)
            {
                throw new RahRowRagee("Assign the static variables HbmKeys, HbmOneToMany and HbmBags" +
                                      " then try again (These values are calculated from Sorting).");
            }
            if (Settings.DoNotReference.Contains(tbl))
            {
                return(null);
            }

            var hbmPk   = HbmKeys.Data;
            var hbmFk   = HbmOneToMany.Data;
            var hbmBags = HbmBags.Data;

            //possiable duplicate names handled within this
            var className = Compose.ClassName(tbl, outputNamespace);

            //not having the naming pattern is exceptional
            Compose.ValidSplit(tbl, 2);

            var tableName  = NfString.ExtractLastWholeWord(tbl, null);
            var schemaName = tbl.Replace(string.Format(".{0}", tableName), string.Empty);

            var xe = XeFactory.HibernateMappingNode();

            var classXe = XeFactory.ClassNode(className, tableName, schemaName);

            var hasNoPkAtAll = GetPk(outputNamespace, tbl, hbmPk, classXe);

            //having no pk, add the contrived comp-key to the class
            if (hasNoPkAtAll)
            {
                GetAllColumnsAsCompositeKey(tbl, classXe, outputNamespace);
            }
            else//simple properties
            {
                foreach (var columnName in Sorting.DbContainers.FlatData.Data.Where(x => string.Equals(x.table_name, tbl, Sorting.C)))
                {
                    var fullColumnName = columnName.column_name;
                    Compose.ValidSplit(fullColumnName, 3);
                    var simplePropXe = GetSimplePropertyHbmXml(columnName, Globals.HbmXmlNames.PROPERTY);
                    classXe.Add(simplePropXe);
                }
            }

            GetFksWhichAreNotPartOfPks(outputNamespace, tbl, hbmFk, classXe);

            GetBags(outputNamespace, tbl, hbmBags, hasNoPkAtAll, className, classXe);

            xe.Add(classXe);

            var hbmXmlOutputPath = Path.Combine(Settings.HbmDirectory,
                                                Compose.HbmFileName(tbl));
            var xmlContent = xe.ToString()
                             .Replace("<hibernate-mapping>", "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\">");

            File.WriteAllText(hbmXmlOutputPath, xmlContent);

            //perform rename of any properties which match classname or are duplicated therein
            CorrectHbmXmlDuplicateNames(hbmXmlOutputPath);
            return(hbmXmlOutputPath);
        }
Esempio n. 29
0
        /// <summary>
        /// Produces a single hbm.xml with the sql-query node in tow.
        /// </summary>
        /// <param name="outputNamespace"></param>
        /// <param name="storedProc"></param>
        /// <returns>The path to the generated hbm.xml file.</returns>
        public static string GetHbmNamedQueryXml(string outputNamespace, string storedProc)
        {
            if (Sorting.AllStoredProcNames == null || Sorting.AllStoredProcNames.Count <= 0)
            {
                throw new RahRowRagee("There doesn't appear to be any stored procs here.");
            }

            if (Settings.DoNotReference.Contains(storedProc) || !Sorting.AllStoredProx.ContainsKey(storedProc))
            {
                return(null);
            }

            var sp = Sorting.AllStoredProx[storedProc];

            if (sp == null)
            {
                return(null);
            }

            var returnedData = sp.ReturnedData;

            if (returnedData == null || returnedData.Count <= 0)
            {
                return(null);
            }

            if (returnedData.Keys.Count <= 0)
            {
                Settings.WriteToStoredProcLog(string.Format("Stored proc named '{0}' has an empty dataset", sp.ProcName));
                if (!Sorting.EmptyDatasetProx.Contains(sp.ProcName))
                {
                    Sorting.EmptyDatasetProx.Add(sp.ProcName);
                }
                return(null);
            }

            //both the return types and the callable sql-query are wrapped in this root node
            var xe = XeFactory.HibernateMappingNode();

            if (returnedData.Count > 1)
            {
                Settings.WriteToStoredProcLog(string.Format("Stored Proc named '{0}' returns a multi-table dataset", storedProc));
                if (!Sorting.MultiTableDsProx.Contains(storedProc))
                {
                    Sorting.MultiTableDsProx.Add(storedProc);
                }
            }

            //possiable duplicate names handled within this
            var className = Compose.ClassName(string.Format("{0}.{1}{2}", Globals.STORED_PROX_FOLDER_NAME, storedProc, "Table"), outputNamespace);

            var classXe = XeFactory.ClassNode(className, null, null);

            classXe.Add(XeFactory.IdNode(null));

            var sqlQryName = NfString.SafeDotNetIdentifier(storedProc);
            var returnsXe  = XeFactory.ReturnNode(sqlQryName, className);

            foreach (var cMeta in returnedData[returnedData.Keys.First()])
            {
                var simplePropName     = Compose.PropertyName(cMeta.column_name, true);
                var simplePropColumn   = NfString.ExtractLastWholeWord(cMeta.column_name, null);
                var simplePropDataType = Util.Lexicon.DotNet2HbmTypes[cMeta.data_type];

                classXe.Add(XeFactory.PropertyNode(Globals.HbmXmlNames.PROPERTY, simplePropName, null, simplePropDataType,
                                                   (cMeta.data_type == "System.String"
                        ? Globals.MSSQL_MAX_VARCHAR.ToString(CultureInfo.InvariantCulture)
                        : null), cMeta.is_nullable.HasValue && cMeta.is_nullable == true, string.Empty));

                returnsXe.Add(XeFactory.ReturnPropertyNode(simplePropColumn, simplePropName));
            }

            var sqlQryXe = XeFactory.SqlQueryNode(sqlQryName);

            sqlQryXe.Add(returnsXe);

            sqlQryXe.Add(new XCData(sp.ToHbmSql()));

            xe.Add(classXe);
            xe.Add(sqlQryXe);

            var hbmXmlOutputPath = Path.Combine(Settings.HbmStoredProcsDirectory,
                                                Compose.HbmFileName(storedProc.Replace(" ", Globals.REPLACE_SPACE_WITH_SEQUENCE)));
            var xmlContent = xe.ToString()
                             .Replace("<hibernate-mapping>", "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\">");

            File.WriteAllText(hbmXmlOutputPath, xmlContent);
            CorrectHbmXmlDuplicateNames(hbmXmlOutputPath, true);
            return(hbmXmlOutputPath);
        }
Esempio n. 30
0
 public static string PropertyName(string name, bool replaceInvalidsWithHexEsc = false)
 {
     name = NfString.ExtractLastWholeWord(name, Shared.Core.NfSettings.DefaultTypeSeparator);
     name = NfString.CapWords(name, null);
     return(NfString.SafeDotNetIdentifier(name, replaceInvalidsWithHexEsc));
 }