Example #1
0
        public VBIB(IKeyValueCollection data) : this()
        {
            var vertexBuffers = data.GetArray("m_vertexBuffers");

            foreach (var vb in vertexBuffers)
            {
                var vertexBuffer = BufferDataFromDATA(vb);

                var decompressedSize = vertexBuffer.ElementCount * vertexBuffer.ElementSizeInBytes;
                if (vertexBuffer.Data.Length != decompressedSize)
                {
                    vertexBuffer.Data = MeshOptimizerVertexDecoder.DecodeVertexBuffer((int)vertexBuffer.ElementCount, (int)vertexBuffer.ElementSizeInBytes, vertexBuffer.Data);
                }
                VertexBuffers.Add(vertexBuffer);
            }
            var indexBuffers = data.GetArray("m_indexBuffers");

            foreach (var ib in indexBuffers)
            {
                var indexBuffer = BufferDataFromDATA(ib);

                var decompressedSize = indexBuffer.ElementCount * indexBuffer.ElementSizeInBytes;
                if (indexBuffer.Data.Length != decompressedSize)
                {
                    indexBuffer.Data = MeshOptimizerIndexDecoder.DecodeIndexBuffer((int)indexBuffer.ElementCount, (int)indexBuffer.ElementSizeInBytes, indexBuffer.Data);
                }

                IndexBuffers.Add(indexBuffer);
            }
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Skeleton"/> class.
        /// </summary>
        public Skeleton(IKeyValueCollection modelData)
        {
            Bones = new Bone[0];
            Roots = new List <Bone>();

            // Check if there is any skeleton data present at all
            if (!modelData.ContainsKey("m_modelSkeleton"))
            {
                Console.WriteLine("No skeleton data found.");
            }

            // Get the remap table and invert it for our construction method
            var remapTable  = modelData.GetIntegerArray("m_remappingTable");
            var invMapTable = new Dictionary <long, int>();

            for (var i = 0; i < remapTable.Length; i++)
            {
                if (!invMapTable.ContainsKey(remapTable[i]))
                {
                    invMapTable.Add(remapTable[i], i);
                }
            }

            // Construct the armature from the skeleton KV
            ConstructFromNTRO(modelData.GetSubCollection("m_modelSkeleton"), invMapTable);
        }
Example #3
0
        public RemapParticleCountToScalar(IKeyValueCollection keyValues)
        {
            if (keyValues.ContainsKey("m_nFieldOutput"))
            {
                fieldOutput = keyValues.GetIntegerProperty("m_nFieldOutput");
            }

            if (keyValues.ContainsKey("m_nInputMin"))
            {
                inputMin = keyValues.GetIntegerProperty("m_nInputMin");
            }

            if (keyValues.ContainsKey("m_nInputMax"))
            {
                inputMax = keyValues.GetIntegerProperty("m_nInputMax");
            }

            if (keyValues.ContainsKey("m_flOutputMin"))
            {
                outputMin = keyValues.GetIntegerProperty("m_flOutputMin");
            }

            if (keyValues.ContainsKey("m_flOutputMax"))
            {
                outputMax = keyValues.GetIntegerProperty("m_flOutputMax");
            }

            if (keyValues.ContainsKey("m_bScaleInitialRange"))
            {
                scaleInitialRange = keyValues.GetProperty <bool>("m_bScaleInitialRange");
            }
        }
        /// <summary>
        /// Using <see cref="CreateBehaviors"/>, behaviors are created. Then calling <see cref="CreateBehaviorContext"/> context is created. And then pipeline is executed.
        /// </summary>
        /// <param name="handler">Handler instance to execute pipeline on.</param>
        /// <param name="customValues">Collection of custom values passed around invokation.</param>
        /// <returns>Continuation task.</returns>
        public Task ExecuteAsync(T handler, IKeyValueCollection customValues)
        {
            IEnumerable <IBehavior <T> > behaviors = CreateBehaviors();
            IBehaviorContext             context   = CreateBehaviorContext(behaviors, handler, customValues);

            return(context.NextAsync());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Skeleton"/> class.
        /// </summary>
        public Skeleton(IKeyValueCollection modelData)
        {
            // Check if there is any skeleton data present at all
            if (!modelData.ContainsKey("m_modelSkeleton"))
            {
                Console.WriteLine("No skeleton data found.");
            }

            // Get the remap table and invert it for our construction method
            var remapTable = modelData.GetIntegerArray("m_remappingTable");

            var start = 0;
            var end   = remapTable.Length;

            var remapTableStarts = modelData.GetIntegerArray("m_remappingTableStarts");

            // we only use lod 1
            if (remapTableStarts.Length > 1)
            {
                start = (int)remapTableStarts[0];
                end   = (int)remapTableStarts[1];
            }

            var invMapTable = remapTable.Skip(start).Take(end - start)
                              .Select((mapping, index) => (mapping, index))
                              .ToLookup(mi => mi.mapping, mi => mi.index);

            if (invMapTable.Any())
            {
                AnimationTextureSize = invMapTable.Select(g => g.Max()).Max() + 1;
            }

            // Construct the armature from the skeleton KV
            ConstructFromNTRO(modelData.GetSubCollection("m_modelSkeleton"), invMapTable);
        }
        public RandomRotationSpeed(IKeyValueCollection keyValues)
        {
            if (keyValues.ContainsKey("m_nFieldOutput"))
            {
                fieldOutput = (ParticleField)keyValues.GetIntegerProperty("m_nFieldOutput");
            }

            if (keyValues.ContainsKey("m_bRandomlyFlipDirection"))
            {
                randomlyFlipDirection = keyValues.GetProperty <bool>("m_bRandomlyFlipDirection");
            }

            if (keyValues.ContainsKey("m_flDegrees"))
            {
                degrees = keyValues.GetFloatProperty("m_flDegrees");
            }

            if (keyValues.ContainsKey("m_flDegreesMin"))
            {
                degreesMin = keyValues.GetFloatProperty("m_flDegreesMin");
            }

            if (keyValues.ContainsKey("m_flDegreesMax"))
            {
                degreesMax = keyValues.GetFloatProperty("m_flDegreesMax");
            }
        }
Example #7
0
        private static OnDiskBufferData BufferDataFromDATA(IKeyValueCollection data)
        {
            OnDiskBufferData buffer = new OnDiskBufferData();

            buffer.ElementCount       = data.GetUInt32Property("m_nElementCount");
            buffer.ElementSizeInBytes = data.GetUInt32Property("m_nElementSizeInBytes");

            buffer.InputLayoutFields = new List <RenderInputLayoutField>();

            var inputLayoutFields = data.GetArray("m_inputLayoutFields");

            foreach (var il in inputLayoutFields)
            {
                RenderInputLayoutField attrib = new RenderInputLayoutField();

                //null-terminated string
                attrib.SemanticName     = System.Text.Encoding.UTF8.GetString(il.GetArray <byte>("m_pSemanticName")).TrimEnd((char)0);
                attrib.SemanticIndex    = il.GetInt32Property("m_nSemanticIndex");
                attrib.Format           = (DXGI_FORMAT)il.GetUInt32Property("m_Format");
                attrib.Offset           = il.GetUInt32Property("m_nOffset");
                attrib.Slot             = il.GetInt32Property("m_nSlot");
                attrib.SlotType         = (RenderSlotType)il.GetUInt32Property("m_nSlotType");
                attrib.InstanceStepRate = il.GetInt32Property("m_nInstanceStepRate");

                buffer.InputLayoutFields.Add(attrib);
            }

            buffer.Data = data.GetArray <byte>("m_pData");

            return(buffer);
        }
Example #8
0
            private IPagedChangeSet <TObject, TKey>?Paginate(ISortedChangeSet <TObject, TKey>?updates = null)
            {
                if (_isLoaded == false)
                {
                    return(null);
                }

                var previous = _current;

                int pages = CalculatePages();
                int page  = _request.Page > pages ? pages : _request.Page;
                int skip  = _request.Size * (page - 1);

                var paged = _all.Skip(skip).Take(_request.Size).ToList();

                _current = new KeyValueCollection <TObject, TKey>(paged, _all.Comparer, updates?.SortedItems.SortReason ?? SortReason.DataChanged, _all.Optimisations);

                // check for changes within the current virtualised page.  Notify if there have been changes or if the overall count has changed
                var notifications = FilteredIndexCalculator <TObject, TKey> .Calculate(_current, previous, updates);

                if (notifications.Count == 0 && (previous.Count != _current.Count))
                {
                    return(null);
                }

                var response = new PageResponse(_request.Size, _all.Count, page, pages);

                return(new PagedChangeSet <TObject, TKey>(_current, notifications, response));
            }
Example #9
0
        /// <summary>
        /// Technique 1 - Simulate transforming input and load all values to KeyValueCollection and save it to file
        /// </summary>
        /// <param name="filePath">File path of tested data file</param>
        /// <param name="keyValueCollection">Final collection key value pair of order (int) and letter (char)</param>
        /// <param name="uIntCollection">Collection of uint no needed in this technique</param>
        /// <returns>Process time in total milliseconds</returns>
        internal static double T1(string filePath, IKeyValueCollection keyValueCollection, IUIntCollection uIntCollection = null)
        {
            Console.Write($"{MethodBase.GetCurrentMethod().Name}\t {keyValueCollection.Name.PadRight(40)}\t {$"without {nameof(IUIntCollection)}".PadRight(30)}\t");

            var stopwatch = Stopwatch.StartNew();

            Parallel.ForEach(File.ReadAllLines(filePath), (line) =>
            {
                if (UInt32.TryParse(line, out uint uintFromString))
                {
                    SimulatesProcessOneLine(line);
                    var byteResult = BitConverter.GetBytes(uintFromString);
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(byteResult);
                    }
                    var letter = Convert.ToChar(byteResult[3]);
                    var order  = byteResult[2] + (byteResult[1] << 8) + (byteResult[0] << 16);

                    var simulatedOrder = SimulateDuplicitValues(uintFromString);
                    keyValueCollection.AddToCollection(simulatedOrder, 'A');
                }
            });

            var count = keyValueCollection.SortAndWriteToFile();

            Console.Write($"{count}\t\t");

            return(StopStopWatch(stopwatch));
        }
Example #10
0
        private static void PrintAttributeOrReferenceValue(IKeyValueCollection attributeValue, IndentedTextWriter writer)
        {
            var value = attributeValue.GetProperty <string>("name");
            var type  = attributeValue.GetProperty <string>("eType");

            switch (type)
            {
            case "REFERENCE_COMPILED":
                value = "s2r://" + value;
                break;

            case "REFERENCE_PASSTHROUGH":
                value = "file://" + value;
                break;

            case "PANEL_ATTRIBUTE_VALUE":
                value = SecurityElement.Escape(value);
                break;

            default:
                throw new Exception($"Unknown attribute type: {type}");
            }

            writer.Write($"\"{value}\"");
        }
Example #11
0
        public FadeAndKill(IKeyValueCollection keyValues)
        {
            if (keyValues.ContainsKey("m_flStartFadeInTime"))
            {
                startFadeInTime = keyValues.GetFloatProperty("m_flStartFadeInTime");
            }

            if (keyValues.ContainsKey("m_flEndFadeInTime"))
            {
                endFadeInTime = keyValues.GetFloatProperty("m_flEndFadeInTime");
            }

            if (keyValues.ContainsKey("m_flStartFadeOutTime"))
            {
                startFadeOutTime = keyValues.GetFloatProperty("m_flStartFadeOutTime");
            }

            if (keyValues.ContainsKey("m_flEndFadeOutTime"))
            {
                endFadeOutTime = keyValues.GetFloatProperty("m_flEndFadeOutTime");
            }

            if (keyValues.ContainsKey("m_flStartAlpha"))
            {
                startAlpha = keyValues.GetFloatProperty("m_flStartAlpha");
            }

            if (keyValues.ContainsKey("m_flEndAlpha"))
            {
                endAlpha = keyValues.GetFloatProperty("m_flEndAlpha");
            }
        }
Example #12
0
        public override void Read(BinaryReader reader, Resource resource)
        {
            Resource = resource;

            if (!resource.ContainsBlockType(BlockType.NTRO))
            {
                var kv3 = new BinaryKV3(KVBlockType)
                {
                    Offset = Offset,
                    Size   = Size,
                };
                kv3.Read(reader, resource);
                Data        = kv3.Data;
                BackingData = kv3;
            }
            else
            {
                var ntro = new NTRO
                {
                    StructName = IntrospectionStructName,
                    Offset     = Offset,
                    Size       = Size,
                };
                ntro.Read(reader, resource);
                Data        = ntro.Output;
                BackingData = ntro;
            }
        }
Example #13
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="exception">An exception to handle.</param>
 /// <param name="metadata">An initial collection of metadata.</param>
 public DefaultExceptionHandlerContext(Exception exception, IKeyValueCollection metadata)
 {
     Ensure.NotNull(exception, "exception");
     Ensure.NotNull(metadata, "metadata");
     Exception     = exception;
     this.metadata = metadata;
 }
Example #14
0
        public RandomRotation(IKeyValueCollection keyValues)
        {
            random = new Random();

            if (keyValues.ContainsKey("m_flDegreesMin"))
            {
                degreesMin = keyValues.GetFloatProperty("m_flDegreesMin");
            }

            if (keyValues.ContainsKey("m_flDegreesMax"))
            {
                degreesMax = keyValues.GetFloatProperty("m_flDegreesMax");
            }

            if (keyValues.ContainsKey("m_flDegrees"))
            {
                degreesOffset = keyValues.GetFloatProperty("m_flDegrees");
            }

            if (keyValues.ContainsKey("m_nFieldOutput"))
            {
                fieldOutput = keyValues.GetIntegerProperty("m_nFieldOutput");
            }

            if (keyValues.ContainsKey("m_bRandomlyFlipDirection"))
            {
                randomlyFlipDirection = keyValues.GetProperty <bool>("m_bRandomlyFlipDirection");
            }
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Skeleton"/> class.
        /// </summary>
        public static Skeleton FromModelData(IKeyValueCollection modelData, int meshIndex)
        {
            // Check if there is any skeleton data present at all
            if (!modelData.ContainsKey("m_modelSkeleton"))
            {
                Console.WriteLine("No skeleton data found.");
            }

            // Get the remap table and invert it for our construction method
            var remapTable = modelData.GetIntegerArray("m_remappingTable");

            var remapTableStarts = modelData.GetIntegerArray("m_remappingTableStarts");

            var start = (int)remapTableStarts[meshIndex];
            var end   = meshIndex < remapTableStarts.Length - 1
                ? (int)remapTableStarts[meshIndex + 1]
                : remapTable.Length;

            var invMapTable = remapTable.Skip(start).Take(end - start)
                              .Select((mapping, index) => (mapping, index))
                              .ToLookup(mi => mi.mapping, mi => mi.index);

            // Construct the armature from the skeleton KV
            return(new Skeleton(modelData.GetSubCollection("m_modelSkeleton"), invMapTable));
        }
 /// <summary>
 /// Creates new instance with the <paramref name="body"/> and the <paramref name="metadata"/>.
 /// </summary>
 /// <param name="body">The body of the evelope.</param>
 /// <param name="metadata">The collection of the metadata. Reference is used (instead of copying items).</param>
 public Envelope(object body, IKeyValueCollection metadata)
 {
     Ensure.NotNull(body, "body");
     Ensure.NotNull(metadata, "metadata");
     Body     = body;
     Metadata = metadata;
 }
        public static IEnumerable <Animation> FromData(IKeyValueCollection animationData, IKeyValueCollection decodeKey)
        {
            var animArray = animationData.GetArray <IKeyValueCollection>("m_animArray");

            if (animArray.Length == 0)
            {
                Console.WriteLine("Empty animation file found.");
                return(Enumerable.Empty <Animation>());
            }

            var decoderArray = MakeDecoderArray(animationData.GetArray("m_decoderArray"));
            var segmentArray = animationData.GetArray("m_segmentArray");

            var animations = new List <Animation>();

            foreach (var anim in animArray)
            {
                // Here be dragons. Animation decoding is complicated, and we have not
                // fully figured it out, especially all of the decoder types.
                // If an animation decoder throws, this prevents the model from loading or exporting,
                // so we catch all exceptions here and skip over the animation.
                // Obviously we want to properly support animation decoding, but we are not there yet.
                try
                {
                    animations.Add(new Animation(anim, decodeKey, decoderArray, segmentArray));
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                }
            }

            return(animations);
        }
 public FadeOutSimple(IKeyValueCollection keyValues)
 {
     if (keyValues.ContainsKey("m_flFadeOutTime"))
     {
         fadeOutTime = keyValues.GetFloatProperty("m_flFadeOutTime");
     }
 }
Example #19
0
        public InstantaneousEmitter(IKeyValueCollection baseProperties, IKeyValueCollection keyValues)
        {
            this.baseProperties = baseProperties;

            emitCount = keyValues.GetNumberProvider("m_nParticlesToEmit");
            startTime = keyValues.GetFloatProperty("m_flStartTime");
        }
Example #20
0
        private static void PrintNode(IKeyValueCollection node, IndentedTextWriter writer)
        {
            var type = node.GetProperty <string>("eType");

            switch (type)
            {
            case "ROOT": PrintPanelBase("root", node, writer); break;

            case "STYLES": PrintPanelBase("styles", node, writer); break;

            case "INCLUDE": PrintInclude(node, writer); break;

            case "PANEL": PrintPanel(node, writer); break;

            case "SCRIPT_BODY": PrintScriptBody(node, writer); break;

            case "SCRIPTS": PrintPanelBase("scripts", node, writer); break;

            case "SNIPPET": PrintSnippet(node, writer); break;

            case "SNIPPETS": PrintPanelBase("snippets", node, writer); break;

            default: throw new Exception($"Unknown node type: {type}");
            }
            ;
        }
        public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName)
        {
            var property = keyValues.GetProperty <object>(propertyName);

            if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType"))
            {
                var type = numberProviderParameters.GetProperty <string>("m_nType");
                switch (type)
                {
                case "PVEC_TYPE_LITERAL":
                    return(new LiteralVectorProvider(numberProviderParameters.GetArray <double>("m_vLiteralValue")));

                default:
                    if (numberProviderParameters.ContainsKey("m_vLiteralValue"))
                    {
                        Console.Error.WriteLine($"Vector provider of type {type} is not directly supported, but it has m_vLiteralValue.");
                        return(new LiteralVectorProvider(numberProviderParameters.GetArray <double>("m_vLiteralValue")));
                    }

                    throw new InvalidCastException($"Could not create vector provider of type {type}.");
                }
            }

            return(new LiteralVectorProvider(keyValues.GetArray <double>(propertyName)));
        }
Example #22
0
        public RenderSprites(IKeyValueCollection keyValues, VrfGuiContext vrfGuiContext)
        {
            shaderProgram = SetupShaderProgram();

            // The same quad is reused for all particles
            quadVao = SetupQuadBuffer();

            var textureSetup = LoadTexture(keyValues.GetProperty <string>("m_hTexture"), vrfGuiContext);

            glTexture       = textureSetup.TextureIndex;
            spriteSheetData = textureSetup.TextureData.GetSpriteSheetData();

            additive = keyValues.GetProperty <bool>("m_bAdditive");
            if (keyValues.ContainsKey("m_flOverbrightFactor"))
            {
                overbrightFactor = keyValues.GetFloatProperty("m_flOverbrightFactor");
            }

            if (keyValues.ContainsKey("m_nOrientationType"))
            {
                orientationType = keyValues.GetIntegerProperty("m_nOrientationType");
            }

            if (keyValues.ContainsKey("m_flAnimationRate"))
            {
                animationRate = keyValues.GetFloatProperty("m_flAnimationRate");
            }
        }
Example #23
0
            private IVirtualChangeSet <TObject, TKey> Virtualise(ISortedChangeSet <TObject, TKey> updates = null)
            {
                if (_isLoaded == false)
                {
                    return(null);
                }

                var previous   = _current;
                var virualised = _all.Skip(_parameters.StartIndex)
                                 .Take(_parameters.Size)
                                 .ToList();

                _current = new KeyValueCollection <TObject, TKey>(virualised, _all.Comparer, updates?.SortedItems.SortReason ?? SortReason.DataChanged, _all.Optimisations);

                ////check for changes within the current virtualised page.  Notify if there have been changes or if the overall count has changed
                var notifications = _changedCalculator.Calculate(_current, previous, updates);

                if (notifications.Count == 0 && (previous.Count != _current.Count))
                {
                    return(null);
                }

                var response = new VirtualResponse(_parameters.Size, _parameters.StartIndex, _all.Count);

                return(new VirtualChangeSet <TObject, TKey>(notifications, _current, response));
            }
        public RenderSprites(IKeyValueCollection keyValues, VrfGuiContext vrfGuiContext)
        {
            shader      = vrfGuiContext.ShaderLoader.LoadShader("vrf.particle.sprite", new Dictionary <string, bool>());
            quadIndices = vrfGuiContext.QuadIndices;

            // The same quad is reused for all particles
            quadVao = SetupQuadBuffer();

            if (keyValues.ContainsKey("m_hTexture"))
            {
                var textureSetup = LoadTexture(keyValues.GetProperty <string>("m_hTexture"), vrfGuiContext);
                glTexture       = textureSetup.TextureIndex;
                spriteSheetData = textureSetup.TextureData?.GetSpriteSheetData();
            }
            else
            {
                glTexture = vrfGuiContext.MaterialLoader.GetErrorTexture();
            }

            additive = keyValues.GetProperty <bool>("m_bAdditive");
            if (keyValues.ContainsKey("m_flOverbrightFactor"))
            {
                overbrightFactor = keyValues.GetFloatProperty("m_flOverbrightFactor");
            }

            if (keyValues.ContainsKey("m_nOrientationType"))
            {
                orientationType = keyValues.GetIntegerProperty("m_nOrientationType");
            }

            if (keyValues.ContainsKey("m_flAnimationRate"))
            {
                animationRate = keyValues.GetFloatProperty("m_flAnimationRate");
            }
        }
Example #25
0
        public static INumberProvider GetNumberProvider(this IKeyValueCollection keyValues, string propertyName)
        {
            var property = keyValues.GetProperty <object>(propertyName);

            if (property is IKeyValueCollection numberProviderParameters)
            {
                var type = numberProviderParameters.GetProperty <string>("m_nType");
                switch (type)
                {
                case "PF_TYPE_LITERAL":
                    return(new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue")));

                default:
                    if (numberProviderParameters.ContainsKey("m_flLiteralValue"))
                    {
                        Console.Error.WriteLine($"Number provider of type {type} is not directly supported, but it has m_flLiteralValue.");
                        return(new LiteralNumberProvider(numberProviderParameters.GetDoubleProperty("m_flLiteralValue")));
                    }

                    throw new InvalidCastException($"Could not create number provider of type {type}.");
                }
            }
            else
            {
                return(new LiteralNumberProvider(Convert.ToDouble(property)));
            }
        }
Example #26
0
        private static void PrintScriptBody(IKeyValueCollection node, IndentedTextWriter writer)
        {
            var content = node.GetProperty <string>("name");

            writer.Write("<script><![CDATA[");
            writer.Write(content);
            writer.WriteLine("]]></script>");
        }
Example #27
0
        private static void PrintInclude(IKeyValueCollection node, IndentedTextWriter writer)
        {
            var reference = node.GetSubCollection("child");

            writer.Write($"<include src=");
            PrintAttributeOrReferenceValue(reference, writer);
            writer.WriteLine(" />");
        }
Example #28
0
        public KeyValueStoreBase(TKeyValueDbContext keyValueDbContext, IStoreKeyPrefixProvider <T> prefixProvider)
        {
            _keyValueDbContext = keyValueDbContext;
            // ReSharper disable once VirtualMemberCallInConstructor
            _collection = keyValueDbContext.Collection(prefixProvider.GetStoreKeyPrefix());

            _messageParser = new MessageParser <T>(() => new T());
        }
        public IKeyToParametersConverter AddWithoutType(IKeyValueCollection parameters, IKey key)
        {
            Ensure.NotNull(parameters, "parameters");
            Ensure.NotNull(key, "key");

            parameters = new KeyValueCollectionWrapper(parameters, null, null, true);
            return(Add(parameters, key));
        }
Example #30
0
 public void Store(IKeyValueCollection storage, object input)
 {
     // TODO: Not null check, UserKey is required!
     if (input is UserEvent payload && payload.UserKey != null)
     {
         storage.Add(Name.UserKey, payload.UserKey);
     }
 }
		/// <summary>
		/// Convert <c>IKeyValueCollection</c> to <c>NameValueCollection</c>.
		/// </summary>
		/// <param name="kvc">The <c>IKeyValueCollection</c> object.</param>
		/// <returns>The generated <c>NameValueCollection</c> object.</returns>
		public static NameValueCollection ConvertToNameValues(IKeyValueCollection kvc)
		{
			NameValueCollection nvc = new NameValueCollection();

			foreach( IKeyValue kv in kvc )
			{
				nvc.Add(kv.Key, kv.Value);
			}

			return nvc;
		}
Example #32
0
 /// <summary>
 /// Parse all semicolon separated parameters.
 /// </summary>
 /// <param name="parameters"></param>
 public static void ParseParameters(IKeyValueCollection<string, string> parameters, ITextReader reader)
 {
     ParseParameters(parameters, reader, ';');
 }
Example #33
0
        /// <summary>
        /// Initializes a new instance containing the elements of 
        /// the specified source collection.
        /// </summary>
        /// <param name="value"></param>
        public KeyValueCollection(
			IKeyValueCollection value
			)
        {
            AddRange(value);
        }
Example #34
0
 /// <summary>
 /// Adds the contents of the specified IKeyValueCollection 
 /// to the end of the collection.
 /// </summary>
 /// <param name="items"></param>
 public void AddRange(IKeyValueCollection items)
 {
     InnerList.AddRange(items);
 }
		/// <summary>
		/// Extract <c>IAttributeSetCollection</c> object from <c>IKeyValueCollection</c> object.
		/// </summary>
		/// <param name="nameValues">The <c>IKeyValueCollection</c> to be converted.</param>
		/// <returns>The extracted <c>IAttributeSetCollection</c> object.</returns>
		public IAttributeSetCollection NameValuesToAttributeSets(IKeyValueCollection nameValues)
		{
			IAttributeSetCollection attrSets = new AttributeSetCollection();			
			AttributeSet attrSet;
			NameValueCollection nvs = AttributesHelper.ConvertToNameValues(nameValues);
			for(int ordinal = 0; ; ordinal++ )
			{
				attrSet = ExtractOneCat(CAT_CS_ID + ordinal.ToString(), nvs);
				if( attrSet != null )
				{
					attrSet.CategoryOrdinal = attrSets.Count;
					attrSets.Add(attrSet);
				}
				else
					break;
			}

			return attrSets;
		}
		/// <summary>
		/// Render HTML text by raw name-value pairs that you got during HTML submit. 
		/// </summary>
		/// <param name="nameValues">List of name-value pairs from submit of attributes HTML form
		/// generated by all these RenderHtml methods.</param>
		/// <param name="errorList">The <c>IErrorSetCollection</c> object returned by <c>Validate</c> method.
		/// Set null if you don't have one.</param>
		/// <returns>The generated HTML text that is encapsulated in HTML table element.</returns>
		public string RenderHtmlForPostback(IKeyValueCollection nameValues, IErrorSetCollection errorList)
		{
			IAttributeSetCollection attrSets = NameValuesToAttributeSets(nameValues);
			return RenderHtml(attrSets, errorList);
		}
Example #37
0
        /// <summary>
        /// Parse all semicolon separated parameters.
        /// </summary>
        /// <param name="parameters">String containing all parameters to parse</param>
        /// <param name="delimiter">Delimiter separating parameters.</param>
        /// <example>
        /// <code>
        /// KeyValueCollection parameters = new KeyValueCollection();
        /// UriParser.ParseParameters(parameters, "hej=hello,welcome=now", ',');
        /// </code>
        /// </example>
        /// <remarks>
        /// Parameter names are converted to lower case.
        /// </remarks>
        public static void ParseParameters(IKeyValueCollection<string, string> parameters, ITextReader reader,
            char delimiter)
        {
            reader.Consume(' ', '\t');
            while (!reader.EOF)
            {
                if (reader.Current == delimiter)
                    reader.Consume();
                if (reader.EOF)
                    return;

                reader.Consume(' ', '\t');
                string name = reader.ReadToEnd("=" + delimiter);
                if (name == null)
                    break;
                name = name.ToLower();

                // No semicolon after last parameter.
                if (reader.EOF)
                {
                    parameters.Add(name, string.Empty);
                    return;
                }

                if (reader.Current == delimiter)
                {
                    parameters.Add(name, string.Empty);
                    continue;
                }

                reader.Consume(' ', '\t', '=');
                string value = reader.Current == '"' ? reader.ReadQuotedString() : reader.ReadToEnd(" \t" + delimiter);

                // no value
                if (value == null)
                {
                    parameters.Add(name, string.Empty);
                    continue;
                }
                parameters.Add(name, value);
                reader.Consume(' ', '\t');

                if (reader.Current != delimiter)
                    break;
            }
        }