Exemple #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Wildcard"/> class.
        /// </summary>
        /// <param name="supported">The supported <see cref="WildcardSelection"/>.</param>
        /// <param name="multiWildcard">The .NET multi (zero or more) wildcard character (defaults to <see cref="MultiWildcardCharacter"/>).</param>
        /// <param name="singleWildcard">The .NET single wildcard character (defaults to <see cref="char.MinValue"/>).</param>
        /// <param name="charactersNotAllowed">The list of characters that are not allowed.</param>
        /// <param name="transform">The <see cref="StringTransform"/> option for the wildcard text.</param>
        /// <param name="spaceTreatment">The <see cref="WildcardSpaceTreatment"/> that defines the treatment of embedded space ' ' characters within the wildcard.</param>
        public Wildcard(WildcardSelection supported, char multiWildcard = MultiWildcardCharacter, char singleWildcard            = char.MinValue, char[]?charactersNotAllowed = null,
                        WildcardSpaceTreatment spaceTreatment           = WildcardSpaceTreatment.None, StringTransform transform = StringTransform.EmptyToNull)
        {
            if (supported == WildcardSelection.Undetermined || supported.HasFlag(WildcardSelection.InvalidCharacter))
            {
                throw new ArgumentException("A Wildcard cannot be configured with Undetermined and/or InvalidCharacter supported selection(s).", nameof(supported));
            }

            if (multiWildcard != char.MinValue && singleWildcard != char.MinValue && multiWildcard == singleWildcard)
            {
                throw new ArgumentException("A Wildcard cannot be configured with the same character for the MultiWildcard and SingleWildcard.", nameof(multiWildcard));
            }

            if (charactersNotAllowed != null && (charactersNotAllowed.Contains(multiWildcard) || charactersNotAllowed.Contains(singleWildcard)))
            {
                throw new ArgumentException("A Wildcard cannot be configured with either the MultiWildcard or SingleWildcard in the CharactersNotAllowed list.", nameof(charactersNotAllowed));
            }

            if (supported.HasFlag(WildcardSelection.MultiWildcard) && multiWildcard == char.MinValue)
            {
                throw new ArgumentException("A Wildcard that supports MultiWildcard must also define the MultiWildcard character.");
            }

            if (supported.HasFlag(WildcardSelection.SingleWildcard) && singleWildcard == char.MinValue)
            {
                throw new ArgumentException("A Wildcard that supports SingleWildcard must also define the SingleWildcard character.");
            }

            Supported            = supported;
            MultiWildcard        = multiWildcard;
            SingleWildcard       = singleWildcard;
            CharactersNotAllowed = new ReadOnlyCollection <char>(charactersNotAllowed != null ? (char[])charactersNotAllowed.Clone() : Array.Empty <char>());
            SpaceTreatment       = spaceTreatment;
            Transform            = transform;
        }
 /// <summary>
 /// Initializes a new instance of <see cref="SymmetricEncryptionConfiguration"/> with default settings consisting of:
 /// <see cref="SymmetricAlgorithmType.Aes"/> encryption using <see cref="System.Security.Cryptography.CipherMode.CBC"/> and <see cref="System.Security.Cryptography.PaddingMode.PKCS7"/>.
 /// Plaintext strings are encoded using a UTF8 transform.
 /// All other strings (ciphertext, key, and IV strings) are encoded using a hex transform.
 /// </summary>
 public SymmetricEncryptionConfiguration()
 {
     AlgorithmType       = SymmetricAlgorithmType.Aes;
     CipherMode          = CipherMode.CBC;
     PaddingMode         = PaddingMode.PKCS7;
     PlainTextTransform  = StringTransform.FromEncoding(Encoding.UTF8);
     CipherTextTransform = StringTransform.GetHexTransform();
     KeyTransform        = StringTransform.GetHexTransform();
     IvTransform         = StringTransform.GetHexTransform();
 }
Exemple #3
0
            protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
            {
                JsonProperty property = base.CreateProperty(member, memberSerialization);

                property.Ignored         = IgnoredDataTypes.Any(p => p == property.PropertyType);
                property.ShouldSerialize = instance => !property.Ignored;

                if (PRETTY_NAMES)
                {
                    property.PropertyName = StringTransform.PrettyMsSqlIdent(property.PropertyName);
                }

                return(property);
            }
Exemple #4
0
            protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
            {
                JsonProperty property = base.CreateProperty(member, memberSerialization);

                property.ShouldSerialize = instance =>
                                           property.PropertyType != typeof(string) &&
                                           (!property.PropertyType.IsValueType || property.PropertyName == "Id");
                property.Ignored = false;
                if (PRETTY_NAMES)
                {
                    property.PropertyName = StringTransform.PrettyMsSqlIdent(property.PropertyName);
                }

                return(property);
            }
 private SymmetricEncryptionService CreateEncryptionService2()
 {
     return(new SymmetricEncryptionService(
                new SymmetricEncryptionConfiguration
     {
         AlgorithmType = GetAlgorithmType(),
         CipherMode = GetCipherMode(),
         PaddingMode = GetPaddingMode(),
         PlainTextTransform = cboPlainTextStringTransformType.SelectedValue as IStringTransform,
         CipherTextTransform = cboCipherTextStringTransformType.SelectedValue as IStringTransform,
         IvTransform = chkIvIsHex.Checked ? StringTransform.GetHexTransform() : StringTransform.FromEncoding(Encoding.Default),
         KeyTransform = chkKeyIsHex.Checked ? StringTransform.GetHexTransform() : StringTransform.FromEncoding(Encoding.Default)
     }
                ));
 }
Exemple #6
0
        public void NoEncryptionTest()
        {
            var encryption = new SymmetricEncryptionService(
                new SymmetricEncryptionConfiguration
            {
                AlgorithmType       = SymmetricAlgorithmType.None,
                PlainTextTransform  = StringTransform.FromEncoding(Encoding.UTF8),
                CipherTextTransform = StringTransform.FromEncoding(Encoding.UTF8)
            }
                );

            const string inputString  = InputStringTest;
            var          outputString = encryption.EncryptString(inputString, (string)null, null);

            Assert.AreEqual(inputString, outputString, "Encrypted string was not equal to the input string.");
        }
Exemple #7
0
        public void NoEncryptionTransformTest()
        {
            var encryption = new SymmetricEncryptionService(
                new SymmetricEncryptionConfiguration
            {
                AlgorithmType       = SymmetricAlgorithmType.None,
                PlainTextTransform  = StringTransform.FromEncoding(Encoding.UTF8),
                CipherTextTransform = StringTransform.GetBase64Transform()
            }
                );

            const string inputString      = InputStringTest;
            var          encryptionOutput = encryption.EncryptString(inputString, (string)null, null);
            var          base64String     = Convert.ToBase64String(Encoding.UTF8.GetBytes(inputString));

            Assert.AreEqual(base64String, encryptionOutput, "Encrypted string was not equal to the base64 hash of the input string.");
        }
