public override int GetHashCode()
        {
            if (KeyValuePair.IsNullOrEmpty())
            {
                return(0);
            }

            return((int)KeyValuePair.Select(kvp => kvp.Key.GetHashCode() ^ kvp.Value.GetHashCode()).Aggregate((x, y) => x ^ y));
        }
        /// <summary>
        /// Is Values in MyDictionary is the same as some collection
        /// </summary>
        public static bool ContentsMatchValues <T1, T2>(this IDictionary <T1, T2> source, IEnumerable <T2> check)
        {
            if (source.IsNullOrEmpty() && check.IsNullOrEmpty())
            {
                return(true);
            }
            if (source.IsNullOrEmpty() || check.IsNullOrEmpty())
            {
                return(false);
            }

            return(source.Values.ContentsMatch(check));
        }
示例#3
0
        private bool GetFolderIsCanceled(string path)
        {
            bool result = false;

            if (path.IsNullOrEmpty())
            {
                return(result);
            }

            ///Check is cancel for every folder
            lock (lockListObj)
            {
                if (allScanPathDic.IsNullOrEmpty())
                {
                    result = true;
                }

                string folderPath = GetPathWithDirSeparatorChar(path);

                foreach (var kv in allScanPathDic)
                {
                    if (kv.Value)
                    {
                        continue;
                    }

                    if (kv.Key == path)
                    {
                        result = !kv.Value;
                        break;
                    }
                    else
                    {
                        string tempPath = GetPathWithDirSeparatorChar(kv.Key);
                        //if parent is canceled
                        if (folderPath.StartsWith(tempPath) && !kv.Value)
                        {
                            result = !kv.Value;
                            break;
                        }
                    }
                }
            }
            //LogHelper.DebugFormat("GetIsCanceled path:{0}, isCanceled:{1} --/", path, result);
            ///Maybe is canceled , the cache is cleared
            ///so add isCanceled
            return(result || isCanceled);
        }
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value == null)
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return(JsonConvert.SerializeObject(dictionary));
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger("ConvertArgumentsToJson").Warn(ex.ToString());
                return("{}");
            }
        }
        public async Task HandleTemplateVersionChanged(SpecificationVersion previousSpecificationVersion,
                                                       SpecificationVersion specificationVersion,
                                                       IDictionary <string, string> assignedTemplateIds,
                                                       Reference user,
                                                       string correlationId)
        {
            Guard.ArgumentNotNull(previousSpecificationVersion, nameof(previousSpecificationVersion));

            if (assignedTemplateIds.IsNullOrEmpty())
            {
                //this is a temporary branch to keep the existing edit call working before the UI catches up
                return;
            }

            string specificationId = previousSpecificationVersion.SpecificationId;
            string fundingPeriodId = previousSpecificationVersion.FundingPeriod.Id;

            foreach (KeyValuePair <string, string> assignedTemplateId in assignedTemplateIds)
            {
                string fundingStreamId   = assignedTemplateId.Key;
                string templateVersionId = assignedTemplateId.Value;

                if (!previousSpecificationVersion.TemplateVersionHasChanged(fundingStreamId, templateVersionId))
                {
                    LogInformation($"FundingStream {fundingStreamId} template version id {templateVersionId} not changed in specification {specificationId}.");

                    continue;
                }

                LogInformation($"FundingStream {fundingStreamId} template version id {templateVersionId} changed for specification {specificationId}.");

                await AssignTemplateWithSpecification(specificationVersion, templateVersionId, fundingStreamId, fundingPeriodId);
                await QueueAssignTemplateCalculationsJob(user, correlationId, specificationId, fundingStreamId, fundingPeriodId, templateVersionId);
            }
        }
示例#6
0
 public static void IsNullOrEmpty <T, TValue>(IDictionary <T, TValue> guardValue, string errorMessage)
 {
     if (guardValue.IsNullOrEmpty())
     {
         throw new ArgumentException(errorMessage);
     }
 }
        public T CreateNew <T>(IDictionary <string, object> parameters) where T : class, new()
        {
            var value = new T();

            var properties = value.GetType().GetProperties();

            foreach (var property in properties)
            {
                object propertyValue;

                if (!parameters.IsNullOrEmpty() && parameters.SafeGet(property.Name).IsNotNull())
                {
// ReSharper disable PossibleNullReferenceException
                    propertyValue = parameters[property.Name];
// ReSharper restore PossibleNullReferenceException
                }
                else
                {
                    var key = property.PropertyType;

                    propertyValue = Mappings.ContainsKey(key)
                        ? Mappings[key]()
                        : null;
                }

                property.SetValue(value, propertyValue, null);
            }

            return(value);
        }
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null && IgnoredTypesForSerializationOnAuditLogging.Any(t => t.IsInstanceOfType(argument.Value)))
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return(AuditingHelper.Serialize(dictionary));
            }
            catch (Exception ex)
            {
                Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName);
                Logger.Warn(ex.ToString(), ex);
                return("{}");
            }
        }
