protected void SetFields(Type elementType, KeyValuePair <string, Type>[] membersInfo = null)
        {
            Dictionary <string, ChoObjectDataReaderProperty> prop = new Dictionary <string, ChoObjectDataReaderProperty>();

            Fields = new List <ChoObjectDataReaderProperty>();

            if (membersInfo != null)
            {
                foreach (KeyValuePair <string, Type> kvp in membersInfo)
                {
                    if (!prop.ContainsKey(kvp.Key))
                    {
                        prop.Add(kvp.Key, new ChoObjectDataReaderProperty(kvp.Key, kvp.Value));
                    }
                }
            }
            else
            {
                foreach (MemberInfo info in ChoType.GetMembers(elementType))
                {
                    if (!prop.ContainsKey(info.Name))
                    {
                        prop.Add(info.Name, new ChoObjectDataReaderProperty(info));
                    }
                }
            }

            Fields = new List <ChoObjectDataReaderProperty>(prop.Values.ToArray());
        }
Beispiel #2
0
        public IDictionary <string, object> GetDefaults()
        {
            IDictionary <string, object> dict = new Dictionary <string, object>();

            ChoPropertyAttribute attr = null;
            object memberValue        = null;
            string propName           = null;

            //scan through members and load them
            foreach (var prop in ChoType.GetMembers(GetType()).Where(m => m.GetCustomAttribute <ChoIgnoreMemberAttribute>() != null && !ChoType.IsReadOnlyMember(m)))
            {
                attr = ChoType.GetMemberAttribute <ChoPropertyAttribute>(prop);
                try
                {
                    propName    = attr != null && !attr.Name.IsNullOrWhiteSpace() ? attr.Name : prop.Name;
                    memberValue = ChoType.GetDefaultValue(ChoType.GetMemberInfo(GetType(), prop.Name));

                    if (memberValue != null && memberValue is string)
                    {
                        string mv = memberValue as string;
                        if (attr != null)
                        {
                            switch (attr.TrimOption)
                            {
                            case ChoPropertyValueTrimOption.Trim:
                                mv = mv.Trim();
                                break;

                            case ChoPropertyValueTrimOption.TrimEnd:
                                mv = mv.TrimEnd();
                                break;

                            case ChoPropertyValueTrimOption.TrimStart:
                                mv = mv.TrimStart();
                                break;
                            }
                        }

                        memberValue = mv;
                    }

                    if (!dict.ContainsKey(propName))
                    {
                        dict.Add(propName, memberValue);
                    }
                }
                catch (Exception ex)
                {
                    //ChoLog.Error("{0}: Error getting default value for '{1}' property. {2}".FormatString(NName, prop.Name, ex.Message));
                    SetDefaultValue(prop, false);
                }
            }

            return(dict);
        }