Exemple #8
0
        public StringBuilder DecryptAllPasswords(StringBuilder stringBuilder)
        {
            Dictionary <string, StringTransform> replacements = new Dictionary <string, StringTransform>
            {
                {
                    "Source", new StringTransform
                    {
                        SearchRegex       = new Regex(@"<Source ID=""[a-fA-F0-9\-]+"" .*ConnectionString=""([^""]+)"" .*>"),
                        GroupNumbers      = new[] { 1 },
                        TransformFunction = DpapiWrapper.DecryptIfEncrypted
                    }
                },
                {
                    "DsfAbstractFileActivity", new StringTransform
                    {
                        SearchRegex       = new Regex(@"&lt;([a-zA-Z0-9]+:)?(DsfFileWrite|DsfFileRead|DsfFolderRead|DsfPathCopy|DsfPathCreate|DsfPathDelete|DsfPathMove|DsfPathRename|DsfZip|DsfUnzip) .*?Password=""([^""]+)"" .*?&gt;"),
                        GroupNumbers      = new[] { 3 },
                        TransformFunction = DpapiWrapper.DecryptIfEncrypted
                    }
                },
                {
                    "DsfAbstractMultipleFilesActivity", new StringTransform
                    {
                        SearchRegex       = new Regex(@"&lt;([a-zA-Z0-9]+:)?(DsfPathCopy|DsfPathMove|DsfPathRename|DsfZip|DsfUnzip) .*?DestinationPassword=""([^""]+)"" .*?&gt;"),
                        GroupNumbers      = new[] { 3 },
                        TransformFunction = DpapiWrapper.DecryptIfEncrypted
                    }
                },
                {
                    "Zip", new StringTransform
                    {
                        SearchRegex       = new Regex(@"&lt;([a-zA-Z0-9]+:)?(DsfZip|DsfUnzip) .*?ArchivePassword=""([^""]+)"" .*?&gt;"),
                        GroupNumbers      = new[] { 3 },
                        TransformFunction = DpapiWrapper.DecryptIfEncrypted
                    }
                }
            };
            string        xml    = stringBuilder.ToString();
            StringBuilder output = new StringBuilder();

            xml = StringTransform.TransformAllMatches(xml, replacements.Values.ToList());
            output.Append(xml);
            return(output);
        }
Exemple #9
0
        public static Expression CreateStringCompare(this Expression leftExpression, StringTransform stringTransform, StringComparison stringComparison, Expression rightExpression)
        {
            var stringType            = typeof(string);
            var stringTransformMethod = stringType.GetMethod(stringTransform.ToString(), Type.EmptyTypes);

            var leftParam = leftExpression == null
                                ? stringTransform == StringTransform.None
                                        ? (Expression)Expression.Parameter(stringType)
                                        : Expression.Call(
                Expression.Parameter(stringType),
                stringTransformMethod)
                                : stringTransform == StringTransform.None
                                        ? leftExpression
                                        : Expression.Call(
                leftExpression,
                stringTransformMethod);

            var rightParam = stringTransform == StringTransform.None ? rightExpression : Expression.Call(rightExpression, stringTransformMethod);

            var stringCompareMethod = stringType.GetMethod(stringComparison.ToString(), new[] { stringType });

            return(Expression.Call(leftParam, stringCompareMethod, rightParam));
        }
        public MainForm()
        {
            InitializeComponent();

            cboPlainTextStringTransformType.Items.Clear();
            cboCipherTextStringTransformType.Items.Clear();

            // List of supported transforms
            var stringTransformTypes = new[]
            {
                new StringTransformComboBoxItem("Default Encoding", StringTransform.FromEncoding(Encoding.Default)),
                new StringTransformComboBoxItem("Base64", StringTransform.GetBase64Transform()),
                new StringTransformComboBoxItem("Hex", StringTransform.GetHexTransform())
            };

            // Each combo box gets its own copy of the transform list
            cboPlainTextStringTransformType.DataSource  = new List <StringTransformComboBoxItem>(stringTransformTypes);
            cboCipherTextStringTransformType.DataSource = new List <StringTransformComboBoxItem>(stringTransformTypes);

            // Make sure we always select our first item
            cboPlainTextStringTransformType.SelectedIndex  = 0;
            cboCipherTextStringTransformType.SelectedIndex = 0;
        }