示例#9
0
        /// <summary>
        /// 应用模块服务
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public override void UsePack(IServiceProvider provider)
        {
            IDictionary <string, OsharpDbContextOptions> dbContextOptions = provider.GetOSharpOptions().DbContexts;

            if (!_optionsValidated)
            {
                if (dbContextOptions.IsNullOrEmpty())
                {
                    throw new OsharpException("配置文件中找不到数据上下文的配置,请配置OSharp:DbContexts节点");
                }

                foreach (var options in dbContextOptions)
                {
                    string msg = options.Value.Error;
                    if (msg != string.Empty)
                    {
                        throw new OsharpException($"数据库“{options.Key}”配置错误:{msg}");
                    }
                }

                _optionsValidated = true;
            }

            if (dbContextOptions.Values.All(m => m.DatabaseType != DatabaseType))
            {
                return;
            }

            IEntityManager manager = provider.GetRequiredService <IEntityManager>();

            manager.Initialize();
            IsEnabled = true;
        }
示例#10
0
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null)
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return(JsonConvert.SerializeObject(dictionary, Formatting.Indented,
                                                   new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                }));
            }
            catch
            {
                return("{}");
            }
        }
示例#11
0
 private Controller()
 {
     loginInformation       = new LoginInformation();
     serielNumberRepository = new SerielNumberRepository();
     putDownStream          = new FileDownStream();
     getFileUpStream        = new FileUpStream();
     serielNumberGenerator  = new SerielNumberGenerator();
     logins            = new Dictionary <string, string>();
     lotteryDictionary = new Dictionary <string, bool>();
     submissionList    = new List <Submission>();
     if (getFileUpStream.isFilePresent(0).Result)
     {
         submissionList = getFileUpStream.LoadSubmissionsFromFileAsync().Result;
     }
     if (getFileUpStream.isFilePresent(1).Result)
     {
         lotteryDictionary = serielNumberRepository.SerielNumbersFromFile().Result;
     }
     if (lotteryDictionary.IsNullOrEmpty())
     {
         Task.Run(() => lotteryDictionary = serielNumberGenerator.GenerateSerielNumberDictionary(serialsAmount));
     }
     if (getFileUpStream.isFilePresent(2).Result)
     {
         logins = loginInformation.LoadLoginsToDictinary().Result;
     }
     if (logins.IsNullOrEmpty())
     {
         logins.Add("admin", "admin");
     }
 }
示例#12
0
        public static string WriteDict_2_ToBriefString <K, V>(this IDictionary <K, V> items)
            where K : struct
            where V : IObjectToBriefString
        {
            if (items == null)
            {
                return("NULL");
            }

            var nextN           = 4u;
            var nextNSpaces     = Spaces(nextN);
            var nextNextN       = nextN + 4;
            var nextNextNSpaces = Spaces(nextNextN);
            var nextNextNextN   = nextNextN + 4;

            var sb = new StringBuilder();

            sb.AppendLine("Begin Dictionary");

            if (!items.IsNullOrEmpty())
            {
                foreach (var item in items)
                {
                    sb.AppendLine($"{nextNSpaces}Begin Item");
                    sb.AppendLine($"{nextNextNSpaces}Key = {item.Key}");
                    sb.AppendLine($"{nextNextNSpaces}Begin Value");
                    sb.Append(item.Value.ToBriefString(nextNextNextN));
                    sb.AppendLine($"{nextNextNSpaces}End Value");
                    sb.AppendLine($"{nextNSpaces}End Item");
                }
            }

            sb.AppendLine("End Dictionary");
            return(sb.ToString());
        }