Beispiel #3
0
        protected void SetFields(Type elementType, KeyValuePair <string, Type>[] membersInfo = null)
        {
            Dictionary <string, ChoObjectDataReaderProperty> prop = new Dictionary <string, ChoObjectDataReaderProperty>();

            Fields = new List <ChoObjectDataReaderProperty>();

            if (membersInfo != null)
            {
                var dict = membersInfo.GroupBy(kvp => kvp.Key).ToDictionary(g => g.Key, g => g.FirstOrDefault());
                var m    = ChoType.GetMembers(elementType).Where(m1 => dict.ContainsKey(m1.Name));
                if (m.Any())
                {
                    foreach (var mi in m)
                    {
                        prop.Add(mi.Name, new ChoObjectDataReaderProperty(mi));
                    }
                }
                else
                {
                    if (elementType.IsSimple())
                    {
                        prop.Add("Value", new ChoObjectDataReaderProperty("Value", elementType, true));
                    }
                    else
                    {
                        foreach (KeyValuePair <string, Type> kvp in membersInfo)
                        {
                            if (!prop.ContainsKey(kvp.Key))
                            {
                                prop.Add(kvp.Key, new ChoObjectDataReaderProperty(kvp.Key, kvp.Value));
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (MemberInfo info in ChoType.GetMembers(elementType))
                {
                    if (!prop.ContainsKey(info.Name))
                    {
                        prop.Add(info.Name, new ChoObjectDataReaderProperty(info));
                    }
                }
            }

            Fields = new List <ChoObjectDataReaderProperty>(prop.Values.ToArray());
        }
Beispiel #4
0
        public static IList <Property> CreatePropertyMethods(Type type)
        {
            var returnValue = new List <Property>();

            //returnValue.Add(new Property("CustomerID", typeof(string)));
            //return returnValue;
            foreach (MemberInfo info in ChoType.GetMembers(type))
            {
            }

            foreach (PropertyInfo prop in type.GetProperties())
            {
                returnValue.Add(new Property(prop));
            }
            return(returnValue);
        }
Beispiel #5
0
        public string GetDescription(string name)
        {
            var m1 = ChoType.GetMembers(GetType()).Where(m => !ChoType.IsReadOnlyMember(m)).FirstOrDefault();

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

            if (ChoType.HasMemberAttribute <DescriptionAttribute>(m1))
            {
                return(m1.GetCustomAttribute <DescriptionAttribute>().Description);
            }
            else
            {
                return(null);
            }
        }
        private static void GetErrorMsgs(object target, ChoStringMsgBuilder msg)
        {
            MemberInfo[]  memberInfos = ChoType.GetMembers(target.GetType()); //, typeof(ChoMemberInfoAttribute));
            List <string> errMsgs     = new List <string>();
            string        errMsg;

            if (memberInfos != null && memberInfos.Length >= 0)
            {
                foreach (MemberInfo memberInfo in memberInfos)
                {
                    errMsg = ChoConfigurationObjectErrorManagerService.GetObjectMemberError(target, memberInfo.Name);
                    if (errMsg != null)
                    {
                        errMsgs.Add(String.Format("{0}: {1}", memberInfo.Name, errMsg));
                    }
                }
            }

            if (errMsgs.Count > 0)
            {
                msg.AppendLine();
                ChoStringMsgBuilder errReport = new ChoStringMsgBuilder("Following errors occurred while construction");

                foreach (string errMsg1 in errMsgs)
                {
                    errReport.AppendFormatLine(errMsg1);
                }

                msg.AppendLine(errReport.ToString().Indent(1));
            }
            else
            {
                errMsg = ChoConfigurationObjectErrorManagerService.GetObjectError(target);

                if (!errMsg.IsNullOrEmpty())
                {
                    msg.AppendLine();
                    ChoStringMsgBuilder errReport = new ChoStringMsgBuilder("Following errors occurred while construction");
                    errReport.AppendFormatLine(errMsg);

                    msg.AppendLine(errReport.ToString().Indent(1));
                }
            }
        }
Beispiel #7
0
        private static void DoValidate <T>(T target, ChoValidationResults validationResults)
        {
            bool validationRoutineFound = false;
            bool canContinue            = true;

            foreach (MethodInfo methodInfo in GetValidationRoutines(target.GetType()))
            {
                canContinue            = false;
                validationRoutineFound = true;
                canContinue            = (bool)ChoType.InvokeMethod(target, methodInfo.Name, new object[] { validationResults });
                if (!canContinue)
                {
                    break;
                }
            }

            //Do built-in attribute validations
            if (!validationRoutineFound)
            {
                MemberInfo[] memberInfos = ChoType.GetMembers(target.GetType());
                foreach (MemberInfo memberInfo in memberInfos)
                {
                    IChoSurrogateValidator validator = ChoCompositeValidatorBuilder.GetValidator(memberInfo);
                    if (validator == null)
                    {
                        continue;
                    }

                    try
                    {
                        validator.Validate(memberInfo, ChoType.GetMemberValue(target, memberInfo.Name));
                    }
                    catch (ChoFatalApplicationException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        validationResults.AddResult(new ChoValidationResult(ex.Message));
                    }
                }
            }
        }
        private void LoadConverterParams(Type declaringType)
        {
            ChoIniFile iniFile = GetIniSection(declaringType, "FORMATTER");

            var                dict            = new Dictionary <string, object[]>();
            string             parameters      = null;
            ChoMemberAttribute memberAttribute = null;

            foreach (MemberInfo memberInfo in ChoType.GetMembers(declaringType))
            {
                memberAttribute = ChoType.GetAttribute <ChoMemberAttribute>(memberInfo);
                if (memberAttribute == null)
                {
                    continue;
                }

                try
                {
                    if (_turnOnMetaDataCache)
                    {
                        parameters = iniFile.GetValue(memberInfo.Name);
                    }

                    List <object> p = new List <object>();
                    if (!parameters.IsNullOrWhiteSpace())
                    {
                        foreach (string kv in parameters.SplitNTrim(';'))
                        {
                            p.Add(kv.SplitNTrim(','));
                        }
                    }

                    dict.Add(memberInfo.Name, parameters.IsNullOrWhiteSpace() ? null : p.ToArray());
                }
                catch (Exception ex)
                {
                    ChoETLFramework.WriteLog(ChoETLFramework.Switch.TraceError, "Failed to retrieve converter params for '{0}' member type from INI file. {1}".FormatString(ChoType.GetMemberName(memberInfo), ex.Message));
                }
            }
            _converterParams.Add(declaringType, dict);
        }
Beispiel #9
0
        public object CleanValue(string name, object value)
        {
            var m1 = ChoType.GetMembers(GetType()).Where(m => !ChoType.IsReadOnlyMember(m) &&
                                                         (m.GetCustomAttribute <ChoPropertyAttribute>() != null && m.GetCustomAttribute <ChoPropertyAttribute>().Name == name) || m.Name == name).FirstOrDefault();

            if (m1 == null)
            {
                return(value);
            }

            value = ChoConvert.ConvertFrom(value, m1);

            var attr = ChoType.GetMemberAttribute <ChoPropertyAttribute>(m1);

            if (value != null && value is string)
            {
                string mv = value as string;
                if (attr != null)
                {
                    switch (attr.TrimOption)
                    {
                    case ChoPropertyValueTrimOption.Trim:
                        mv = mv.Trim();
                        break;

                    case ChoPropertyValueTrimOption.TrimEnd:
                        mv = mv.TrimEnd();
                        break;

                    case ChoPropertyValueTrimOption.TrimStart:
                        mv = mv.TrimStart();
                        break;
                    }
                }
                return(mv);
            }

            return(value);
        }
Beispiel #10
0
        public static bool IsValid(this object @this, out Exception aggEx)
        {
            aggEx = null;

            if (@this == null)
            {
                return(true);
            }

            var    results = new List <ValidationResult>();
            object surrObj = ChoSurrogateObjectCache.Default.GetSurrogateObject(@this);

            if (surrObj is IChoValidatable)
            {
                ((IChoValidatable)surrObj).TryValidate(@this, results);
            }
            else
            {
                foreach (MemberInfo mi in ChoType.GetMembers(@this.GetType()).Where(m => ChoType.GetMemberAttributeByBaseType <ChoMemberAttribute>(m) != null))
                {
                    //if (ChoObjectMemberMetaDataCache.Default.IsRequired(mi) && ChoType.GetMemberValue(@this, mi) == null)
                    //    results.Add(new ValidationResult("Null value found for {0} member.".FormatString(mi.Name)));
                }

                var context = new ValidationContext(@this, null, null);
                Validator.TryValidateObject(@this, context, results, true);
            }

            if (results.Count > 0)
            {
                aggEx = new ApplicationException("Failed to validate '{0}' object. {2}{1}".FormatString(@this.GetType().FullName, ToString(results), Environment.NewLine));
                return(false);
            }
            else
            {
                return(true);
            }
        }
        private void LoadIsRequireds(Type declaringType)
        {
            ChoIniFile iniFile = GetIniSection(declaringType, "REQUIRED");

            var  dict       = new Dictionary <string, bool>();
            bool isRequired = false;
            ChoMemberAttribute memberAttribute = null;

            foreach (MemberInfo memberInfo in ChoType.GetMembers(declaringType))
            {
                memberAttribute = ChoType.GetAttribute <ChoMemberAttribute>(memberInfo);
                if (memberAttribute == null)
                {
                    continue;
                }

                try
                {
                    if (_turnOnMetaDataCache)
                    {
                        isRequired = iniFile.GetValue(memberInfo.Name, memberAttribute.IsRequired, _isLockedCache[declaringType]);
                    }
                    else
                    {
                        isRequired = memberAttribute.IsRequired;
                    }

                    dict.Add(memberInfo.Name, isRequired);
                }
                catch (Exception ex)
                {
                    ChoETLFramework.WriteLog(ChoETLFramework.Switch.TraceError, "Incorrect IsRequired value specified for '{0}' member type in INI file. Defaulted to false. {1}".FormatString(ChoType.GetMemberName(memberInfo), ex.Message));
                }
            }

            _isReqCache.Add(declaringType, dict);
        }
Beispiel #12
0
        private static void DoValidate(object target, ChoValidationResults validationResults)
        {
            bool canContinue = true;

            foreach (MethodInfo methodInfo in GetValidationRoutines(target.GetType()))
            {
                canContinue = false;

                canContinue = (bool)ChoType.InvokeMethod(target, methodInfo.Name, validationResults);
                if (!canContinue)
                {
                    break;
                }
            }

            //Do built-in attribute validations
            if (canContinue)
            {
                MemberInfo[] memberInfos = ChoType.GetMembers(target.GetType());
                foreach (MemberInfo memberInfo in memberInfos)
                {
                    foreach (ChoMemberAttribute memberAttribute in ChoType.GetMemberAttributesByBaseType(memberInfo,
                                                                                                         typeof(ChoMemberAttribute)))
                    {
                        try
                        {
                            memberAttribute.Validate(ChoType.GetMemberValue(target, memberInfo.Name), false);
                        }
                        catch (Exception ex)
                        {
                            validationResults.AddResult(ex.Message);
                        }
                    }
                }
            }
        }
Beispiel #13
0
        private void Initialize()
        {
            try
            {
                if (!Monitor.TryEnter(_padLock, 1 * 1000))
                {
                    return;
                }

                IDictionary <string, object> kvpDict = null;

                if (_func != null)
                {
                    kvpDict = _func();
                }
                else
                {
                    kvpDict = Seed();
                }

                if (kvpDict == null)
                {
                    return;
                }

                IDictionary <string, object> mkvpDict = _kvpDict;
                bool hasDiff = mkvpDict == null || kvpDict.Except(mkvpDict).Concat(mkvpDict.Except(kvpDict)).Any();
                if (!hasDiff)
                {
                    return;
                }

                _kvpDict = kvpDict;

                ChoPropertyAttribute attr = null;
                object memberValue        = null;
                string propName           = null;
                //scan through members and load them
                foreach (var prop in ChoType.GetMembers(GetType()).Where(m => m.GetCustomAttribute <ChoIgnoreMemberAttribute>() != null && !ChoType.IsReadOnlyMember(m)))
                {
                    attr = ChoType.GetMemberAttribute <ChoPropertyAttribute>(prop);
                    try
                    {
                        SetDefaultValue(prop, true);

                        propName = attr != null && !attr.Name.IsNullOrWhiteSpace() ? attr.Name : prop.Name;

                        if (kvpDict.ContainsKey(propName))
                        {
                            memberValue = AfterKVPLoaded(prop.Name, kvpDict[propName]);
                        }
                        else
                        {
                            memberValue = AfterKVPLoaded(prop.Name, null);
                        }

                        if (memberValue != null && memberValue is string)
                        {
                            string mv = memberValue as string;
                            if (attr != null)
                            {
                                switch (attr.TrimOption)
                                {
                                case ChoPropertyValueTrimOption.Trim:
                                    mv = mv.Trim();
                                    break;

                                case ChoPropertyValueTrimOption.TrimEnd:
                                    mv = mv.TrimEnd();
                                    break;

                                case ChoPropertyValueTrimOption.TrimStart:
                                    mv = mv.TrimStart();
                                    break;
                                }
                            }

                            memberValue = mv;
                        }

                        if (ChoType.GetMemberType(prop) == typeof(string))
                        {
                            if (!((string)memberValue).IsNullOrEmpty())
                            {
                                ChoType.ConvertNSetMemberValue(this, prop, memberValue);
                            }
                        }
                        else
                        {
                            if (memberValue != null)
                            {
                                ChoType.ConvertNSetMemberValue(this, prop, memberValue);
                            }
                        }
                        ChoValidator.ValidateFor(this, prop);
                    }
                    catch (Exception ex)
                    {
                        //ChoLog.Error("{0}: Error loading '{1}' property. {2}".FormatString(NName, prop.Name, ex.Message));
                        SetDefaultValue(prop, false);
                    }
                }
            }
            catch (Exception outerEx)
            {
                //ChoLog.Error("{0}: Error loading options. {1}".FormatString(NName, outerEx.Message));
            }
            finally
            {
                Monitor.Exit(_padLock);
            }
        }
Beispiel #14
0
        private void LoadConfig(bool refresh)
        {
            object configObject = _configObject;

            //Set default trace output file name
            _traceOutputFileName = configObject.GetType().Name;

            MemberInfo[] memberInfos = ChoType.GetMembers(configObject.GetType(), typeof(ChoMemberInfoAttribute));
            if (memberInfos == null || memberInfos.Length == 0)
            {
                return;
            }

            _configSection = GetConfig();
            if (_configSection == null)
            {
                throw new ChoConfigurationConstructionException("Missing configuration section.");
            }

            if (!refresh)
            {
                //Hookup the configuration watch job
                ChoConfigurationChangeWatcherManager.SetWatcherForConfigSource(_configSection.ConfigurationChangeWatcher);
                ChoConfigurationChangeWatcherManager.ConfigurationChanged += new ChoConfigurationChangedEventHandler(ChoConfigurationChangeWatcherManager_ConfigurationChanged);
            }
            else
            {
                _configSection.ConfigurationChangeWatcher.StopWatching();
            }

            ErrMsg = _configSection.ErrMsg;

            if (!IgnoreError && ErrMsg != null)
            {
                throw new ApplicationException(ErrMsg);
            }

            Hashtable hashTable = _configSection.ToHashtable();
            //Set member values
            string name;
            ChoMemberInfoAttribute memberInfoAttribute = null;

            foreach (MemberInfo memberInfo in memberInfos)
            {
                memberInfoAttribute = (ChoMemberInfoAttribute)ChoType.GetMemberAttribute(memberInfo, typeof(ChoMemberInfoAttribute));
                if (memberInfoAttribute == null)
                {
                    continue;
                }

                name = memberInfoAttribute.Name;

                try
                {
                    //Set the config values
                    if (hashTable[name] != null)
                    {
                        ChoType.SetMemberValue(configObject, memberInfo.Name, hashTable[name]);
                    }
                    //Set default values
                    else if (memberInfoAttribute.DefaultValue != null)
                    {
                        ChoType.SetMemberValue(configObject, memberInfo.Name, memberInfoAttribute.DefaultValue);
                    }
                }
                catch (Exception ex)
                {
                    if (IgnoreError)
                    {
                        SetMemberError(configObject, memberInfo.Name, String.Format(Resources.ConfigConstructMsg, ChoString.ToString(hashTable[name]), ex.Message));
                    }
                    else
                    {
                        throw new ChoConfigurationConstructionException(String.Format(Resources.ConfigConstructExceptionMsg, ChoString.ToString(hashTable[name]), configObject.GetType().Name,
                                                                                      memberInfo.Name), ex);
                    }
                }

                //try
                //{
                //    //Validate the member with associated attributes
                //    foreach (IChoMemberValidator memberValidator in ChoType.GetMemberAttributesByBaseInterface(memberInfo, typeof(IChoMemberValidator)))
                //    {
                //        memberValidator.Validate(configObject, memberInfo);
                //    }
                //    foreach (ChoConfigurationValidatorAttribute memberValidator in ChoType.GetMemberAttributesByBaseInterface(memberInfo, typeof(ChoConfigurationValidatorAttribute)))
                //    {
                //        if (memberValidator.ValidatorInstance.CanValidate(ChoType.GetMemberType(memberInfo)))
                //            memberValidator.ValidatorInstance.Validate(ChoType.GetMemberValue(configObject, memberInfo.Name));
                //    }
                //}
                //catch (Exception ex)
                //{
                //    if (IgnoreError)
                //        SetMemberError(configObject, memberInfo.Name, String.Format(Resources.ConfigConstructValidationMsg, ChoString.ToString(ChoType.GetMemberValue(configObject, memberInfo.Name)),
                //            ex.Message));
                //    else
                //        throw new ChoConfigurationConstructionException(String.Format(Resources.ConfigConstructValidationExceptionMsg, ChoString.ToString(ChoType.GetMemberValue(configObject, memberInfo.Name))), ex);
                //}
            }

            _configSection.ConfigurationChangeWatcher.StartWatching();

            //Print the output to file
            TraceOutput(configObject);
        }
        public static string ToString(object configObject)
        {
            if (configObject == null)
            {
                return(String.Empty);
            }

            string configObjectString = ChoObject.ToString(configObject);

            ChoConfigurationElementMapAttribute configurationElementMap = ChoType.GetAttribute(configObject.GetType(), typeof(ChoConfigurationElementMapAttribute)) as ChoConfigurationElementMapAttribute;

            if (configurationElementMap == null)
            {
                return(configObjectString);
            }
            else if (configObjectString == configObject.GetType().FullName)
            {
                ChoStringMsgBuilder msg = new ChoStringMsgBuilder(configurationElementMap.Description);

                MemberInfo[] memberInfos = ChoType.GetMembers(configObject.GetType(), typeof(ChoMemberInfoAttribute));
                if (memberInfos == null || memberInfos.Length == 0)
                {
                    msg.AppendLine(ChoStringMsgBuilder.Empty);
                }
                else
                {
                    string errMsg;
                    foreach (MemberInfo memberInfo in memberInfos)
                    {
                        errMsg = ChoType.GetAttributeNameParameterValue(configObject.GetType(), memberInfo.Name, typeof(ChoMemberInfoAttribute), "ErrMsg") as string;
                        if (errMsg == null)
                        {
                            msg.AppendFormatLine("{0}: {1}", memberInfo.Name, ChoType.GetMemberValue(configObject, memberInfo.Name));
                        }
                        else
                        {
                            msg.AppendFormatLine("{0}: {1} [ERROR: {2}]", memberInfo.Name, ChoType.GetMemberValue(configObject, memberInfo.Name), errMsg);
                        }
                    }
                }
                msg.AppendNewLine();
                return(msg.ToString());
            }
            else
            {
                StringBuilder msg = new StringBuilder(configObjectString);

                MemberInfo[]  memberInfos = ChoType.GetMembers(configObject.GetType(), typeof(ChoMemberInfoAttribute));
                List <string> errMsgs     = new List <string>();
                if (memberInfos != null && memberInfos.Length >= 0)
                {
                    string errMsg;
                    foreach (MemberInfo memberInfo in memberInfos)
                    {
                        errMsg = ChoType.GetAttributeNameParameterValue(configObject.GetType(), memberInfo.Name, typeof(ChoMemberInfoAttribute), "ErrMsg") as string;
                        if (errMsg != null)
                        {
                            errMsgs.Add(String.Format("{0}: {1}", memberInfo.Name, errMsg));
                        }
                    }
                }

                if (errMsgs.Count > 0)
                {
                    ChoStringMsgBuilder errReport = new ChoStringMsgBuilder("Following errors produced while construction");

                    foreach (string errMsg in errMsgs)
                    {
                        errReport.AppendFormatLine(errMsg);
                    }

                    msg.AppendLine(errReport.ToString());
                }

                return(msg.ToString());
            }
        }