Exemple #11
0
        /// <summary>
        ///     takes the standard Xsd.exe /classes command example.cs output & customizes it to be a baseDoc for this solution
        /// </summary>
        /// <param name="DocTypeName"></param>
        /// <param name="cSharpCode"></param>
        /// <param name="PrimaryTypeParentType">default is typeof(BaseDoc)</param>
        /// <param name="PrimaryTypeAppliedInterfaces">default is IDocIdentifiers, if DocTypeName is DocRev IDocRev also</param>
        /// <param name="SecondaryTypeParentType">default is typeof(BaseAutoIdent)</param>
        /// <param name="SecondaryTypesAppliedInterfaces">nothing is applied when null</param>
        /// <returns></returns>
        public static string CustomizeXsdToCSharpOutput(
            string DocTypeName,
            string cSharpCode,
            Type PrimaryTypeParentType               = null,
            string[] PrimaryTypeAppliedInterfaces    = null,
            Type SecondaryTypeParentType             = null,
            string[] SecondaryTypesAppliedInterfaces = null)
        {
            #region Apply_Defaults

            /*
             * BANDAID: DocRev
             * (search for this though out the code for more on DocRev snafus in general),
             * class inheritance should code customization should not be performed like this. This is specifically to cater toward IDocRev and nothing more.
             */
            if (PrimaryTypeParentType == null)
            {
                PrimaryTypeParentType = typeof(BaseDoc);
            }

            if (PrimaryTypeAppliedInterfaces == null || PrimaryTypeAppliedInterfaces.Length == 0)
            {
                PrimaryTypeAppliedInterfaces = new[] { nameof(IDocIdentifiers) }
            }
            ;

            string ApplyToPrimaryClass = string.Format("{0}", string.Join(", ", new[] {
                PrimaryTypeParentType.Name
            }.Union(PrimaryTypeAppliedInterfaces)));

            if (SecondaryTypeParentType == null)
            {
                SecondaryTypeParentType = typeof(BaseAutoIdent);
            }

            if (SecondaryTypesAppliedInterfaces == null || SecondaryTypesAppliedInterfaces.Length == 0)
            {
                SecondaryTypesAppliedInterfaces = new string[]
                { }
            }
            ;

            string ApplyToSecondayClasses = string.Format("{0}", string.Join(", ", new[] {
                SecondaryTypeParentType.Name
            }.Union(SecondaryTypesAppliedInterfaces)));

            #endregion Apply_Defaults

            List <string> IgnoreDataTypePropertiesMapped = new List <string> {
                "byte",
                "System.Xml.XmlElement",
                "System.Xml.XmlElement"
            };
            List <string> IgnorePropertyPrefixes = new List <string> {
                "field", "calc", "tmp", "signatures1", "signatures2"
            };

            // add a Nullable variable type for each of the IgnoreDataTypePropertiesMapped defined
            foreach (string type in IgnoreDataTypePropertiesMapped.ToArray())
            {
                IgnoreDataTypePropertiesMapped.Add(string.Format("System.Nullable<{0}>", type));
                IgnoreDataTypePropertiesMapped.Add(string.Format("System.Nullable<{0}>[]", type));
                IgnoreDataTypePropertiesMapped.Add(string.Format("{0}[]", type));
            }

            // convert aliases specifically for byte arrays as the DocRev interface will be looking for byte[]; not Byte90
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"Byte\[\]",
                @"byte[]");

            // apply DataMember attributes to properties in an attempt to make them more readable to developer
            // effects of these attributes do not cross over to InfoPath's primary serializer (XmlSerializer)
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"([\n\r\s]+)(public)(\s+[^\s]+\s+)(\w+)([\n\r\s]+)(\{)([\n\r\s]+)(get)([\n\r\s]+)(\{)",
                match => string.Format(
                    "{0}[DataMember(Name = \"{1}\", EmitDefaultValue = false)]{2}",
                    match.Groups[1].Value,                                    /* 0 */
                    StringTransform.PrettyCSharpIdent(match.Groups[4].Value), /* 1 */
                    match.Value),                                             /* 3 */
                RegexOptions.IgnoreCase);

            // Stripe out legacy soap 1.2 "bool specified" properties
            // Ref: http://weblog.west-wind.com/posts/2007/Dec/13/Generated-Date-Types-in-WCF-and-unexpected-dateSpecified-fields
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"((\[.*\])\s+)+public bool \w+Specified\s+\{(\s+(get|set)\s+\{\s+.*\s+\})+\s+\}\s*",
                string.Empty,
                RegexOptions.IgnoreCase);

            cSharpCode = Regex.Replace(
                cSharpCode,
                @"\s+private\s+bool \w+FieldSpecified;",
                string.Empty,
                RegexOptions.IgnoreCase);

            // TODO: Apply against class types found that are not a form type, this will force ignore for anything InfoPath Designer that is not a simple datatype
            /* Strip out XMLSerialization attributes & Signatures### properties as they seem to screw up some IIS WCF hosted services because there data type of XmlElement is not serializable */
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"private.*anyAttrField;.*",
                string.Empty,
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            cSharpCode = Regex.Replace(
                cSharpCode,
                @"\[System\.Xml\.Serialization\.XmlAnyAttributeAttribute\(\)\]",
                string.Empty,
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            cSharpCode = Regex.Replace(
                cSharpCode,
                @"\[System\.Xml\.Serialization\.XmlAnyAttributeAttribute\(\)\](\s+\[[^]\n\r]+\])*([^}]+\}){3,3}", "",
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            cSharpCode = Regex.Replace(
                cSharpCode,
                @".*EmitDefaultValue\s*=\s*false\s*\)\]\s*public\s+System\.Xml\.XmlAttribute\[\]\s+AnyAttr\s*{\s*get\s*{\s*return\s*this\.anyAttrField;\s*}\s*set\s*{\s*this\.anyAttrField\s*=\s*value;\s*}\s*}",
                string.Empty,
                RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

            string[] DocTypeNames =
            {
                DocTypeName
            };

            // Make sure encapsulated private properties are excluded as DataMembers
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"([ ]+)(private\s+[^\s]+\s+\w+;)",
                "\r\n$1[IgnoreDataMember]\r\n$1$2");

            // add class attributes: DataContract for WCF
            // make classes inheritors of BaseDoc (the class representing the root object for the doc) or BaseAutoIdent (a supporting child class usually spawned for repeating elements in the main document)
            cSharpCode = Regex.Replace(
                cSharpCode,
                /**1******2***********************************************3*****************4*************5*******6***************************************7*********/
                @"(\s+\[)(System\.Xml\.Serialization\.XmlRootAttribute\(|System\.Xml\.Serialization\.XmlTypeAttribute\()(\""[\w]+\"",\s+)?(Namespace="")([^""]*)([^\]]+\]\s+public\s+partial\s+class\s+)([\w_\d]+)",
                match => string.Format(
                    "{1}DataContract(Name = \"{3}\", Namespace = \"{2}\")]{0} : {4}",
                    /*the entire match undivided*/
                    match.Value,
                    /*left square bracket with leading white-spaces*/
                    match.Groups[1].Value,
                    /*xml namespace URI*/
                    match.Groups[5].Value,

                    /*
                     * Title-casing with underscore separate words
                     * are applied to generate a prettier SQL SSMS Object Explorer node-set
                     * & WCF Client proxy API that Visual Studio generates for
                     * external applications that will consume our service.
                     * With exception to the main/root document objects/pocos,
                     * this is applied to all classes.
                     */
                    DocTypeName == match.Groups[7].Value
                        ? match.Groups[7].Value
                        : DocTypeName + "_" + StringTransform.PrettyCSharpIdent(
                        string.IsNullOrWhiteSpace(match.Groups[3].Value)
                                  ? match.Groups[7].Value
                                  : match.Groups[3].Value.Trim(',', ' ', '"')),
                    DocTypeName == match.Groups[7].Value
                        ? ApplyToPrimaryClass
                        : ApplyToSecondayClasses),
                RegexOptions.IgnoreCase);

            /* add a parameter-less constructor to each class specifically to support XmlSerialization operations anticipated to run against the objects compiled from the code this is generating */
            //TODO:combine this RegEx replacement logic with the one directly above (the one that is decorating class attributes */
            cSharpCode = Regex.Replace(
                cSharpCode,
                @"(?<LeadingWhitespace>\s+)(?<ClassModifiers>public\s+partial\s+class\s+)(?<ClassName>[\w_\d]+)(?<InheritanceAndOpenClassBodyCurlyBrace>[\w_\d \{:,]+)",
                match => string.Format(
                    "{0}\n{1}public {2}() {{}}",
                    match.Value,
                    match.Groups["LeadingWhitespace"].Value,
                    match.Groups["ClassName"].Value),
                RegexOptions.IgnoreCase);

            // convert array properties to generic List
            cSharpCode = Regex.Replace(
                cSharpCode,
                /**1****2***************3****4***********5*****6****7*****/
                @"(\s+)(public|private)(\s+)([\.<>\w_]+)(\[\])(\s+)([^\s]+)",
                match => string.Format(
                    (IgnoreDataTypePropertiesMapped.Any(
                         m => m == match.Groups[4].Value || Regex.IsMatch(match.Groups[4].Value, @"signatures\d+"))
                         ? "{0}"
                         : "{1}{2}{3}List<{4}>{6}{7}"),
                    match.Value,
                    match.Groups[1].Value,
                    match.Groups[2].Value,
                    match.Groups[3].Value,
                    match.Groups[4].Value,
                    match.Groups[5].Value,
                    match.Groups[6].Value,
                    match.Groups[7].Value),
                RegexOptions.IgnoreCase);

            // ensure XmlElement types are ignore (mainly by binary serializer)
            cSharpCode = cSharpCode.Replace("private System.Xml.XmlElement[]", "[System.NonSerialized] private System.Xml.XmlElement[]");

            // add using statements to beginning to top of the document
            cSharpCode = string.Format("{0}{1}",
                                       string
                                       .Join("",
                                             USING_NAMESPACES
                                             .Keys
                                             .OrderBy(ns => ns)
                                             .Select(ns => string.Format("using {0};\n", ns))), cSharpCode);

            return(cSharpCode);
        }