示例#13
0
        public static object ToEntity(this IDictionary <string, object> source, Type type)
        {
            if (source.IsNullOrEmpty())
            {
                return(null);
            }
            FastType fastType = FastType.Get(type);
            var      instance = Activator.CreateInstance(type);

            foreach (var p in fastType.Setters)
            {
                if (p.Name.IsNullOrEmpty())
                {
                    continue;
                }
                if (source.Keys.Contains(p.Name))
                {
                    p.SetValue(instance, source[p.Name].ConvertToType(p.Type));
                }
            }
            var temp = instance as IExtProperty;

            if (temp != null)
            {
                var keys = source.Keys.Where(o => o.StartsWith(SysConfig.ExtFieldName, StringComparison.OrdinalIgnoreCase));
                if (!keys.IsNullOrEmpty())
                {
                    foreach (var key in keys)
                    {
                        temp.Properties[key] = source[key];
                    }
                }
            }
            return(instance);
        }
        /// <summary>
        /// Sets the relationships on a parsed resource.
        /// </summary>
        /// <param name="resource">
        /// The parsed resource.
        /// </param>
        /// <param name="relationshipValues">
        /// Relationships and their values, as in the serialized content.
        /// </param>
        /// <param name="relationshipAttributes">
        /// Exposed relationships for <paramref name="resource" />.
        /// </param>
        protected virtual IIdentifiable SetRelationships(IIdentifiable resource, IDictionary <string, RelationshipEntry> relationshipValues,
                                                         IReadOnlyCollection <RelationshipAttribute> relationshipAttributes)
        {
            ArgumentGuard.NotNull(resource, nameof(resource));
            ArgumentGuard.NotNull(relationshipAttributes, nameof(relationshipAttributes));

            if (relationshipValues.IsNullOrEmpty())
            {
                return(resource);
            }

            foreach (RelationshipAttribute attr in relationshipAttributes)
            {
                bool relationshipIsProvided = relationshipValues.TryGetValue(attr.PublicName, out RelationshipEntry relationshipData);

                if (!relationshipIsProvided || !relationshipData.IsPopulated)
                {
                    continue;
                }

                if (attr is HasOneAttribute hasOneAttribute)
                {
                    SetHasOneRelationship(resource, hasOneAttribute, relationshipData);
                }
                else if (attr is HasManyAttribute hasManyAttribute)
                {
                    SetHasManyRelationship(resource, hasManyAttribute, relationshipData);
                }
            }

            return(resource);
        }
示例#15
0
 /// <summary>
 /// Заменяет в указанной входной строке все указанные её подстроки на соответствующие им новые подстроки
 /// </summary>
 /// <param name="Input">Входная строка, в которой требуется заменить содержимое определённых подстрок. Не может быть NULL или пустой.</param>
 /// <param name="ReplacementList">Список замен, которые необходимо произвести во входной строке. 
 /// Ключ - это подстрока для замены, которая обязательно должна иметь в качестве базовой строки указанную входную строку.  
 /// Значение - это новая строка, которая должна быть внедрена во входную строку вместо соответствующей ей в ключе подстроки на те же самые позиции. 
 /// Если новая строка в значении является NULL или пустой, произойдёт фактически вырезание из входной строки подстроки, без замены содержимого на новое. 
 /// Если список замен является NULL или пустым, будет возвращена входная строка без изменений.</param>
 /// <returns>Новый экземпляр строки, если замены произошли, или входная строка, если список замен пуст</returns>
 /// <exception cref="ArgumentNullException"></exception>
 /// <exception cref="ArgumentException"></exception>
 public static String ReplaceAll(String Input, IDictionary<Substring, String> ReplacementList)
 {
     if (Input == null) { throw new ArgumentNullException("Input"); }
     if (Input.Length == 0) { throw new ArgumentException("Входная строка не может быть пустой", "Input"); }
     if (ReplacementList.IsNullOrEmpty()) { return Input; }
     Substring[] substrings = ReplacementList.Keys.ToArray();
     if (substrings.Length > 1 && Substring.HaveCommonBaseString(substrings) == false)
     {
         throw new ArgumentException("Не все подстроки из списка замен имеют в качестве базовой строки указанную входную строку", "ReplacementList");
     }
     StringBuilder output = new StringBuilder(Input.Length);
     Int32 offset = 0;
     Substring previous = null;
     foreach (KeyValuePair<Substring, string> onePairToReplace in ReplacementList)
     {
         if (previous != null && Substring.AreIntersecting(previous, onePairToReplace.Key) == true)
         {
             throw new ArgumentException("В списке замен присутствуют пересекающиеся подстроки", "ReplacementList");
         }
         output.Append(Input.Substring(offset, onePairToReplace.Key.StartIndex - offset));
         output.Append(onePairToReplace.Value);
         offset = onePairToReplace.Key.EndIndex + 1;
         previous = onePairToReplace.Key;
     }
     output.Append(Input.Substring(offset));
     return output.ToString();
 }
