Пример #1
0
        internal static ISerializable Deserialize(
            Stream source,
            Dictionary <int, Func <ISerializable> > codeToConstuctorMapping,
            string formatExceptionMessage)
        {
            source.ThrowIfNull(nameof(source));
            codeToConstuctorMapping.ThrowIfNull(nameof(codeToConstuctorMapping));
            formatExceptionMessage.ThrowIfNull(nameof(formatExceptionMessage));

            var buffer = new byte[sizeof(int)];

            source.Read(buffer, 0, buffer.Length);
            var objectKey = BitConverter.ToInt32(buffer, 0);

            if (!codeToConstuctorMapping.TryGetValue(objectKey, out Func <ISerializable> objConstructor))
            {
                throw new FormatException(formatExceptionMessage);
            }

            ISerializable obj = objConstructor();

            obj.GetSerializer().Deserialize(source);

            return(obj);
        }
Пример #2
0
        public DictionaryManager(LanguageType languageType,
                                 Dictionary <Nouns, OneWordWeightDictionary> nouns,
                                 Dictionary <Verbs, MultiWordWeightDictionary> verbs,
                                 Dictionary <Adjectives, OneWordWeightDictionary> adjectives,
                                 Dictionary <Adverbs, OneWordWeightDictionary> adverbs,
                                 Dictionary <Collocations, MultiWordWeightDictionary> collocations,
                                 Dictionary <Nouns, MultiWordWeightDictionary> ners
                                 )
        {
            nouns.ThrowIfNull("nouns");
            verbs.ThrowIfNull("verbs");
            adjectives.ThrowIfNull("adjectives");
            adverbs.ThrowIfNull("adverbs");
            collocations.ThrowIfNull("collocations");
            ners.ThrowIfNull("ners");


            this.LanguageType = languageType;
            _Nouns            = new Dictionary <Nouns, OneWordWeightDictionary>(nouns);
            _Verbs            = new Dictionary <Verbs, MultiWordWeightDictionary>(verbs);
            _Adjectives       = new Dictionary <Adjectives, OneWordWeightDictionary>(adjectives);
            _Adverbs          = new Dictionary <Adverbs, OneWordWeightDictionary>(adverbs);
            _Collocations     = new Dictionary <Collocations, MultiWordWeightDictionary>(collocations);
            _Ners             = new Dictionary <Nouns, MultiWordWeightDictionary>(ners);
        }
Пример #3
0
        /// <summary>
        /// Append the "$metadata" identifier to the property values, which helps the service identify the patch as a component update.
        /// </summary>
        /// <param name="propertyKeyValuePairs">The dictionary of property key values pairs to update to.</param>
        internal static void AddComponentUpdateIdentifier(this Dictionary <string, object> propertyKeyValuePairs)
        {
            propertyKeyValuePairs.ThrowIfNull(nameof(propertyKeyValuePairs));

            const string metadataKey = "$metadata";

            propertyKeyValuePairs.Add(metadataKey, new object());
        }
 public static string PrettyPrint <TKey, TValue>(
     this Dictionary <TKey, TValue> dictionary,
     char separator     = EnumerableExtensions.PrettyPrintDefaultSeparator,
     uint minSeparation = EnumerableExtensions.PrettyPrintMinSeparation)
 {
     dictionary.ThrowIfNull(nameof(dictionary));
     return(dictionary.AsEnumerable().PrettyPrint(separator, minSeparation));
 }
Пример #5
0
        internal GremlinQuery(StringBuilder queryBuilder, Dictionary <string, object> arguments)
        {
            queryBuilder.ThrowIfNull(nameof(queryBuilder));
            arguments.ThrowIfNull(nameof(arguments));

            _queryBuilder = queryBuilder;
            Arguments     = arguments;
        }
Пример #6
0
        public void AddCookie(HttpCookie cookie)
        {
            cookies.ThrowIfNull(nameof(cookies));

            if (ContainsCookie(cookie.Key))
            {
                throw new InternalServerErrorException();
            }

            cookies.Add(cookie.Key, cookie);
        }