Exemple #12
0
        /// <summary>
        /// Sets a <see cref="String"/> property value and raises the <see cref="PropertyChanged"/> event where applicable.
        /// </summary>
        /// <param name="propertyValue">The property value to set.</param>
        /// <param name="setValue">The value to set.</param>
        /// <param name="immutable">Indicates whether the value is immutable; can not be changed once set.</param>
        /// <param name="trim">The <see cref="StringTrim"/> (defaults to <see cref="StringTrim.End"/>).</param>
        /// <param name="transform">The <see cref="StringTransform"/> (defaults to <see cref="StringTransform.EmptyToNull"/>).</param>
        /// <param name="beforeChange">Function to invoke before changing the value; a result of <c>true</c> indicates that the property change is to be cancelled; otherwise, <c>false</c>.</param>
        /// <param name="propertyNames">The names of the properties that changed.</param>
        /// <returns><c>true</c> indicates that the property value changed; otherwise, <c>false</c>.</returns>
        /// <remarks>The first property name specified (see <paramref name="propertyNames"/>) is the primary property; therefore, the only property
        /// where the <see cref="BeforePropertyChanged"/> event is raised. The additional property names allow for the <see cref="PropertyChanged"/>
        /// event to be raised for other properties where related versus having to raise seperately.</remarks>
        protected bool SetValue(ref string propertyValue, string setValue, bool immutable = false, StringTrim trim = StringTrim.End, StringTransform transform = StringTransform.EmptyToNull, Func <string, bool> beforeChange = null, params string[] propertyNames)
        {
            ValidateSetValuePropertyNames(propertyNames);

            lock (_lock)
            {
                string val       = Cleaner.Clean(setValue, trim, transform);
                var    isChanged = val != propertyValue;
                if (!RaisePropertyChangedWhenSame && !isChanged)
                {
                    return(false);
                }

                if (IsReadOnly && isChanged)
                {
                    throw new InvalidOperationException(EntityIsReadOnlyMessage);
                }

                if (immutable && isChanged && propertyValue != null)
                {
                    throw new InvalidOperationException(ValueIsImmutableMessage);
                }

                if (beforeChange != null)
                {
                    if (beforeChange.Invoke(setValue))
                    {
                        return(false);
                    }
                }

                if (OnBeforePropertyChanged(propertyNames[0], setValue))
                {
                    return(false);
                }

                propertyValue = val;
                TriggerPropertyChanged(propertyNames);

                return(true);
            }
        }
Exemple #13
0
 /// <summary>
 /// Sets a <see cref="String"/> property value and raises the <see cref="PropertyChanged"/> event where applicable.
 /// </summary>
 /// <param name="propertyValue">The property value to set.</param>
 /// <param name="setValue">The value to set.</param>
 /// <param name="immutable">Indicates whether the value is immutable; can not be changed once set.</param>
 /// <param name="trim">The <see cref="StringTrim"/> (defaults to <see cref="StringTrim.End"/>).</param>
 /// <param name="transform">The <see cref="StringTransform"/> (defaults to <see cref="StringTransform.EmptyToNull"/>).</param>
 /// <param name="propertyNames">The names of the properties that changed.</param>
 /// <returns><c>true</c> indicates that the property value changed; otherwise, <c>false</c>.</returns>
 /// <remarks>The first property name specified (see <paramref name="propertyNames"/>) is the primary property; therefore, the only property
 /// where the <see cref="BeforePropertyChanged"/> event is raised. The additional property names allow for the <see cref="PropertyChanged"/>
 /// event to be raised for other properties where related versus having to raise seperately.</remarks>
 protected bool SetValue(ref string propertyValue, string setValue, bool immutable = false, StringTrim trim = StringTrim.End, StringTransform transform = StringTransform.EmptyToNull, params string[] propertyNames)
 {
     return(SetValue(ref propertyValue, setValue, immutable, trim, transform, null, propertyNames));
 }
Exemple #14
0
 public void CorrectLoginTest()
 {
     LoginService.LogIn(_correctLoginName, _correctLoginPass);
     AssertService.AssetEqual(LoginService.GetLoginName(), StringTransform.FirstUpper(_correctLoginName));
 }
Exemple #15
0
        /// <summary>
        ///     Creates a namespace (each DocType, DocRev & it's children reside in a dedicated namespace) that is suitable for
        ///     parsing then reversing to it's original string representations. The transformations to and from DocTypeName/DocRev
        ///     & C# namespace is a lossless operation. The inverse of this method is TryParseDocTypeAndRev. Segments for the
        ///     DocType's actual name are prefixed with "doc", for the DocRev: "rev". Example:
        ///     docMyName200.rev1.rev0.rev56.HERE.ARE.SOME.ADDITIONAL.NS_PARTS
        /// </summary>
        /// <param name="DocTypeName"></param>
        /// <param name="DocRev"></param>
        /// <param name="AdditionalRootNames"></param>
        /// <returns>DotTypeName as the root name & DocRev as the second level name if nothing specified in AdditionalRootNames</returns>
        public static string CalcCSharpNamespace(string DocTypeName, string DocRev, params string[] AdditionalRootNames)
        {
            Validate(DocTypeName, DocRev, AdditionalRootNames);

            string[] DocTypeNameParts = DocTypeName.Split('.').Select(s => String.Format("{0}{1}", DOCTYPENAME_NS_PREFIX, s.ToUpper())).ToArray();
            string[] RevParts         = DocRev.Split('.').Select(s => String.Format("{0}{1}", DOCREV_NS_PREFIX, s)).ToArray();
            string[] OtherParts       = AdditionalRootNames == null
                                      ? new string[]
            { }
                                      : AdditionalRootNames.Where(s => !String.IsNullOrWhiteSpace(s)).Select(s => String.Format("{0}{1}", ADDITIONAL_NS_PREFIX, StringTransform.SafeIdentifier(s ?? "_"))).ToArray();

            return(String.Join(".", DocTypeNameParts.Concat(RevParts).Concat(OtherParts)));
        }