示例#16
0
 public BusinessOperationConfigCollection(IDictionary <string, IBusinessOperationConfig <TContainer> > configs)
 {
     if (!configs.IsNullOrEmpty())
     {
         configs.ForEach(config => this.New(config.Key, config.Value));
     }
 }
示例#17
0
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null && _configuration.IgnoredTypes.Any(t => t.IsInstanceOfType(argument.Value)))
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return(_auditSerializer.Serialize(dictionary));
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex.ToString(), ex);
                return("{}");
            }
        }
示例#18
0
        public static bool HasGeneric(this IEnumerable <Resource> inventory, IDictionary <ResourceType, int> requiredGeneric)
        {
            if (requiredGeneric.IsNullOrEmpty())
            {
                return(true);
            }

            var inv = inventory.ToList();

            if (!inv.Any())
            {
                return(false);
            }

            var keyToCheck = requiredGeneric.First().Key;
            var res        = requiredGeneric.ToDictionary(e => e.Key, e => e.Value);

            res[keyToCheck] -= 1;
            if (res[keyToCheck] == 0)
            {
                res.Remove(keyToCheck);
            }

            foreach (var item in inv.Where(x => (x.Type & keyToCheck) == keyToCheck).ToList())
            {
                inv.Remove(item);
                if (inv.HasGeneric(res))
                {
                    return(true);
                }
                inv.Add(item);
            }
            return(false);
        }
        /// <summary>
        /// Generic helper method to retreive a value
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="pattern"></param>
        /// <param name="index"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T GetValue <T>(IDictionary <string, T> collection, string pattern, int index, T defaultValue)
        {
            if (collection.IsNullOrEmpty() || index < 0)
            {
                return(defaultValue);
            }

            foreach (var kv in collection)
            {
                var key = kv.Key.Replace(pattern, string.Empty);

                if (string.IsNullOrEmpty(key))
                {
                    return(defaultValue);
                }

                int keyIndex;

                if (!int.TryParse(key, out keyIndex))
                {
                    continue;
                }

                if (keyIndex.Equals(index))
                {
                    return(kv.Value);
                }
            }

            return(defaultValue);
        }
示例#20
0
        public static bool HasUnique(this IEnumerable <Resource> inventory, IDictionary <Resource, int> requiredUnique, out IEnumerable <Resource> remaining)
        {
            var inv = inventory.ToList();

            remaining = inv;

            if (requiredUnique.IsNullOrEmpty())
            {
                return(true);
            }

            foreach (var resource in requiredUnique)
            {
                for (int i = 0; i < resource.Value; i++)
                {
                    if (!inv.Contains(resource.Key))
                    {
                        return(false);
                    }
                    inv.Remove(resource.Key);
                }
            }

            return(true);
        }
示例#21
0
 public void BindingsConfigurations()
 {
     if (!bindings.IsNullOrEmpty() && !ignoreMembers.IsNullOrEmpty())
     {
         bindings.RemoveAllIfContains(ignoreMembers);
     }
 }
示例#22
0
        private static Expression <Func <T, bool> > BuildQueryPredicate(IDictionary <string, object> propertyEqualsFilter)
        {
            if (propertyEqualsFilter.IsNullOrEmpty())
            {
                throw new ArgumentException("属性筛选器字典不能为空。", nameof(propertyEqualsFilter));
            }
            var parameter = Expression.Parameter(typeof(T), "o");
            BinaryExpression binaryExpression = null;

            foreach (var propertyValue in propertyEqualsFilter)
            {
                PropertyInfo propertyInfo = typeof(T).GetTypeInfo().DeclaredProperties
                                            .FirstOrDefault(p => propertyValue.Key.Equals(p.Name, StringComparison.Ordinal) && p.CanRead && !p.GetMethod.IsStatic);

                if (propertyInfo == null)
                {
                    throw new ArgumentException($"属性筛选字典中包含了 {propertyValue.Key} 键, 但是类型 {typeof(T).Name} 中找不到名为 {propertyValue.Key} 的属性。", nameof(propertyEqualsFilter));
                }
                var propertyExpression = Expression.MakeMemberAccess(parameter, propertyInfo);
                var valueExpression    = propertyValue.Value == null?Expression.Constant(null) : Expression.Constant(propertyValue.Value, propertyInfo.PropertyType);

                var equalExpression = Expression.Equal(propertyExpression, valueExpression);
                if (binaryExpression == null)
                {
                    binaryExpression = equalExpression;
                }
                else
                {
                    binaryExpression = Expression.And(binaryExpression, equalExpression);
                }
            }
            Expression <Func <T, bool> > predicate = (Expression <Func <T, bool> >)Expression.Lambda(binaryExpression, parameter);

            return(predicate);
        }