Пример #7
0
        public StateMachineBuilder(
            TStatefulTask initialTask,
            TStateId initialStateId,
            Dictionary <TStateId, TStatefulTask> transitionsTable)
        {
            InitialTask       = initialTask.ThrowIfNull(nameof(initialTask));
            StateId           = initialStateId;
            _transitionsTable = transitionsTable.ThrowIfNull(nameof(transitionsTable));

            // Add initial stateful task.
            _transitionsTable.TryAdd(StateId, InitialTask);
        }
Пример #8
0
        private void AddExceptionIfFound(XElement entryEvent, Dictionary <string, object> metaData, XNamespace @namespace)
        {
            entryEvent.ThrowIfNull(nameof(entryEvent));

            metaData.ThrowIfNull(nameof(metaData));

            var exceptionElement = entryEvent.Element(@namespace + "exception");

            if (exceptionElement != null)
            {
                metaData["Exception"] = exceptionElement.Value;
            }
        }
Пример #9
0
        /// <summary>
        /// Serialize dictionary holding custom properties.
        /// </summary>
        /// <param name="customProperties">Custom properties dictionary.</param>
        /// <returns></returns>
        internal string Convert(Dictionary <string, object> customProperties)
        {
            customProperties.ThrowIfNull(nameof(customProperties));
            JObject rootObject = new JObject();

            foreach (KeyValuePair <string, object> customProperty in customProperties)
            {
                rootObject.Add(
                    customProperty.Key,
                    JToken.FromObject(customProperty.Value));
            }

            return(JsonConvert.SerializeObject(rootObject));
        }
        /// <summary>
        /// Include a replace component operation.
        /// Learn more about managing digital twins here <see href="https://docs.microsoft.com/azure/iot-pnp/howto-manage-digital-twin"/>.
        /// </summary>
        /// <remarks>
        /// This utility appends the "$metadata" identifier to the property values,
        /// which helps the service identify this as a component update, and not a root-level property update.
        /// <para>
        /// The component patch should be in the following format:
        /// [
        ///     {
        ///         "op": "replace",
        ///         "path": "/sampleComponentName",
        ///         "value": {
        ///             "samplePropertyName": 20,
        ///             "$metadata": {}
        ///         }
        ///     }
        /// ]
        /// </para>
        /// </remarks>
        /// <param name="path">The path to the component to be updated.</param>
        /// <param name="propertyValues">The dictionary of property key values pairs to update to.</param>
        public void AppendReplaceComponentOp(string path, Dictionary <string, object> propertyValues)
        {
            propertyValues.ThrowIfNull(nameof(propertyValues));
            propertyValues.AddComponentUpdateIdentifier();

            var op = new Dictionary <string, object>
            {
                { Op, Replace },
                { Path, path },
                { Value, propertyValues },
            };

            _ops.Add(op);
        }
        /// <summary>
        /// Used to create the metadata type instance for a corresponding Box File Id.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="metadata"></param>
        /// <param name="typeInstance"></param>
        /// <returns>A BoxMetadata object that includes key:value pairs defined by a user or application. 
        /// If the properties instance already exists, a 409 HTTP status code of conflict will be returned and the update method should be used</returns>
        public async Task<BoxMetadata> CreateMetadata(string id, Dictionary<string,string> metadata, string typeInstance = DefaultTypeInstance)
        {
            id.ThrowIfNullOrWhiteSpace("id");
            metadata.ThrowIfNull("metadata");

            BoxRequest request = new BoxRequest(new Uri(Constants.BoxApiUriString + string.Format(CultureInfo.InvariantCulture, MetadataEndpointPath, id, typeInstance)))
                .Method(RequestMethod.Post);

            request.Payload = _converter.Serialize(metadata);
            request.ContentType = JsonContentType;

            IBoxResponse<BoxMetadata> response = await ToResponseAsync<BoxMetadata>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Used to create the metadata type instance for a corresponding Box File Id.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="metadata"></param>
        /// <param name="typeInstance"></param>
        /// <returns>A BoxMetadata object that includes key:value pairs defined by a user or application.
        /// If the properties instance already exists, a 409 HTTP status code of conflict will be returned and the update method should be used</returns>
        public async Task <BoxMetadata> CreateMetadata(string id, Dictionary <string, string> metadata, string typeInstance = DefaultTypeInstance)
        {
            id.ThrowIfNullOrWhiteSpace("id");
            metadata.ThrowIfNull("metadata");

            BoxRequest request = new BoxRequest(new Uri(Constants.BoxApiUriString + string.Format(CultureInfo.InvariantCulture, MetadataEndpointPath, id, typeInstance)))
                                 .Method(RequestMethod.Post);

            request.Payload     = _converter.Serialize(metadata);
            request.ContentType = JsonContentType;

            IBoxResponse <BoxMetadata> response = await ToResponseAsync <BoxMetadata>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
        public DictionaryManager(LanguageType languageType,
                                 Dictionary <DictionaryType, OneWordWeightDictionary> verbs,
                                 Dictionary <DictionaryType, MultiWordWeightDictionary> phrasis,
                                 Dictionary <DictionaryType, OneWordWeightDictionary> singleWords,
                                 Dictionary <DictionaryType, MultiWordWeightDictionary> multiWords)
        {
            verbs.ThrowIfNull("verbs");
            phrasis.ThrowIfNull("phrasis");
            singleWords.ThrowIfNull("singleWords");
            multiWords.ThrowIfNull("multiWords");

            LanguageType = languageType;
            _Verbs       = new Dictionary <DictionaryType, OneWordWeightDictionary>(verbs);
            _Phrasis     = new Dictionary <DictionaryType, MultiWordWeightDictionary>(phrasis);
            _SingleWords = new Dictionary <DictionaryType, OneWordWeightDictionary>(singleWords);
            _MultiWords  = new Dictionary <DictionaryType, MultiWordWeightDictionary>(multiWords);
        }
Пример #14
0
        internal static void Serialize(
            Stream destination,
            ISerializable obj,
            Dictionary <Type, int> typeToCodeMapping,
            string formatExceptionMessage)
        {
            destination.ThrowIfNull(nameof(destination));
            obj.ThrowIfNull(nameof(obj));
            typeToCodeMapping.ThrowIfNull(nameof(typeToCodeMapping));
            formatExceptionMessage.ThrowIfNull(nameof(formatExceptionMessage));

            if (!typeToCodeMapping.TryGetValue(obj.GetType(), out int value))
            {
                throw new FormatException(formatExceptionMessage);
            }

            var bytes = BitConverter.GetBytes(value);

            destination.Write(bytes, 0, bytes.Length);

            obj.GetSerializer().Serialize(destination);
        }
Пример #15
0
        /// <summary>
        /// Gets the time required to train all the prerequisites
        /// </summary>
        /// <param name="src">The source.</param>
        /// <param name="alreadyCountedList">The already counted list.</param>
        /// <param name="isCurrentlyTraining">if set to <c>true</c> [is currently training].</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">src or alreadyCountedList</exception>
        public static TimeSpan GetTotalTrainingTime(this IEnumerable <SkillLevel> src, Dictionary <Skill, Int64> alreadyCountedList,
                                                    ref bool isCurrentlyTraining)
        {
            src.ThrowIfNull(nameof(src));

            alreadyCountedList.ThrowIfNull(nameof(alreadyCountedList));

            TimeSpan result = TimeSpan.Zero;

            foreach (SkillLevel item in src)
            {
                Skill skill = item.Skill;
                isCurrentlyTraining |= skill.IsTraining;

                // Gets the number of points we're starting from
                Int64 fromPoints = skill.SkillPoints;
                if (alreadyCountedList.ContainsKey(skill))
                {
                    fromPoints = alreadyCountedList[skill];
                }

                // Gets the number of points we're targeting
                Int64 toPoints = skill.GetLeftPointsRequiredToLevel(item.Level);
                if (fromPoints < toPoints)
                {
                    result += skill.GetTimeSpanForPoints(toPoints - fromPoints);
                }

                // Updates the alreadyCountedList
                alreadyCountedList[skill] = Math.Max(fromPoints, toPoints);

                // Recursive
                if (fromPoints < toPoints)
                {
                    result += skill.Prerequisites.GetTotalTrainingTime(alreadyCountedList, ref isCurrentlyTraining);
                }
            }
            return(result);
        }
Пример #16
0
        /// <summary>
        /// Gets the time required to train all the prerequisites
        /// </summary>
        /// <param name="src">The source.</param>
        /// <param name="alreadyCountedList">The already counted list.</param>
        /// <param name="isCurrentlyTraining">if set to <c>true</c> [is currently training].</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">src or alreadyCountedList</exception>
        public static TimeSpan GetTotalTrainingTime(this IEnumerable<SkillLevel> src, Dictionary<Skill, Int64> alreadyCountedList,
            ref bool isCurrentlyTraining)
        {
            src.ThrowIfNull(nameof(src));

            alreadyCountedList.ThrowIfNull(nameof(alreadyCountedList));

            TimeSpan result = TimeSpan.Zero;
            foreach (SkillLevel item in src)
            {
                Skill skill = item.Skill;
                isCurrentlyTraining |= skill.IsTraining;

                // Gets the number of points we're starting from
                Int64 fromPoints = skill.SkillPoints;
                if (alreadyCountedList.ContainsKey(skill))
                    fromPoints = alreadyCountedList[skill];

                // Gets the number of points we're targeting
                Int64 toPoints = skill.GetLeftPointsRequiredToLevel(item.Level);
                if (fromPoints < toPoints)
                    result += skill.GetTimeSpanForPoints(toPoints - fromPoints);

                // Updates the alreadyCountedList
                alreadyCountedList[skill] = Math.Max(fromPoints, toPoints);

                // Recursive
                if (fromPoints < toPoints)
                    result += skill.Prerequisites.GetTotalTrainingTime(alreadyCountedList, ref isCurrentlyTraining);
            }
            return result;
        }
Пример #17
0
        public ThemesManager(Dictionary <ThemeType, Theme> themes)
        {
            themes.ThrowIfNull("themes");

            _Themes = new Dictionary <ThemeType, Theme>(themes);
        }
        public LanguagesManager(Dictionary <LanguageType, Language> languages)
        {
            languages.ThrowIfNull("languages");

            _Languages = new Dictionary <LanguageType, Language>(languages);
        }
 public SearchTemplateDescriptor <T> Params(Dictionary <string, object> paramDictionary)
 {
     paramDictionary.ThrowIfNull("paramDictionary");
     this.Self.Params = paramDictionary;
     return(this);
 }
Пример #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BehavioralFunction"/> class.
 /// </summary>
 /// <param name="map">Maps each derivative to an unknown</param>
 /// <param name="derivatives">The derivatives.</param>
 public BehavioralFunction(Dictionary <int, int> map, Derivatives <Func <double> > derivatives)
 {
     _map         = map.ThrowIfNull(nameof(map));
     _derivatives = derivatives.ThrowIfNull(nameof(map));
 }
 /// <summary>
 /// Safely returns the value from the dictionary associated to the key supplied, or the default (usually a null) for the
 /// value type.
 /// </summary>
 /// <typeparam name="TKey">Dictionary key type, can usually be deduced from the dictionary parameter.</typeparam>
 /// <typeparam name="TValue">Dictionary value type, can usually be deduced from the dictionary> parameter.</typeparam>
 /// <param name="dictionary">Dictionary in which to look.</param>
 /// <param name="key">Key to find in dictionary.</param>
 /// <returns>Value corresponding to the supplied key.</returns>
 public static TValue Get <TKey, TValue>(this Dictionary <TKey, TValue> dictionary, TKey key)
 {
     dictionary.ThrowIfNull(nameof(dictionary));
     return(dictionary.ContainsKey(key) ? dictionary[key] : default(TValue));
 }