Exemple #16
0
        /// <summary>
        /// Cleans a <see cref="String"/> and optionally allows <see cref="String.Empty"/>.
        /// </summary>
        /// <param name="value">The value to clean.</param>
        /// <param name="trim">The <see cref="StringTrim"/> (defaults to <see cref="DefaultStringTrim"/>).</param>
        /// <param name="transform">The <see cref="StringTransform"/> (defaults to <see cref="DefaultStringTransform"/>).</param>
        /// <returns>The cleaned value.</returns>
        public static string?Clean(string?value, StringTrim trim = DefaultStringTrim, StringTransform transform = DefaultStringTransform)
        {
            // Handle a null string.
            if (value == null)
            {
                if (transform == StringTransform.NullToEmpty)
                {
                    return(string.Empty);
                }
                else
                {
                    return(value);
                }
            }

            var tmp = trim switch
            {
                StringTrim.Both => value.Trim(),
                StringTrim.Start => value.TrimStart(),
                StringTrim.End => value.TrimEnd(),
                _ => value,
            };

            // Transform the string.
            return(transform switch
            {
                StringTransform.EmptyToNull => (tmp.Length == 0) ? null : tmp,
                StringTransform.NullToEmpty => tmp ?? string.Empty,
                _ => tmp,
            });
Exemple #17
0
        /// <summary>
        ///     PropertyType(s) are merged when there DeclaringType(s) have the same names & the properties between those
        ///     DeclaringType(s) match also. This will yield a class that given any of the sourceTypes serialized with json; can be
        ///     de-serialized with a class defining the properties return.
        /// </summary>
        /// <param name="nameSpace"></param>
        /// <param name="sourceTypes"></param>
        /// <param name="propertyNameExclutions"></param>
        /// <param name="BaseType"></param>
        /// <param name="prettyNames"></param>
        /// <param name="ClassProperties"></param>
        /// <returns></returns>
        private ClassProperty[] ConsolidatePropertyNames(string nameSpace, Type[] sourceTypes = null, string[] propertyNameExclutions = null, Type BaseType = null, bool prettyNames = true, ClassProperty[] ClassProperties = null)
        {
            if (ClassProperties == null)
            {
                ClassProperties = new ClassProperty[] { }
            }
            ;

            if (propertyNameExclutions == null)
            {
                propertyNameExclutions = new string[] { }
            }
            ;

            if (sourceTypes == null)
            {
                sourceTypes = new Type[] { }
            }
            ;
            else
            {
                if (BaseType == null)
                {
                    BaseType = DefaultBaseType(sourceTypes);
                }

                if (BaseType != null)
                {
                    propertyNameExclutions =
                        BaseType
                        .GetProperties()
                        .Select(p => p.Name)
                        .Union(propertyNameExclutions)
                        .ToArray();
                }
            }

            Dictionary <string, Type> dic = new Dictionary <string, Type>();

            // do simple value/quazi-value type properties first
            foreach (var _ClassProperty in
                     FilterInvalidProperties(sourceTypes, propertyNameExclutions, prettyNames)
                     .Select(p => new ClassProperty(p.Name, p.PropertyType))
                     .Union(ClassProperties))
            {
                string propName = prettyNames
                                      ? StringTransform.PrettyMsSqlIdent(_ClassProperty.Name)
                                      : _ClassProperty.Name;

                if (_ClassProperty.PropertyType.hasConvert())
                {
                    // handle normal numeric, byte, string & datetime types
                    Type typeA = _ClassProperty.PropertyType;
                    Type typeB = dic.ContainsKey(propName)
                                     ? dic[propName]
                                     : _ClassProperty.PropertyType;
                    Type typeC = ImplicitTypeConversionExtension.TypeLcd(typeA.GetPrincipleType(), typeB.GetPrincipleType());

                    // there are many situations that will yield a nullable
                    if (Nullable.GetUnderlyingType(typeA) != null || Nullable.GetUnderlyingType(typeB) != null)
                    {
                        dic[propName] = typeof(Nullable <>).MakeGenericType(typeC);
                    }
                    else if (typeC.IsNullable() && sourceTypes.Count() > 0 && FilterInvalidProperties(sourceTypes, propertyNameExclutions, prettyNames).Count() != sourceTypes.Count())
                    {
                        dic[propName] = typeof(Nullable <>).MakeGenericType(typeC);
                    }
                    else
                    {
                        dic[propName] = typeC;
                    }
                }
                else if (dic.ContainsKey(propName) && dic[propName].hasConvert() != _ClassProperty.PropertyType.hasConvert())
                {
                    throw new Exception(string.Format("Property {0} is defined as both a primitive value data type & complex reference type amount properties defined in parent types {1}; automatic union of these property types can't be performed.", propName, string.Join(", ", sourceTypes.Select(t => t.FullName).ToArray())));
                }
                else if (dic.ContainsKey(propName) && dic[propName].isEnumeratedType() != _ClassProperty.PropertyType.isEnumeratedType())
                {
                    throw new Exception(string.Format("Property {0} is defined as both a Enumerable & Non-Enumerable properties defined in parent types {1}; automatic union of these property types can't be performed.", propName, string.Join(", ", sourceTypes.Select(t => t.FullName).ToArray())));
                }
                else if (_ClassProperty.PropertyType == typeof(byte[]) || _ClassProperty.PropertyType == typeof(string))
                {
                    dic[propName] = _ClassProperty.PropertyType;
                }
                else if (!dic.ContainsKey(propName))
                {
                    //TODO:stop recursive compiling off child objects as the names are the only thing we are looking for, not the types. far to many needless compiles are occurring when calling upon UnionOnName
                    ClassProperty[] dstTypes = FilterInvalidProperties(sourceTypes, propertyNameExclutions, prettyNames, new[] { _ClassProperty.Name }, ClassProperties);

                    if (dstTypes.Length > 0)
                    {
                        Type _UnionOnNameType = MergeOnPropertyNames(
                            nameSpace,
                            dstTypes.Select(prop => prop.PropertyType.GetPrincipleType()).ToArray(),
                            null,
                            propertyNameExclutions.Union(
                                dstTypes
                                .Where(prop => !sourceTypes.Select(t => t.Name).Contains(prop.PropertyType.Name))
                                .Select(prop => prop.Name)
                                ).ToArray(),
                            prettyNames);

                        // properties that are collections will yield as generic lists only
                        dic[propName] =
                            _ClassProperty.PropertyType.GetEnumeratedType() != null &&
                            _ClassProperty.PropertyType != typeof(string)
                                ? typeof(List <>).MakeGenericType(_UnionOnNameType)
                                : _UnionOnNameType;
                    }
                }
            }

            return(dic.Select(m => new ClassProperty(m.Key, m.Value)).ToArray());
        }
 public string EncryptDsfFileWritePasswords(string xml)
 {
     return(StringTransform.TransformAllMatches(xml, new List <StringTransform> {
         _replacements["DsfAbstractFileActivity"]
     }));
 }
 public string EncryptSourceConnectionStrings(string xml)
 {
     return(StringTransform.TransformAllMatches(xml, new List <StringTransform> {
         _replacements["Source"]
     }));
 }
Exemple #20
0
        public static int Main(string[] args)
        {
            var app = new CommandLineApplication
            {
                Name        = "ConsoleApp",
                Description = "An required assignment",
            };

            app.HelpOption(inherited: true);

            //Number 1
            /*------------------------------------------------------------------------*/
            app.Command("uppercase", setCmd =>
            {
                var word = setCmd.Argument("key", "Name of the config").IsRequired();
                setCmd.OnExecute(() =>
                {
                    Console.WriteLine(StringTransform.Uppercase(word.Value));
                });
            });

            app.Command("lowercase", setCmd =>
            {
                setCmd.Description = "Set config value";
                var word           = setCmd.Argument("key", "Name of the config").IsRequired();
                setCmd.OnExecute(() =>
                {
                    Console.WriteLine(StringTransform.Lowercase(word.Value));
                });
            });

            app.Command("capitalize", setCmd =>
            {
                setCmd.Description = "Set config value";
                var word           = setCmd.Argument("key", "Name of the config").IsRequired();
                setCmd.OnExecute(() =>
                {
                    Console.WriteLine(StringTransform.Capitalize(word.Value));
                });
            });

            //Number 2
            /*------------------------------------------------------------------------*/


            app.Command("add", cmd =>
            {
                var files = cmd.Argument("numbers", "numbers to count", multipleValues: true);
                cmd.OnExecute(() =>
                {
                    var result = Arithmetic.DoArithmetic(files.Values, "add");

                    Console.WriteLine(result);
                });
            });

            app.Command("substract", cmd =>
            {
                var files = cmd.Argument("numbers", "numbers to count", multipleValues: true);
                cmd.OnExecute(() =>
                {
                    var result = Arithmetic.DoArithmetic(files.Values, "substract");

                    Console.WriteLine(result);
                });
            });

            app.Command("multiply", cmd =>
            {
                var files = cmd.Argument("numbers", "numbers to count", multipleValues: true);
                cmd.OnExecute(() =>
                {
                    var result = Arithmetic.DoArithmetic(files.Values, "multiply");

                    Console.WriteLine(result);
                });
            });

            app.Command("divide", cmd =>
            {
                var files = cmd.Argument("numbers", "numbers to count", multipleValues: true);
                cmd.OnExecute(() =>
                {
                    var result = Arithmetic.DoArithmetic(files.Values, "divide");

                    Console.WriteLine(result);
                });
            });

            //Number 3
            /*------------------------------------------------------------------------*/

            app.Command("palindrome", setCmd =>
            {
                setCmd.Description = "Set c onfig value";
                var word           = setCmd.Argument("key", "Name of the config").IsRequired();
                setCmd.OnExecute(() =>
                {
                    var result = Palindrome.IsPalindrome(word.Value);
                    if (result == true)
                    {
                        Console.WriteLine("Is Palindrome? Yes");
                    }
                    else
                    {
                        Console.WriteLine("Is Palindrome? No");
                    }
                });
            });

            //Number 4
            /*------------------------------------------------------------------------*/

            app.Command("obfuscator", setCmd =>
            {
                setCmd.Description = "Set c onfig value";
                var word           = setCmd.Argument("key", "Name of the config").IsRequired();
                setCmd.OnExecute(() =>
                {
                    Console.WriteLine(Obfuscator.Obfuscate(word.Value));
                });
            });

            app.OnExecute(() =>
            {
                Console.WriteLine("Specify a subcommand");
                app.ShowHelp();
                return(1);
            });

            //Number 5
            /*------------------------------------------------------------------------*/


            app.Command("random", cmd =>
            {
                var length                = cmd.Option("--length", "setting random length", CommandOptionType.SingleOrNoValue);
                var letters               = cmd.Option("--letters", "setting letters availability", CommandOptionType.SingleOrNoValue);
                var numbers               = cmd.Option("--numbers", "setting numbers availability", CommandOptionType.SingleOrNoValue);
                var lowercase             = cmd.Option("--lowercase", "setting lowercase", CommandOptionType.NoValue);
                RandomGenerator generator = new RandomGenerator();
                cmd.OnExecute(() =>
                {
                    int num = Convert.ToInt32(length.Value());
                    string result;
                    if (!length.HasValue())
                    {
                        num = 32;
                    }

                    if (!letters.HasValue() || numbers.HasValue())
                    {
                        result = generator.GenerateNum(num);
                    }
                    else if (letters.HasValue() || !numbers.HasValue())
                    {
                        result = generator.GenerateLet(num);
                    }
                    else
                    {
                        result = generator.GenerateAll(num);
                    }

                    if (lowercase.HasValue())
                    {
                        result = result.ToLower();
                    }

                    Console.WriteLine(result);
                });
            });

            //Number 6
            /*------------------------------------------------------------------------*/

            app.Command("ip", cmd =>
            {
                cmd.OnExecute(() =>
                {
                    Console.WriteLine(GetIp.GetLocalIPAddress());
                });
            });

            //Number 7
            /*------------------------------------------------------------------------*/

            app.Command("ip-external", cmd =>
            {
                cmd.OnExecute(() =>
                {
                    Console.WriteLine(GetIp.GetPublicIp());
                });
            });

            //Number 8
            /*------------------------------------------------------------------------*/

            app.Command("screenshot", cmd =>
            {
                var link   = cmd.Argument("link", "link to be screenshot").IsRequired();
                var format = cmd.Option("--format", "the format", CommandOptionType.SingleOrNoValue);
                var output = cmd.Option("--output", "the output", CommandOptionType.SingleOrNoValue);
                cmd.OnExecute(() =>
                {
                    if (format.HasValue() && output.HasValue())
                    {
                        Screenshot.GetScreenshot(link.Value, format.Value(), output.Value());
                    }
                    else if (format.HasValue())
                    {
                        Screenshot.GetScreenshot(link.Value, format.Value());
                    }
                    else if (output.HasValue())
                    {
                        Screenshot.GetScreenshot(link.Value, default, output.Value());
Exemple #21
0
            /// <summary>
            ///     Runs a given form's xml schema against it throwing an exception if it fails to validate
            /// </summary>
            /// <param name= NavKey.DocTypeName></param>
            /// <param name="xml"></param>
            internal void Validate(string DocData, BaseDoc _BaseDoc)
            {
                if (_BaseDoc.DocKeys.Count == 0)
                {
                    throw new Exception("No DocKeys have been defined");
                }

                Type t = _BaseDoc.GetType();

                using (StringReader _StringReader = new StringReader(DocData))
                    using (XmlTextReader _XmlTextReader = new XmlTextReader(_StringReader))
                        using (XmlValidatingReader _XmlValidatingReader = new XmlValidatingReader(_XmlTextReader)
                        {
                            ValidationType = ValidationType.Schema
                        })
                        //TODO:Use XmlReader to perform validation instead of XmlValidatingReader (http://msdn.microsoft.com/en-us/library/hdf992b8%28v=VS.80%29.aspx)
                        {
                            // Grab the xml namescape that was expressed as an attribute of the class the XsnTransform.cmd auto generated
                            ValidatingNamespace = t
                                                  .GetCustomAttributes(false)
                                                  .OfType <DataContractAttribute>()
                                                  .FirstOrDefault()
                                                  .Namespace;

                            using (StringReader _StringReaderXsd = new StringReader(TemplateController.Instance.OpenText(_BaseDoc.DocTypeName, _BaseDoc.solutionVersion, "myschema.xsd")))
                                using (XmlTextReader _XmlTextReaderXsd = new XmlTextReader(_StringReaderXsd))
                                {
                                    // Add that class into .Net XML XSD schema validation
                                    _XmlValidatingReader.Schemas.Add(ValidatingNamespace, _XmlTextReaderXsd);

                                    _XmlValidatingReader.ValidationEventHandler += _XmlValidatingReader_ValidationEventHandler;
                                    //Start validating

                                    while (_XmlValidatingReader.Read())
                                    {
                                    }
                                }
                        }

                if (ValidationMessages.Count > 0)
                {
                    List <string> FieldErrors = new List <string>();

                    Regex regexObj = new Regex(@"http://[^']+:(\w+)' element has an invalid value according to its data type", RegexOptions.IgnoreCase | RegexOptions.Multiline);

                    foreach (string _T in ValidationMessages)
                    {
                        if (_T.Contains("Signature(s)"))
                        {
                            FieldErrors.Add(_T);
                        }
                        else if (regexObj.IsMatch(_T))
                        {
                            FieldErrors.Add(StringTransform.Wordify(regexObj.Match(_T)
                                                                    .Groups[1].Value.Trim()
                                                                    .Trim(':')));
                        }
                        else
                        {
                            foreach (PropertyInfo p in t.GetProperties())
                            {
                                if (Regex.IsMatch(_T, string.Format(@"\b(?=\w){0}\b(?!\w)", p.Name)))
                                {
                                    FieldErrors.Add(StringTransform.Wordify(p.Name)
                                                    .Trim()
                                                    .Trim(':'));
                                }
                            }
                        }
                    }

                    if (FieldErrors.Count > 0)
                    {
                        string ValidationMessageMarkDown =
                            string.Format(
                                "\t\t{0}",
                                string.Join("\r\n\t\t", FieldErrors.Where(m => !string.IsNullOrWhiteSpace(m))
                                            .Distinct()));

                        int ValidationMessagesCount = FieldErrors.Count;
                        ValidationMessages.Clear();

                        throw new Exception(
                                  string.Format(
                                      "TODO:Put back this valiation message from repo as I deleted the resx on accident",
                                      ValidationMessagesCount,
                                      ValidationMessageMarkDown));
                    }
                }
                ValidationMessages.Clear();
            }
Exemple #22
0
        /// <summary>
        /// </summary>
        /// <param name="cSharpCode"></param>
        /// <param name="TempFileFolderName">Define this for debugging purposes</param>
        /// <returns></returns>
        internal static Assembly CompileCSharpCode(string cSharpCode, params string[] DebuggingTempFileDirectoryNameParts)
        {
            bool IncludeDebugInformation =
#if DEBUG
                true;
#else
                false;
#endif
            int key = Math.Abs(cSharpCode.GetHashCode()
                               ^ IncludeDebugInformation.GetHashCode()
                               ^ typeof(Runtime).Assembly.FullName.GetHashCode()
                               ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode() // just incase the user changes due to an apppool change
                               );

            if (!CompileCSharpCodeAssemblies.ContainsKey(key))
            {
                CompilerParameters _CompilerParameters = new CompilerParameters
                {
                    IncludeDebugInformation = IncludeDebugInformation,
                    GenerateExecutable      = false,
                    GenerateInMemory        = false,
                    WarningLevel            = 0
                };

                // it was unknown at them time of this writting
                if (!string.IsNullOrWhiteSpace(CompileCSharpCodeDefaultOutDirectory))
                {
                    _CompilerParameters.OutputAssembly = CompileCSharpCodeDefaultOutDirectory + "\\" + Base36.Encode(key) + ".dll";
                }

                if (File.Exists(_CompilerParameters.OutputAssembly))
                {
                    CompileCSharpCodeAssemblies[key] = Assembly.LoadFile(_CompilerParameters.OutputAssembly);
                }
                else
                {
                    // Combine & normalize (different paths that load to the same dll) lists of referenced assemblies. Consider our custom list (UsingNamespaces.Values) & whatever is currently loaded into the AppDomain.This ensures the newly compiled object will have everything it needs.
                    Dictionary <string, string> ReferenceAssembliesDic = new Dictionary <string, string>();
                    foreach (string AppDomainAssemFileName in
                             AppDomain.CurrentDomain.GetAssemblies().Where(m => !m.IsDynamic).Select(m => m.Location))
                    {
                        if (File.Exists(AppDomainAssemFileName))
                        {
                            foreach (
                                string DirectoryName in
                                new[]
                            {
                                new FileInfo(AppDomainAssemFileName).DirectoryName,
                                @".",
                                @".\bin",
                                @".\bin\debug",
                                @".\bin\release"
                            })
                            {
                                if (Directory.Exists(DirectoryName))
                                {
                                    foreach (FileInfo _FileInfo in USING_NAMESPACES
                                             .Values
                                             .Select(FileName => String.Format(@"{0}\\{1}", DirectoryName, FileName))
                                             .Where(FilePath => File.Exists(FilePath))
                                             .Select(FilePath => new FileInfo(FilePath))
                                             .Where(_FileInfo => !ReferenceAssembliesDic.ContainsKey(_FileInfo.Name.ToLower())))
                                    {
                                        ReferenceAssembliesDic[_FileInfo.Name.ToLower()] = _FileInfo.FullName;
                                    }
                                }
                            }
                        }
                    }

                    _CompilerParameters.ReferencedAssemblies.AddRange(ReferenceAssembliesDic.Values.ToArray());

                    CompilerResults _CompilerResults = CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                    if (_CompilerResults.Errors.Count == 0)
                    {
                        CompileCSharpCodeDefaultOutDirectory = Path.GetDirectoryName(_CompilerResults.PathToAssembly);
                        CompileCSharpCodeAssemblies[key]     = _CompilerResults.CompiledAssembly;
                    }
                    else
                    {
                        new DirectoryInfo(RequestPaths.GetPhysicalApplicationPath(FOLDER_FOR_COMPILE_TEMPORARY_FILES)).mkdir().Attributes = FileAttributes.Hidden;

                        if (DebuggingTempFileDirectoryNameParts != null && DebuggingTempFileDirectoryNameParts.Length > 0)
                        {
                            int           i = 0;
                            DirectoryInfo _DirectoryInfo = null;


                            // often there are processes that just won't let there handles go off previous files generated
                            // now we try delete those directories or create a new one with an auto-incremented number when the previous can't be removed
                            do
                            {
                                _DirectoryInfo = new DirectoryInfo(
                                    RequestPaths
                                    .GetPhysicalApplicationPath(
                                        new[] { FOLDER_FOR_COMPILE_TEMPORARY_FILES, StringTransform.SafeIdentifier(string.Join(" ", DebuggingTempFileDirectoryNameParts.Union(new[] { string.Format("{0}", i++) }))) }
                                        .ToArray()));

                                try { _DirectoryInfo.rmdir(); } catch (Exception) { }
                            } while (_DirectoryInfo.Exists);

                            _DirectoryInfo.mkdir();

                            _CompilerParameters.GenerateInMemory        = false;
                            _CompilerParameters.IncludeDebugInformation = true;
                            _CompilerParameters.TempFiles             = new TempFileCollection(_DirectoryInfo.FullName, true);
                            _CompilerParameters.TreatWarningsAsErrors = true;

                            CSharpCodeProvider.CompileAssemblyFromSource(_CompilerParameters, cSharpCode);

                            throw new Exception(string.Format("\"{0}\" Contains runtime the intermediate files of a runtime build (compile) that failed.", _DirectoryInfo.FullName));
                        }
                    }
                }
            }
            return(CompileCSharpCodeAssemblies[key]);
        }
Exemple #23
0
        public static Expression CreateStringPropertyCompareExpression(this Expression keyValueParm, string keyCompareValue, string propertyValue, StringTransform keyTransform, StringComparison keyComparison)
        {
            var keyProp  = Expression.Property(keyValueParm, propertyValue);
            var keyConst = Expression.Constant(keyCompareValue, typeof(string));

            return(keyProp.CreateStringCompare(keyTransform, keyComparison, keyConst));
        }
Exemple #24
0
        public static Expression CreateStringPropertyCompareExpression <TValue>(this Expression keyValueParm, TValue keyCompareValue, Expression property, StringTransform keyTransform, StringComparison keyComparison)
        {
            var keyConst = Expression.Constant(keyCompareValue, typeof(TValue));

            return(keyComparison == StringComparison.NotEquals ? Expression.Not(property.CreateStringCompare(keyTransform, keyComparison, keyConst)) : property.CreateStringCompare(keyTransform, keyComparison, keyConst));
        }
Exemple #25
0
 private static string pretty(string Name)
 {
     return(StringTransform.PrettyMsSqlIdent(Name));
 }
Exemple #26
0
        /// <summary>
        /// Cleans a <see cref="String"/> and optionally allows <see cref="String.Empty"/>.
        /// </summary>
        /// <param name="value">The value to clean.</param>
        /// <param name="trim">The <see cref="StringTrim"/> (defaults to <see cref="DefaultStringTrim"/>).</param>
        /// <param name="transform">The <see cref="StringTransform"/> (defaults to <see cref="DefaultStringTransform"/>).</param>
        /// <returns>The cleaned value.</returns>
        public static string Clean(string value, StringTrim trim = DefaultStringTrim, StringTransform transform = DefaultStringTransform)
        {
            // Handle a null string.
            if (value == null)
            {
                if (transform == StringTransform.NullToEmpty)
                {
                    return(string.Empty);
                }
                else
                {
                    return(value);
                }
            }

            // Trim the string.
            string tmp;

            switch (trim)
            {
            case StringTrim.Both:
                tmp = value.Trim();
                break;

            case StringTrim.Start:
                tmp = value.TrimStart();
                break;

            case StringTrim.End:
                tmp = value.TrimEnd();
                break;

            case StringTrim.None:
            default:
                tmp = value;
                break;
            }

            // Transform the string.
            switch (transform)
            {
            case StringTransform.EmptyToNull:
                return((tmp.Length == 0) ? null : tmp);

            case StringTransform.NullToEmpty:
                return(tmp ?? string.Empty);

            case StringTransform.None:
            default:
                return(tmp);
            }
        }
Exemple #27
0
 private static string pretty(string name) =>
 _prettyDictionary.ContainsKey(name)
                                                  ? _prettyDictionary[name]
                                                  : (_prettyDictionary[name] = StringTransform.PrettyMsSqlIdent(name));
Exemple #28
0
        /// <summary>
        ///     Creates a namespace (each DocType, DocRev & it's children reside in a dedicated namespace) that is suitable for
        ///     parsing then reversing to it's original string representations. The transformations to and from DocTypeName/DocRev
        ///     & C# namespace is a lossless operation. The inverse of this method is TryParseDocTypeAndRev. Segments for the
        ///     DocType's actual name are prefixed with "doc", for the DocRev: "rev". Example:
        ///     docFORM200.rev1.rev0.rev56.HERE.ARE.SOME.ADDITIONAL.NS_PARTS
        /// </summary>
        /// <param name="DocTypeName"></param>
        /// <param name="DocRev"></param>
        /// <param name="AdditionalRootNames"></param>
        /// <returns>DotTypeName as the root name & DocRev as the second level name if nothing specified in AdditionalRootNames</returns>
        internal static string CalcCSharpFullname(string DocTypeName, string DocRev, params string[] AdditionalRootNames)
        {
            // validate arguments
            if (INVALID_CSHARP_NAMESPACE_PART_MATCH.IsMatch(DocTypeName) | String.IsNullOrWhiteSpace(DocTypeName))
            {
                throw new ArgumentException(String.Format("\"{0}\" is not a valid DocTypeName for namespace code generation operations"), DocTypeName);
            }

            if (INVALID_CSHARP_NAMESPACE_PART_MATCH.IsMatch(DocRev) | String.IsNullOrWhiteSpace(DocRev))
            {
                throw new ArgumentException(String.Format("\"{0}\" is not a valid DocRev for namespace code generation operations"), DocRev);
            }

            if (AdditionalRootNames != null)
            {
                foreach (string test in AdditionalRootNames)
                {
                    if (!String.IsNullOrWhiteSpace(test))
                    {
                        if (INVALID_CSHARP_NAMESPACE_PART_MATCH.IsMatch(test))
                        {
                            throw new ArgumentException(String.Format("\"{0}\" is not valid for namespace code generation operations"), test);
                        }
                    }
                }
            }

            string[] DocTypeNameParts = DocTypeName.Split('.').Select(s => String.Format("{0}{1}", DOCTYPENAME_NS_PREFIX, s.ToUpper())).ToArray();
            string[] RevParts         = DocRev.Split('.').Select(s => String.Format("{0}{1}", DOCREV_NS_PREFIX, s.ToUpper())).ToArray();
            string[] OtherParts       = AdditionalRootNames == null
                                      ? new string[]
            {}
                                      : AdditionalRootNames.Where(s => !String.IsNullOrWhiteSpace(s)).Select(s => String.Format("{0}{1}", ADDITIONAL_NS_PREFIX, StringTransform.SafeIdentifier(s ?? "_").ToUpper())).ToArray();

            return(String.Join(".", DocTypeNameParts.Concat(RevParts).Concat(OtherParts)));
        }