示例#23
0
        public IFormatter Select(FilterType type)
        {
            Guard.Against <ArgumentException>(formatters.IsNullOrEmpty(), "Не определен список форматтеров");
            //Guard.Against<ArgumentException>(!formatters.ContainsKey(type), $"Отсутствует форматер для {type}");

            return(!formatters.ContainsKey(type) ? defaultFormatter : formatters[type]);
        }
示例#24
0
        /// <summary>
        /// Compare 2 dictionnaire entre eux. Comparaison des clés et des valeurs
        /// </summary>
        public static bool DictionaryEqual <TKey, TValue>(this IDictionary <TKey, TValue> first, IDictionary <TKey, TValue> second)
        {
            if (first == second)
            {
                return(true);
            }
            if (first.IsNullOrEmpty() && second.IsNullOrEmpty())
            {
                return(true);
            }
            if ((first == null) || (second == null))
            {
                return(false);
            }
            if (first.Count() != second.Count())
            {
                return(false);
            }

            var comparer = EqualityComparer <TValue> .Default;

            foreach (KeyValuePair <TKey, TValue> kvp in first)
            {
                TValue secondValue;
                if (!second.TryGetValue(kvp.Key, out secondValue))
                {
                    return(false);
                }
                if (!comparer.Equals(kvp.Value, secondValue))
                {
                    return(false);
                }
            }
            return(true);
        }
示例#25
0
 private void CheckValidIndex(int i)
 {
     if (_results.IsNullOrEmpty() || !_results.ContainsKey(i))
     {
         throw new IndexOutOfRangeException("The specified index does not exist.");
     }
 }
示例#26
0
        protected virtual string SerializeConvertArguments(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null && Options.IgnoredTypes.Any(t => t.IsInstanceOfType(argument.Value)))
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return(AuditSerializer.Serialize(dictionary));
            }
            catch (Exception ex)
            {
                Logger.LogException(ex, LogLevel.Warning);
                return("{}");
            }
        }
示例#27
0
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    dictionary[argument.Key] = argument.Value;
                }

                return(JsonConvert.SerializeObject(
                           dictionary,
                           new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }));
            }
            catch (Exception ex)
            {
                Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName);
                Logger.Warn(ex.ToString(), ex);
                return("{}");
            }
        }
 public ChoiceRuleEvaluator(IDictionary <string, IChoiceRule <TEntity, TChoiceEntity> > rules)
 {
     if (!rules.IsNullOrEmpty())
     {
         rules.ForEach(rule => AddRule(rule.Key, rule.Value));
     }
 }
示例#29
0
        private string ConvertArgumentsToJson(IDictionary <string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return("{}");
                }

                var dictionary = new Dictionary <string, object>();

                foreach (var argument in arguments)
                {
                    dictionary[argument.Key] = argument.Value;
                }
                var settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver      = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                };
                return(JsonConvert.SerializeObject(dictionary, settings));
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.ToString(), ex);
                return("{}");
            }
        }
示例#30
0
 public static void ClearCache()
 {
     if (!JsonFolderCache.IsNullOrEmpty())
     {
         JsonFolderCache.Clear();
     }
 }
