Ejemplo n.º 1
0
        /// <summary>
        /// Creates an instance of a SqlCommand. Populates the command if the parameters are supplied.
        /// </summary>
        /// <param name="sql">The T-SQL for the command.</param>
        /// <param name="parameters">An object that contains properties to use as parameters for the command. The property name must match a parameter in the sql or it will be ignored.</param>
        /// <returns></returns>
        public DbCommand CreateCommand(string sql = null, object parameters = null)
        {
            var cmd = new SqlCommand();

            cmd.CommandText = sql;
            if (parameters == null)
            {
                return(cmd);
            }

            var props = TypeDescriptor.GetProperties(parameters);

            foreach (PropertyDescriptor prop in props)
            {
                var paramName = "@" + prop.Name;
                if (!sql.Contains(paramName))
                {
                    continue;
                }
                var parameter = cmd.CreateParameter();
                parameter.ParameterName = paramName;
                var value = prop.GetValue(parameters);
                if (ConvertEx.IsEmpty(value))
                {
                    value = DBNull.Value;
                }
                parameter.Value = value;
                cmd.Parameters.Add(parameter);
            }
            return(cmd);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Adds a value to the end of the parameter collection.
 /// </summary>
 /// <param name="parameters"></param>
 /// <param name="name"></param>
 /// <param name="value"></param>
 /// <param name="setNull">If true, sets the value to DBNull if it ConvertEx.IsEmpty is true.</param>
 /// <returns></returns>
 public static SqlParameter AddWithValue(this SqlParameterCollection parameters, string name, object value, bool setNull)
 {
     if (setNull && ConvertEx.IsEmpty(value))
     {
         value = DBNull.Value;
     }
     return(parameters.AddWithValue(name, value));
 }
Ejemplo n.º 3
0
 /// <summary>
 /// If ConvertEx.IsEmpty() return true, returns the emptyVal. Otherwise returns the original object.
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="emptyVal"></param>
 /// <returns></returns>
 public static object IfEmpty(this object obj, object emptyVal)
 {
     if (ConvertEx.IsEmpty(obj))
     {
         return(emptyVal);
     }
     else
     {
         return(obj);
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a new array that contains the non-empty elements of the given array.
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static IEnumerable <T> RemoveEmpties <T>(this IEnumerable <T> arr)
        {
            var vals = new List <T>();

            foreach (var val in arr)
            {
                if (!ConvertEx.IsEmpty(val))
                {
                    vals.Add(val);
                }
            }

            return(vals);
        }
Ejemplo n.º 5
0
        public void IsEmptyTest()
        {
            object value = null;

            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = "test";
            Assert.IsFalse(ConvertEx.IsEmpty(value));

            value = "";
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = int.MinValue;
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = int.MaxValue;
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = 0;
            Assert.IsFalse(ConvertEx.IsEmpty(value));

            value = new char();
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = DateTime.MinValue;
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = DateTime.Parse("7/4/2008");
            Assert.IsFalse(ConvertEx.IsEmpty(value));

            value = String.Empty;
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = ConvertTest.Empty;
            Assert.IsTrue(ConvertEx.IsEmpty(value));

            value = new ConvertTest()
            {
                X = 5, Y = 10
            };
            Assert.IsFalse(ConvertEx.IsEmpty(value));

            value = new ConvertTest()
            {
                X = 0, Y = 0
            };
            Assert.IsTrue(ConvertEx.IsEmpty(value));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a new array that contains the non-empty elements of the given array.
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static Array RemoveEmpties(this Array arr)
        {
            var vals = new List <object>();

            for (int i = 0; i < arr.Length; i++)
            {
                var val = arr.GetValue(i);
                if (!ConvertEx.IsEmpty(val))
                {
                    vals.Add(val);
                }
            }

            Array retArr = Array.CreateInstance(arr.GetType().GetElementType(), vals.Count);

            for (int i = 0; i < vals.Count; i++)
            {
                retArr.SetValue(vals[i], i);
            }

            return(retArr);
        }
Ejemplo n.º 7
0
 public void IsEmptyTest()
 {
     Assert.IsTrue(ConvertEx.IsEmpty(null));
     Assert.IsFalse(ConvertEx.IsEmpty("test"));
     Assert.IsTrue(ConvertEx.IsEmpty(""));
     Assert.IsTrue(ConvertEx.IsEmpty(int.MinValue));
     Assert.IsTrue(ConvertEx.IsEmpty(int.MaxValue));
     Assert.IsTrue(ConvertEx.IsEmpty(0));
     Assert.IsFalse(ConvertEx.IsEmpty(123));
     Assert.IsTrue(ConvertEx.IsEmpty(new char()));
     Assert.IsTrue(ConvertEx.IsEmpty(DateTime.MinValue));
     Assert.IsFalse(ConvertEx.IsEmpty("7/4/2008"));
     Assert.IsTrue(ConvertEx.IsEmpty(String.Empty));
     Assert.IsTrue(ConvertEx.IsEmpty(ConvertTest.Empty));
     Assert.IsFalse(ConvertEx.IsEmpty(new ConvertTest()
     {
         X = 5, Y = 10
     }));
     Assert.IsTrue(ConvertEx.IsEmpty(new ConvertTest()
     {
         X = 0, Y = 0
     }));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds a value to the end of the parameter collection.
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="setNull">If true, sets the value to DBNull if it ConvertEx.IsEmpty is true.</param>
        /// <param name="dbType"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static DbParameter AddParameter(this DbCommand cmd, string name, object value, bool setNull, DbType?dbType = null, int?size = null)
        {
            if (setNull && ConvertEx.IsEmpty(value))
            {
                value = DBNull.Value;
            }

            var param = cmd.CreateParameter();

            param.ParameterName = name;
            param.Value         = value;

            if (dbType.HasValue)
            {
                param.DbType = dbType.Value;
            }
            if (size.HasValue)
            {
                param.Size = size.Value;
            }

            cmd.Parameters.Add(param);
            return(param);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Shortcut for !ConvertEx.IsEmpty. Works because this is an extension method, not a real method.
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static bool HasValue(this string str)
 {
     return(!ConvertEx.IsEmpty(str));
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Shortcut for ConvertEx.IsEmpty. Works because this is an extension method, not a real method.
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static bool IsEmpty(this string str)
 {
     return(ConvertEx.IsEmpty(str));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets the full description for the command-line arguments.
        /// </summary>
        /// <param name="maxWidth">Determines the number of characters per line. Set this to Console.Width.</param>
        /// <returns></returns>
        public virtual string GetHelpText(int maxWidth)
        {
            if (Properties == null)
            {
                throw new InvalidOperationException("The command-line object has not been initialized yet.");
            }

            var helpTextBuilder = new HelpTextBuilder(maxWidth);

            if (mErrors != null && mErrors.Any())
            {
                helpTextBuilder.AppendLine("ERROR: " + mErrors[0]);
                foreach (var error in mErrors)
                {
                    helpTextBuilder.AppendLine(error);
                }
                helpTextBuilder.AppendLine();
            }

            helpTextBuilder.AppendLine(Options.Title);
            helpTextBuilder.AppendLine(Options.Description);
            helpTextBuilder.AppendLine(Options.Usage);
            helpTextBuilder.AppendLine();

            int maxNameWidth = GetMaxNameLength() + 6;             // Add extra for ' (S): '
            int maxDescWidth = maxWidth - maxNameWidth;
            var indent       = new string(Space, maxNameWidth);

            foreach (CmdLineProperty prop in Properties)
            {
                var propName = new StringBuilder();

                if (prop.Aliases.Length == 0)
                {
                    propName.Append(Options.ArgumentPrefix);
                    propName.Append(prop.Name);
                }
                else
                {
                    propName.Append(Options.ArgumentPrefix);
                    propName.Append(string.Join(" | " + Options.ArgumentPrefix, prop.Aliases));
                }

                helpTextBuilder.Append(propName.ToString().PadRight(maxNameWidth));
                string   propDesc = prop.Description.Wrap(maxDescWidth);
                string[] lines    = propDesc.Lines();
                if (lines.Length > 0)
                {
                    helpTextBuilder.AppendLine(lines[0]);
                    for (int i = 1; i < lines.Length; i++)
                    {
                        helpTextBuilder.AppendLine(indent + lines[i]);
                    }
                }
                else
                {
                    // If there isn't a description, we need to add a line break.
                    helpTextBuilder.AppendLine(prop.Name.Wrap(maxDescWidth));
                }
                if (prop.Required)
                {
                    helpTextBuilder.AppendLine(indent + "REQUIRED");
                }
                else if (prop.ShowDefaultValue)
                {
                    object dflt = prop.DefaultValue;
                    if (!ConvertEx.IsEmpty(dflt))
                    {
                        var arr = dflt as Array;
                        if (arr != null)
                        {
                            string[] strs = arr.Convert <string>();
                            if (dflt.GetType().GetElementType() == typeof(string))
                            {
                                dflt = "[\"{0}\"]".Fmt(strs.Join("\", \""));
                            }
                            else
                            {
                                dflt = "[{0}]".Fmt(strs.Join(", "));
                            }
                        }
                        helpTextBuilder.AppendLine(indent + string.Format("Default Value: {0}", dflt));
                    }
                }

                if (prop.PropertyType.IsEnum)
                {
                    var      enumVals  = new StringBuilder();
                    string[] enumNames = prop.PropertyType.GetEnumNames();
                    enumVals.AppendFormat(indent + "Possible Values: [{0}]", enumNames.Join(", "));
                    helpTextBuilder.AppendLine(enumVals.ToString());
                }

                foreach (ValidationAttribute validator in prop.GetValidationAtts())
                {
                    string message = validator.FormatErrorMessage(prop.Name).Wrap(maxDescWidth);
                    foreach (string line in message.Lines())
                    {
                        helpTextBuilder.AppendLine(indent + line);
                    }
                }
                foreach (ICustomValidator validator in prop.Validators)
                {
                    string message = validator.FormatErrorMessage(prop.Name).Wrap(maxDescWidth);
                    foreach (string line in message.Lines())
                    {
                        helpTextBuilder.AppendLine(indent + line);
                    }
                }
            }

            return(helpTextBuilder.ToString());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the help text for a single property.
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        public virtual string GetPropertyHelp(CmdLineProperty prop)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("{0}{1}", ParseResults.Options.ArgumentPrefix, prop.Name);
            if (prop.Aliases.Length > 0)
            {
                var aliases = string.Join(" | " + ParseResults.Options.ArgumentPrefix, prop.Aliases);
                sb.AppendFormat(" ({0}{1})", ParseResults.Options.ArgumentPrefix, aliases);
            }

            sb.AppendFormat(" <{0}>", GetPropertyTypeDisplay(prop));

            if (prop.Required)
            {
                sb.Append(" REQUIRED");
            }

            if (prop.Description.HasValue())
            {
                sb.AppendFormat("\n\t{0}", prop.Description);
            }

            if (prop.ShowDefaultValue)
            {
                object dflt = prop.DefaultValue;
                if (!ConvertEx.IsEmpty(dflt) || prop.PropertyType.IsEnum)
                {
                    if (dflt is Array arr)
                    {
                        var strs = arr.Convert <string>();
                        if (dflt.GetType().GetElementType() == typeof(string))
                        {
                            dflt = "[\"{0}\"]".Fmt(strs.Join("\", \""));
                        }
                        else
                        {
                            dflt = "[{0}]".Fmt(strs.Join(", "));
                        }
                    }
                    sb.AppendFormat("\n\tDefault: {0}", dflt);
                }
            }

            foreach (var att in prop.Property.Attributes)
            {
                var validator = att as ValidationAttribute;
                if (validator == null)
                {
                    continue;
                }

                // The RequiredAttribute is handled differently.
                if (validator.GetType() == typeof(RequiredAttribute))
                {
                    continue;
                }

                string message = validator.FormatErrorMessage(prop.Name);
                sb.AppendFormat("\n\t{0}", message);
            }

            return(sb.ToString());
        }