示例#31
0
        internal void Import(ExportablePlayerProfileCI exportable)
        {
            if (exportable == null)
            {
                throw new ArgumentNullException(nameof(exportable));
            }

            Names = exportable.Name.IsNullOrEmpty() ? new Dictionary <CultureInfo, string>() : new Dictionary <CultureInfo, string>(exportable.Name);
            if (!Names.IsNullOrEmpty())
            {
                _fetchedCultures = new List <CultureInfo>(exportable.Name.Keys);
                _primaryCulture  = exportable.Name.Keys.First();
            }
            _nationalities = exportable.Nationalities.IsNullOrEmpty() ? new Dictionary <CultureInfo, string>() : new Dictionary <CultureInfo, string>(exportable.Nationalities);
            _type          = exportable.Type;
            _dateOfBirth   = exportable.DateOfBirth;
            _height        = exportable.Height;
            _weight        = exportable.Weight;
            _abbreviation  = exportable.Abbreviation;
            _gender        = exportable.Gender;
            _competitorId  = string.IsNullOrEmpty(exportable.CompetitorId) ? null : URN.Parse(exportable.CompetitorId);
            CountryCode    = exportable.CountryCode;
            FullName       = exportable.FullName;
            Nickname       = exportable.Nickname;
        }
        public static void AddAttributes(this HtmlTextWriter writer, IDictionary<string, object> attributes)
        {
            Guard.IsNotNull(writer, "writer");

            if (!attributes.IsNullOrEmpty())
            {
                foreach (KeyValuePair<string, object> attribute in attributes)
                {
                    writer.AddAttribute(attribute.Key, attribute.Value.ToString(), true);
                }
            }
        }
示例#33
0
        public void SetProcessInformationFrom(IDictionary<string, IList<int>> iisWorkerProcessData)
        {
            if (iisWorkerProcessData.IsNullOrEmpty())
            {
                return;
            }

            ForAllInstances((inst) =>
                {
                    string appPoolName = inst.Staged; // TODO: we have to "know" that this is the app pool name
                    IList<int> tmp;
                    if (iisWorkerProcessData.TryGetValue(appPoolName, out tmp))
                    {
                        foreach (int pid in tmp)
                        {
                            try
                            {
                                inst.AddWorkerProcess(Process.GetProcessById(pid));
                            }
                            catch { }
                        }
                    }
                });
        }
示例#34
0
        private string ConvertArgumentsToJson(IDictionary<string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return "{}";
                }

                var dictionary = new Dictionary<string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null && _ignoredTypesForSerialization.Any(t => t.IsInstanceOfType(argument.Value)))
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;                        
                    }
                }

                return JsonConvert.SerializeObject(
                    dictionary,
                    new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    });
            }
            catch (Exception ex)
            {
                Logger.Warn("Could not serialize arguments for method: " + _auditInfo.ServiceName + "." + _auditInfo.MethodName);
                Logger.Warn(ex.ToString(), ex);
                return "{}";
            }
        }
        private string ConvertArgumentsToJson(IDictionary<string, object> arguments)
        {
            try
            {
                if (arguments.IsNullOrEmpty())
                {
                    return "{}";
                }

                var dictionary = new Dictionary<string, object>();

                foreach (var argument in arguments)
                {
                    if (argument.Value != null && IgnoredTypesForSerializationOnAuditLogging.Any(t => t.IsInstanceOfType(argument.Value)))
                    {
                        dictionary[argument.Key] = null;
                    }
                    else
                    {
                        dictionary[argument.Key] = argument.Value;
                    }
                }

                return AuditingHelper.Serialize(dictionary);
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.ToString(), ex);
                return "{}";
            }
        }
 /// <summary>
 /// The anything to trace.
 /// </summary>
 /// <param name="option">
 /// The options. 
 /// </param>
 /// <param name="workflowTraceOptions">
 /// The trace options 
 /// </param>
 /// <param name="annotations">
 /// The annotations. 
 /// </param>
 /// <param name="arguments">
 /// The arguments. 
 /// </param>
 /// <param name="variables">
 /// The variables. 
 /// </param>
 /// <param name="data">
 /// The data. 
 /// </param>
 /// <returns>
 /// true if there is anything to trace. 
 /// </returns>
 private static bool AnythingToTrace(
     TrackingOption option, 
     WorkflowTraceOptions workflowTraceOptions, 
     IDictionary<string, string> annotations, 
     IDictionary<string, object> arguments, 
     IDictionary<string, object> variables, 
     IDictionary<string, object> data)
 {
     return option.HasFlag(TrackingOption.InstanceId)
            || option.HasFlag(TrackingOption.Time)
            || workflowTraceOptions.HasFlag(WorkflowTraceOptions.ShowEmptyCollections)
            || (option.HasFlag(TrackingOption.Annotations) && !annotations.IsNullOrEmpty())
            || (option.HasFlag(TrackingOption.Arguments) && !arguments.IsNullOrEmpty())
            || (option.HasFlag(TrackingOption.Variables) && !variables.IsNullOrEmpty())
            || (option.HasFlag(TrackingOption.Data) && !data.IsNullOrEmpty());
 }