예제 #1
0
		public StoreInfoPage(IStore store, ContentMode mode = ContentMode.View)
		{
			//Setup view model
			this.ViewModel = MvxToolbox.LoadViewModel<StoreInfoViewModel>();
			this.ViewModel.Store = store;
			this.ViewModel.Mode = mode;

			InitializeComponent();

			//Setup Header
			this.HeaderView.BindingContext = this.ViewModel;

			//Setup events
			this.listView.ItemSelected += itemSelected;
			this.ViewModel.Products.ReloadFinished += (sender, e) =>
			{
				this.listView.EndRefresh();
			};

			//Setup view model actions
			this.ViewModel.ShowStoreDetailsAction = async (s) =>
			{
				await this.Navigation.PushAsync(new StoreDetailsPage(s, mode));
			};

			this.ViewModel.AddProductAction = async (p, s) =>
			{
				await this.Navigation.PushModalAsync(new NavigationPage(new SaveProductPage(p, s)));
			};
		}
예제 #2
0
 public static string GetContentModeResponse(ContentMode mode, string content, bool connectionClose = false)
 {
     switch (mode)
     {
         case ContentMode.ContentLength:
             return GetHttpResponse(content: content, connectionClose: connectionClose);
         case ContentMode.SingleChunk:
             return GetSingleChunkHttpResponse(content: content, connectionClose: connectionClose);
         case ContentMode.BytePerChunk:
             return GetBytePerChunkHttpResponse(content: content, connectionClose: connectionClose);
         case ContentMode.ConnectionClose:
             Assert.True(connectionClose);
             return GetConnectionCloseResponse(content: content);
         default:
             Assert.True(false, $"Unknown content mode: {mode}");
             return null;
     }
 }
        /// <summary>
        /// Copies the CloudEvent into this HttpWebRequest instance
        /// </summary>
        /// <param name="httpWebRequest">this</param>
        /// <param name="cloudEvent">CloudEvent to copy</param>
        /// <param name="contentMode">Content mode (structured or binary)</param>
        /// <param name="formatter">Formatter</param>
        /// <returns>Task</returns>
        public static async Task CopyFromAsync(this HttpWebRequest httpWebRequest, CloudEvent cloudEvent,
                                               ContentMode contentMode, ICloudEventFormatter formatter)
        {
            if (contentMode == ContentMode.Structured)
            {
                var buffer =
                    formatter.EncodeStructuredEvent(cloudEvent, out var contentType);
                httpWebRequest.ContentType = contentType.ToString();
                await(httpWebRequest.GetRequestStream()).WriteAsync(buffer, 0, buffer.Length);
                return;
            }

            Stream stream = MapDataAttributeToStream(cloudEvent, formatter);

            httpWebRequest.ContentType = cloudEvent.DataContentType?.ToString() ?? "application/json";
            MapAttributesToWebRequest(cloudEvent, httpWebRequest);
            await stream.CopyToAsync(httpWebRequest.GetRequestStream());
        }
예제 #4
0
		public StoreDetailsPage(IStore store, ContentMode mode = ContentMode.View)
		{
			this.ViewModel = MvxToolbox.LoadViewModel<StoreDetailsViewModel>();
			this.ViewModel.Store = store;
			this.ViewModel.Mode = mode;
			InitializeComponent();
			this.deliveryNotes.DidOpen += (sender, e) => {
				this.scrollView.ScrollToAsync(this.deliveryNotes, ScrollToPosition.End, true);
			};
			if (mode == ContentMode.Edit && store != null)
			{
				this.ToolbarItems.Add(new ToolbarItem(AppResources.ButtonEdit, "", async () =>
					{
						var editStorePage = new SaveStorePage(store);
						await this.Navigation.PushModalAsync(new NavigationPage(editStorePage));
					}));
			}
		}
        /// <summary>
        /// Copies the CloudEvent into this HttpListenerResponse instance
        /// </summary>
        /// <param name="httpListenerResponse">this</param>
        /// <param name="cloudEvent">CloudEvent to copy</param>
        /// <param name="contentMode">Content mode (structured or binary)</param>
        /// <param name="formatter">Formatter</param>
        /// <returns>Task</returns>
        public static Task CopyFromAsync(this HttpListenerResponse httpListenerResponse, CloudEvent cloudEvent,
                                         ContentMode contentMode, ICloudEventFormatter formatter)
        {
            if (contentMode == ContentMode.Structured)
            {
                var buffer =
                    formatter.EncodeStructuredEvent(cloudEvent, out var contentType);
                httpListenerResponse.ContentType = contentType.ToString();
                MapAttributesToListenerResponse(cloudEvent, httpListenerResponse);
                return(httpListenerResponse.OutputStream.WriteAsync(buffer, 0, buffer.Length));
            }

            Stream stream = MapDataAttributeToStream(cloudEvent, formatter);

            httpListenerResponse.ContentType = cloudEvent.DataContentType?.ToString() ?? "application/json";
            MapAttributesToListenerResponse(cloudEvent, httpListenerResponse);
            return(stream.CopyToAsync(httpListenerResponse.OutputStream));
        }
        protected static string GetResponseForContentMode(string content, ContentMode mode)
        {
            switch (mode)
            {
            case ContentMode.ContentLength:
                return(LoopbackServer.GetHttpResponse(content: content));

            case ContentMode.SingleChunk:
                return(LoopbackServer.GetSingleChunkHttpResponse(content: content));

            case ContentMode.BytePerChunk:
                return(LoopbackServer.GetBytePerChunkHttpResponse(content: content));

            default:
                Assert.True(false);
                return(null);
            }
        }
예제 #7
0
        /// <summary>
        /// Converts a CloudEvent to <see cref="Message"/>.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        public static Message ToAmqpMessage(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            var applicationProperties = MapHeaders(cloudEvent);
            RestrictedDescribed bodySection;
            Properties          properties;

            switch (contentMode)
            {
            case ContentMode.Structured:
                bodySection = new Data
                {
                    Binary = formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType)
                };
                // TODO: What about the other parts of the content type?
                properties = new Properties {
                    ContentType = contentType.MediaType
                };
                break;

            case ContentMode.Binary:
                bodySection = new Data {
                    Binary = formatter.EncodeBinaryModeEventData(cloudEvent)
                };
                properties = new Properties {
                    ContentType = cloudEvent.DataContentType
                };
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            return(new Message
            {
                ApplicationProperties = applicationProperties,
                BodySection = bodySection,
                Properties = properties
            });
        }
예제 #8
0
		public ProductDetailsPage(IProduct product, ContentMode mode = ContentMode.View)
		{
			this.ViewModel = MvxToolbox.LoadViewModel<ProductDetailsViewModel>();
			this.ViewModel.Product = product;
			this.ViewModel.Mode = mode;
			InitializeComponent();
			this.ViewModel.ShowStoreInfoPageAction = async (s) =>
			{
				await this.Navigation.PushAsync(new StoreInfoPage(s));
			};

			if (mode == ContentMode.Edit)
			{
				this.ToolbarItems.Add(new ToolbarItem(AppResources.ButtonEdit, "", async () =>
					{
						var saveProductPage = new SaveProductPage(product, product.Store);
						await this.Navigation.PushModalAsync(new NavigationPage(saveProductPage));
					}));
			}

			this.carouselLayout.IndicatorStyle = CarouselLayout.IndicatorStyleEnum.Dots;
		}
예제 #9
0
        /// <summary>
        /// Determines if the given value represents a valid state of this property.
        /// </summary>
        /// <param name="value">The state that should be used.</param>
        /// <returns>True if the state is valid, otherwise false.</returns>
        protected override Boolean IsValid(CSSValue value)
        {
            if (value.Is("normal"))
                _mode = _normal;
            else if (value.Is("none"))
                _mode = null;
            else if (value is CSSValueList)
                return Evaluate((CSSValueList)value);
            else if (value == CSSValue.Inherit)
                return true;
            else
            {
                var mode = Evaluate(value);

                if (mode == null)
                    return false;

                _mode = mode;
            }

            return true;
        }
        /// <summary>
        /// Converts a CloudEvent to <see cref="Message"/>.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        /// <returns>A <see cref="Message"/>.</returns>
        public static Message ToServiceBusMessage(
            this CloudEvent cloudEvent,
            ContentMode contentMode,
            CloudEventFormatter formatter
            )
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            Message message;

            switch (contentMode)
            {
            case ContentMode.Structured:
                message = new Message(
                    BinaryDataUtilities.AsArray(formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType))
                    )
                {
                    ContentType = contentType.MediaType,
                };
                break;

            case ContentMode.Binary:
                message = new Message(
                    BinaryDataUtilities.AsArray(formatter.EncodeBinaryModeEventData(cloudEvent))
                    )
                {
                    ContentType = cloudEvent.DataContentType,
                };
                break;

            default:
                throw new ArgumentException($"Unsupported content mode: {contentMode}", nameof(contentMode));
            }

            MapHeaders(cloudEvent, message);

            return(message);
        }
예제 #11
0
        public static Generator Resolve(FileSourceInfo source, AST.Element e, ContentMode contentMode, InstanceType instanceType, Common.IMarkupErrorLog log)
        {
            var g = e.Generator;

            if (g is UnspecifiedGenerator)
            {
                var ug = (UnspecifiedGenerator)g;
                if (contentMode == ContentMode.Default || e.UXKey != null)
                {
                    if (instanceType == InstanceType.Local)
                    {
                        return(new InstanceGenerator());
                    }
                    else if (instanceType == InstanceType.Global)
                    {
                        return(new GlobalInstanceGenerator(null));
                    }
                    else
                    {
                        throw new Exception("Unhandled instance type: " + instanceType);
                    }
                }
                else if (contentMode == ContentMode.Template)
                {
                    var t = (UnspecifiedGenerator)g;
                    return(new TemplateGenerator(null, t.Case, t.IsDefaultCase));
                }
                else
                {
                    log.ReportError(source.FileName, source.LineNumber, "Unknown content mode: " + contentMode);
                    return(new InstanceGenerator());
                }
            }
            else
            {
                return(g);
            }
        }
예제 #12
0
파일: UI.cs 프로젝트: Slaktus/LaneDefender
    public Field(string name, string label, float width, float height, int fontSize = 35, GameObject parent = null, ContentMode contentMode = ContentMode.TextAndNumbers, ButtonMode buttonMode = ButtonMode.Left, EditMode editMode = EditMode.SingleClick, Action <Field> StartInput = null, Action <Field> EndInput = null) : base(label, width, height, parent, name, hideQuad: true, fontSize: fontSize)
    {
        this.StartInput = StartInput;
        this.EndInput   = EndInput;
        _contentMode    = contentMode;
        _buttonMode     = buttonMode;
        _editMode       = editMode;

        SetStay(( Button button ) =>
        {
            if (Input.GetMouseButtonDown((int)_buttonMode))
            {
                switch (_editMode)
                {
                case EditMode.DoubleClick:
                    if (_doubleClick)
                    {
                        _handler = Handler();
                    }
                    else
                    {
                        _doubleClick = true;
                    }
                    break;

                case EditMode.SingleClick:
                    _handler = Handler();
                    break;
                }
            }
        });
    }
        public async Task GetAsync_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(ContentMode mode)
        {
            if (IsWinHttpHandler)
            {
                if (mode == ContentMode.BytePerChunk)
                {
                    // WinHttpHandler's behavior with multiple chunks is inconsistent, so disable the test.
                    return;
                }
            }
            else if (IsCurlHandler)
            {
                // CurlHandler's behavior here is inconsistent, so disable the test.
                return;
            }

            const string simpleContent = "Hello world!";

            await LoopbackServer.CreateClientAndServerAsync(
                async url =>
            {
                using (var client = CreateHttpClient())
                {
                    HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                    ValidateResponseHeaders(response1, simpleContent.Length, mode);

                    // Read up to exactly 1 byte before the end of the response
                    Stream responseStream = await response1.Content.ReadAsStreamAsync();
                    byte[] bytes          = await ReadToByteCount(responseStream, simpleContent.Length - 1);
                    Assert.Equal(simpleContent.Substring(0, simpleContent.Length - 1), Encoding.ASCII.GetString(bytes));

                    // Introduce a short delay to try to ensure that when we dispose the response,
                    // all response data is available and we can drain synchronously and reuse the connection.
                    await Task.Delay(100);

                    response1.Dispose();

                    // Issue another request.  We'll confirm that it comes on the same connection.
                    HttpResponseMessage response2 = await client.GetAsync(url);
                    ValidateResponseHeaders(response2, simpleContent.Length, mode);
                    Assert.Equal(simpleContent, await response2.Content.ReadAsStringAsync());
                }
            },
                async server =>
            {
                await server.AcceptConnectionAsync(async connection =>
                {
                    string response = GetResponseForContentMode(simpleContent, mode);
                    await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
                    await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
                });
            });
        }
        public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_KillsConnection(int totalSize, int readSize, ContentMode mode)
        {
            if (IsWinHttpHandler)
            {
                // [ActiveIssue(28424)]
                return;
            }

            await LoopbackServer.CreateClientAndServerAsync(
                async url =>
            {
                HttpClientHandler handler = CreateHttpClientHandler();
                SetResponseDrainTimeout(handler, Timeout.InfiniteTimeSpan);

                // Set MaxConnectionsPerServer to 1.  This will ensure we will wait for the previous request to drain (or fail to)
                handler.MaxConnectionsPerServer = 1;

                using (var client = new HttpClient(handler))
                {
                    HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                    ValidateResponseHeaders(response1, totalSize, mode);

                    // Read part but not all of response
                    Stream responseStream = await response1.Content.ReadAsStreamAsync();
                    await ReadToByteCount(responseStream, readSize);

                    response1.Dispose();

                    // Issue another request.  We'll confirm that it comes on a new connection.
                    HttpResponseMessage response2 = await client.GetAsync(url);
                    ValidateResponseHeaders(response2, totalSize, mode);
                    Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
                }
            },
                async server =>
            {
                string content  = new string('a', totalSize);
                string response = GetResponseForContentMode(content, mode);
                await server.AcceptConnectionAsync(async connection =>
                {
                    await connection.ReadRequestHeaderAsync();
                    try
                    {
                        await connection.Writer.WriteAsync(response);
                    }
                    catch (Exception) { }         // Eat errors from client disconnect.

                    await server.AcceptConnectionSendCustomResponseAndCloseAsync(response);
                });
            });
        }
        public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(int totalSize, int readSize, ContentMode mode)
        {
            if (IsWinHttpHandler)
            {
                // WinHttpHandler seems to only do a limited amount of draining, and this test starts
                // failing if there's any measurable delay introduced in the response such that it dribbles
                // in.  So just skip these tests.
                return;
            }

            if (IsCurlHandler)
            {
                // CurlHandler drain behavior is very inconsistent, so just skip these tests.
                return;
            }

            await LoopbackServer.CreateClientAndServerAsync(
                async url =>
            {
                HttpClientHandler handler = CreateHttpClientHandler();
                SetResponseDrainTimeout(handler, Timeout.InfiniteTimeSpan);

                // Set MaxConnectionsPerServer to 1.  This will ensure we will wait for the previous request to drain (or fail to)
                handler.MaxConnectionsPerServer = 1;

                using (var client = new HttpClient(handler))
                {
                    HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                    ValidateResponseHeaders(response1, totalSize, mode);

                    // Read part but not all of response
                    Stream responseStream = await response1.Content.ReadAsStreamAsync();
                    await ReadToByteCount(responseStream, readSize);

                    response1.Dispose();

                    // Issue another request.  We'll confirm that it comes on the same connection.
                    HttpResponseMessage response2 = await client.GetAsync(url);
                    ValidateResponseHeaders(response2, totalSize, mode);
                    Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
                }
            },
                async server =>
            {
                string content  = new string('a', totalSize);
                string response = GetResponseForContentMode(content, mode);
                await server.AcceptConnectionAsync(async connection =>
                {
                    // Process the first request, with some introduced delays in the response to
                    // stress the draining.
                    await connection.ReadRequestHeaderAsync().ConfigureAwait(false);
                    foreach (char c in response)
                    {
                        await connection.Writer.WriteAsync(c);
                    }

                    // Process the second request.
                    await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
                });
            });
        }
예제 #16
0
 public void ActivateAdvance(PartyUnit partyUnit, Align align = Align.Middle, bool isInterractible = true, ContentMode mode = ContentMode.Full, BackgroundIntermediate.Mode backgroundMode = BackgroundIntermediate.Mode.MiddleScreen)
 {
     // verify party unit is not null, if it is null,
     // then user right clicked on a cell without unit
     if (partyUnit)
     {
         ActivateUnitInfoPanel(partyUnit, backgroundMode);
         SetAlign(align);
         interactable = isInterractible;
         if (mode == ContentMode.Full)
         {
             // activate full mode Br
             transform.Find("BrFull").gameObject.SetActive(true);
             // deactivate short mode Br
             transform.Find("BrShort").gameObject.SetActive(false);
             // activate unit description
             transform.Find("Panel/UnitDescription").gameObject.SetActive(true);
         }
         else if (mode == ContentMode.Short)
         {
             // deactivate full mode Br
             transform.Find("BrFull").gameObject.SetActive(false);
             // activate short mode Br
             transform.Find("BrShort").gameObject.SetActive(true);
             // deactivate unit description
             transform.Find("Panel/UnitDescription").gameObject.SetActive(false);
         }
         else
         {
             Debug.LogError("Unknown mode: " + mode.ToString());
         }
     }
 }
        private void ServiceBusMessageTest(Func <CloudEvent, ServiceBusCloudEventMessage> event2message, ContentMode contentMode)
        {
            var data       = "<much wow=\"xml\"/>";
            var cloudEvent = new CloudEvent(
                CloudEventsSpecVersion.V1_0,
                "com.github.pull.create",
                source: new Uri("https://github.com/cloudevents/spec/pull"),
                subject: "123")
            {
                Id              = "A234-1234-1234",
                Time            = new DateTime(2018, 4, 5, 17, 31, 0, DateTimeKind.Utc),
                DataContentType = new ContentType(MediaTypeNames.Text.Xml),
                Data            = contentMode == ContentMode.Structured ? (object)data : (object)Encoding.UTF8.GetBytes(data),
            };

            var attrs = cloudEvent.GetAttributes();

            attrs["comexampleextension1"] = "value";
            attrs["comexampleextension2"] = new { othervalue = 5 };

            var message = event2message(cloudEvent);

            message.IsCloudEvent().Should().BeTrue();

            var clonedMessage = message.Clone();

            clonedMessage.IsCloudEvent().Should().BeTrue();

            var receivedCloudEvent = clonedMessage.ToCloudEvent();

            receivedCloudEvent.SpecVersion.Should().Be(CloudEventsSpecVersion.Default);
            receivedCloudEvent.Type.Should().Be("com.github.pull.create");
            receivedCloudEvent.Source.Should().Be(new Uri("https://github.com/cloudevents/spec/pull"));
            receivedCloudEvent.Subject.Should().Be("123");
            receivedCloudEvent.Id.Should().Be("A234-1234-1234");
            receivedCloudEvent.Time.Should().NotBeNull();
            receivedCloudEvent.Time !.Value.ToUniversalTime().Should().Be(DateTime.Parse("2018-04-05T17:31:00Z", CultureInfo.InvariantCulture).ToUniversalTime());
            receivedCloudEvent.DataContentType.Should().Be(new ContentType(MediaTypeNames.Text.Xml));

            if (contentMode == ContentMode.Structured)
            {
                receivedCloudEvent.Data.Should().Be(data);
            }
            else
            {
                Encoding.UTF8.GetString((byte[])receivedCloudEvent.Data).Should().Be(data);
            }

            var receivedAttrs = receivedCloudEvent.GetAttributes();

            ((string)receivedAttrs["comexampleextension1"]).Should().Be("value");
            ((int)((dynamic)receivedAttrs["comexampleextension2"]).othervalue).Should().Be(5);
        }
예제 #18
0
파일: Content.cs 프로젝트: fourks/FreeSO
        /// <summary>
        /// Creates a new instance of Content.
        /// </summary>
        /// <param name="basePath">Path to client directory.</param>
        /// <param name="device">A GraphicsDevice instance.</param>
        private Content(string basePath, ContentMode mode, GraphicsDevice device)
        {
            this.BasePath = basePath;
            this.Device   = device;
            this.Mode     = mode;

            if (device != null)
            {
                UIGraphics = new UIGraphicsProvider(this);
                if (TS1)
                {
                    TS1Global      = new TS1Provider(this);
                    AvatarTextures = new TS1AvatarTextureProvider(TS1Global);
                    AvatarMeshes   = new TS1BMFProvider(TS1Global);
                }
                else
                {
                    AvatarTextures = new AvatarTextureProvider(this);
                    AvatarMeshes   = new AvatarMeshProvider(this, Device);
                }
                AvatarHandgroups = new HandgroupProvider(this);
                AbstractTextureRef.FetchDevice        = device;
                AbstractTextureRef.ImageFetchFunction = AbstractTextureRef.ImageFetchWithDevice;
            }
            Changes           = new ChangeManager();
            AvatarBindings    = new AvatarBindingProvider(this);
            AvatarAppearances = new AvatarAppearanceProvider(this);
            AvatarOutfits     = new AvatarOutfitProvider(this);

            AvatarPurchasables = new AvatarPurchasables(this);
            AvatarCollections  = new AvatarCollectionsProvider(this);
            AvatarThumbnails   = new AvatarThumbnailProvider(this);

            if (TS1)
            {
                var provider = new TS1ObjectProvider(this, TS1Global);
                WorldObjects      = provider;
                WorldCatalog      = provider;
                BCFGlobal         = new TS1BCFProvider(this, TS1Global);
                AvatarAnimations  = new TS1BCFAnimationProvider(BCFGlobal);
                AvatarSkeletons   = new TS1BCFSkeletonProvider(BCFGlobal);
                AvatarAppearances = new TS1BCFAppearanceProvider(BCFGlobal);
                Audio             = new TS1Audio(this);
            }
            else
            {
                AvatarAnimations = new AvatarAnimationProvider(this);
                AvatarSkeletons  = new AvatarSkeletonProvider(this);
                WorldObjects     = new WorldObjectProvider(this);
                WorldCatalog     = new WorldObjectCatalog();
                Audio            = new Audio(this);
            }
            WorldFloors        = new WorldFloorProvider(this);
            WorldWalls         = new WorldWallProvider(this);
            WorldObjectGlobals = new WorldGlobalProvider(this);
            WorldRoofs         = new WorldRoofProvider(this);

            GlobalTuning = new Tuning(Path.Combine(basePath, "tuning.dat"));
            Ini          = new IniProvider(this);
            CityMaps     = new CityMapsProvider(this);

            RackOutfits = new RackOutfitsProvider(this);

            Init();
        }
예제 #19
0
        // TODO: Update to a newer version of MQTTNet and support both binary and structured mode?
        /// <summary>
        /// Converts a CloudEvent to <see cref="MqttApplicationMessage"/>.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Currently only structured mode is supported.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        /// <param name="topic">The MQTT topic for the message. May be null.</param>
        public static MqttApplicationMessage ToMqttApplicationMessage(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter, string?topic)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            switch (contentMode)
            {
            case ContentMode.Structured:
                return(new MqttApplicationMessage
                {
                    Topic = topic,
                    Payload = BinaryDataUtilities.AsArray(formatter.EncodeStructuredModeMessage(cloudEvent, out _))
                });

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
        }
예제 #20
0
 internal override void Reset()
 {
     _mode = _normal;
 }
예제 #21
0
		public StoreDetailsViewModel(IStore store = null, ContentMode mode = ContentMode.View)
			: base(store)
		{
			this.ShouldSubscribeToSessionChange = true;
			var messenger = Mvx.Resolve<IMvxMessenger>();
		}
예제 #22
0
        public AmqpCloudEventMessage(CloudEvent cloudEvent, ContentMode contentMode, ICloudEventFormatter formatter)
        {
            if (contentMode == ContentMode.Structured)
            {
                this.BodySection = new Data
                {
                    Binary = formatter.EncodeStructuredEvent(cloudEvent, out var contentType)
                };
                this.Properties = new Properties()
                {
                    ContentType = contentType.MediaType
                };
                this.ApplicationProperties = new ApplicationProperties();
                MapHeaders(cloudEvent);
                return;
            }

            if (cloudEvent.Data is byte[])
            {
                this.BodySection = new Data {
                    Binary = (byte[])cloudEvent.Data
                };
            }
            else if (cloudEvent.Data is Stream)
            {
                if (cloudEvent.Data is MemoryStream)
                {
                    this.BodySection = new Data {
                        Binary = ((MemoryStream)cloudEvent.Data).ToArray()
                    };
                }
                else
                {
                    var buffer = new MemoryStream();
                    ((Stream)cloudEvent.Data).CopyTo(buffer);
                    this.BodySection = new Data {
                        Binary = buffer.ToArray()
                    };
                }
            }
            else if (cloudEvent.Data is string)
            {
                this.BodySection = new AmqpValue()
                {
                    Value = cloudEvent.Data
                };
            }

            this.Properties = new Properties()
            {
                ContentType = cloudEvent.DataContentType?.MediaType
            };
            this.ApplicationProperties = new ApplicationProperties();
            MapHeaders(cloudEvent);
        }

        void MapHeaders(CloudEvent cloudEvent)
        {
            foreach (var attribute in cloudEvent.GetAttributes())
            {
                if (!attribute.Key.Equals(CloudEventAttributes.DataAttributeName(cloudEvent.SpecVersion)) &&
                    !attribute.Key.Equals(CloudEventAttributes.DataContentTypeAttributeName(cloudEvent.SpecVersion)))
                {
                    if (attribute.Value is Uri)
                    {
                        this.ApplicationProperties.Map.Add("cloudEvents:" + attribute.Key, attribute.Value.ToString());
                    }
                    else if (attribute.Value is DateTime || attribute.Value is DateTime || attribute.Value is string)
                    {
                        this.ApplicationProperties.Map.Add("cloudEvents:" + attribute.Key, attribute.Value);
                    }
                    else
                    {
                        Map dict = new Map();
                        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(attribute.Value))
                        {
                            dict.Add(descriptor.Name, descriptor.GetValue(attribute.Value));
                        }

                        this.ApplicationProperties.Map.Add("cloudEvents:" + attribute.Key, dict);
                    }
                }
            }
        }
    }
예제 #23
0
        /// <summary>
        /// Creates a new instance of Content.
        /// </summary>
        /// <param name="basePath">Path to client directory.</param>
        /// <param name="device">A GraphicsDevice instance.</param>
        private GameContent(string basePath, ContentMode mode, GraphicsDevice device, bool init)
        {
            LoadProgress = ContentLoadingProgress.Started;
            BasePath     = basePath;
            _device      = device;
            Mode         = mode;

            ImageLoader.PremultiplyPNG = 1;// (FSOEnvironment.DirectX)?0:1;

            if (device != null)
            {
                RCMeshes   = new RCMeshProvider(device);
                UIGraphics = new UIGraphicsProvider(this);
                if (TS1)
                {
                    TS1Global      = new TS1Provider(this);
                    AvatarTextures = new TS1AvatarTextureProvider(TS1Global);
                    AvatarMeshes   = new TS1BMFProvider(TS1Global);
                }
                else
                {
                    AvatarTextures = new AvatarTextureProvider(this);
                    AvatarMeshes   = new AvatarMeshProvider(this, _device);
                }
                AvatarHandgroups = new HandgroupProvider(this);
                AbstractTextureRef.FetchDevice        = device;
                AbstractTextureRef.ImageFetchFunction = AbstractTextureRef.ImageFetchWithDevice;
            }
            Changes  = new ChangeManager();
            CustomUI = new CustomUIProvider(this);

            if (TS1)
            {
                var provider = new TS1ObjectProvider(this, TS1Global);
                WorldObjects      = provider;
                WorldCatalog      = provider;
                BCFGlobal         = new TS1BCFProvider(this, TS1Global);
                AvatarAnimations  = new TS1BCFAnimationProvider(BCFGlobal);
                AvatarSkeletons   = new TS1BCFSkeletonProvider(BCFGlobal);
                AvatarAppearances = new TS1BCFAppearanceProvider(BCFGlobal);
                Audio             = new TS1Audio(this);
            }
            else
            {
                AvatarBindings    = new AvatarBindingProvider(this);
                AvatarAppearances = new AvatarAppearanceProvider(this);
                AvatarOutfits     = new AvatarOutfitProvider(this);

                AvatarPurchasables = new AvatarPurchasables(this);
                AvatarCollections  = new AvatarCollectionsProvider(this);
                AvatarThumbnails   = new AvatarThumbnailProvider(this);

                AvatarAnimations = new AvatarAnimationProvider(this);
                AvatarSkeletons  = new AvatarSkeletonProvider(this);
                WorldObjects     = new WorldObjectProvider(this);
                WorldCatalog     = new WorldObjectCatalog();
                Audio            = new Audio(this);
                CityMaps         = new CityMapsProvider(this);
                RackOutfits      = new RackOutfitsProvider(this);
                Ini          = new IniProvider(this);
                GlobalTuning = new Tuning(Path.Combine(basePath, "tuning.dat"));
            }
            WorldFloors        = new WorldFloorProvider(this);
            WorldWalls         = new WorldWallProvider(this);
            WorldObjectGlobals = new WorldGlobalProvider(this);
            WorldRoofs         = new WorldRoofProvider(this);

            InitBasic();
            if (init)
            {
                Init();
            }
        }
예제 #24
0
 internal CSSContentProperty()
     : base(PropertyNames.Content)
 {
     _mode = _normal;
     _inherited = false;
 }
        public AmqpCloudEventMessage(CloudEvent cloudEvent, ContentMode contentMode, ICloudEventFormatter formatter)
        {
            if (contentMode == ContentMode.Structured)
            {
                this.BodySection = new Data
                {
                    Binary = formatter.EncodeStructuredEvent(cloudEvent, out var contentType)
                };
                this.Properties = new Properties()
                {
                    ContentType = contentType.MediaType
                };
                this.ApplicationProperties = new ApplicationProperties();
                MapHeaders(cloudEvent);
                return;
            }

            if (cloudEvent.Data is byte[])
            {
                this.BodySection = new Data {
                    Binary = (byte[])cloudEvent.Data
                };
            }
            else if (cloudEvent.Data is Stream)
            {
                if (cloudEvent.Data is MemoryStream)
                {
                    this.BodySection = new Data {
                        Binary = ((MemoryStream)cloudEvent.Data).ToArray()
                    };
                }
                else
                {
                    var buffer = new MemoryStream();
                    ((Stream)cloudEvent.Data).CopyTo(buffer);
                    this.BodySection = new Data {
                        Binary = buffer.ToArray()
                    };
                }
            }
            else if (cloudEvent.Data is string)
            {
                this.BodySection = new AmqpValue()
                {
                    Value = cloudEvent.Data
                };
            }

            this.Properties = new Properties()
            {
                ContentType = cloudEvent.DataContentType?.MediaType
            };
            this.ApplicationProperties = new ApplicationProperties();
            MapHeaders(cloudEvent);
        }

        void MapHeaders(CloudEvent cloudEvent)
        {
            foreach (var attribute in cloudEvent.GetAttributes())
            {
                if (!attribute.Key.Equals(CloudEventAttributes.DataAttributeName(cloudEvent.SpecVersion)) &&
                    !attribute.Key.Equals(CloudEventAttributes.DataContentTypeAttributeName(cloudEvent.SpecVersion)))
                {
                    string key = "cloudEvents:" + attribute.Key;
                    if (attribute.Value is Uri)
                    {
                        this.ApplicationProperties.Map.Add(key, attribute.Value.ToString());
                    }
                    else if (attribute.Value is DateTimeOffset dto)
                    {
                        // AMQPNetLite doesn't support DateTimeOffset values, so convert to UTC.
                        // That means we can't roundtrip events with non-UTC timestamps, but that's not awful.
                        this.ApplicationProperties.Map.Add(key, dto.UtcDateTime);
                    }
                    else if (attribute.Value is string)
                    {
                        this.ApplicationProperties.Map.Add(key, attribute.Value);
                    }
                    else
                    {
                        Map dict = new Map();
                        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(attribute.Value))
                        {
                            dict.Add(descriptor.Name, descriptor.GetValue(attribute.Value));
                        }

                        this.ApplicationProperties.Map.Add("cloudEvents:" + attribute.Key, dict);
                    }
                }
            }
        }
    }
예제 #26
0
 internal CSSContentProperty()
     : base(PropertyNames.Content)
 {
     _mode      = _normal;
     _inherited = false;
 }
예제 #27
0
    public override void OnInspectorGUI()
    {
        ARController arController = (ARController)target;

        if (arController == null)
        {
            return;
        }

        EditorGUILayout.LabelField("Version", "ARToolKit " + arController.Version);

        EditorGUILayout.Separator();
        if (cameras == null)
        {
            cameras = ARToolKitAssetManager.GetCameras();
        }
        cameraCount = (cameras == null ? 0 : cameras.Length);

        if (!arController.VideoIsStereo)
        {
            if (cameraCount <= 0)
            {
                arController.videoCparamOverride0 = false;
            }
            EditorGUI.BeginDisabledGroup(cameraCount <= 0);
            arController.videoCparamOverride0 = !EditorGUILayout.Toggle("Use automatic camera parameters", !arController.videoCparamOverride0);
            EditorGUI.EndDisabledGroup();
            if (!arController.videoCparamOverride0)
            {
                arController.videoCParamName0 = "";
            }
            else
            {
                arController.EditorCameraIndex = EditorGUILayout.Popup("Camera Parameter", Math.Min(cameraCount - 1, arController.EditorCameraIndex), cameras);
                if (string.Compare(cameras[arController.EditorCameraIndex], arController.videoCParamName0, StringComparison.Ordinal) != 0)
                {
                    arController.videoCParamName0 = cameras[arController.EditorCameraIndex];
                }
            }
            if (cameraCount <= 0)
            {
                EditorGUILayout.HelpBox("No camera parameters found.", MessageType.Info);
            }
        }
        else
        {
            if (cameraCount <= 0)
            {
                arController.videoCparamOverride0 = false;
            }
            EditorGUI.BeginDisabledGroup(cameraCount <= 0);
            arController.videoCparamOverride0 = !EditorGUILayout.Toggle("Use automatic camera parameters (L)", !arController.videoCparamOverride0);
            EditorGUI.EndDisabledGroup();
            if (!arController.videoCparamOverride0)
            {
                arController.videoCParamName0 = "";
            }
            else
            {
                arController.EditorCameraIndex = EditorGUILayout.Popup("Camera Parameter (L)", Math.Min(cameraCount - 1, arController.EditorCameraIndex), cameras);
                if (string.Compare(cameras[arController.EditorCameraIndex], arController.videoCParamName0, StringComparison.Ordinal) != 0)
                {
                    arController.videoCParamName0 = cameras[arController.EditorCameraIndex];
                }
            }
            if (cameraCount <= 0)
            {
                arController.videoCparamOverride1 = false;
            }
            EditorGUI.BeginDisabledGroup(cameraCount <= 0);
            arController.videoCparamOverride1 = !EditorGUILayout.Toggle("Use automatic camera parameters (R)", !arController.videoCparamOverride1);
            EditorGUI.EndDisabledGroup();
            if (!arController.videoCparamOverride1)
            {
                arController.videoCParamName1 = "";
            }
            else
            {
                arController.EditorCameraIndexR = EditorGUILayout.Popup("Camera Parameter (R)", Math.Max(cameraCount - 1, arController.EditorCameraIndexR), cameras);
                if (string.Compare(cameras[arController.EditorCameraIndexR], arController.videoCParamName1, StringComparison.Ordinal) != 0)
                {
                    arController.videoCParamName1 = cameras[arController.EditorCameraIndexR];
                }
            }
            if (cameraCount <= 0)
            {
                EditorGUILayout.HelpBox("No camera parameters found.", MessageType.Info);
            }
        }

        showVideoConfiguration = EditorGUILayout.Foldout(showVideoConfiguration, "Video Configuration");
        if (showVideoConfiguration)
        {
            if (!arController.VideoIsStereo)
            {
                arController.videoConfigurationAndroid0      = EditorGUILayout.TextField("Android", arController.videoConfigurationAndroid0);
                arController.videoConfigurationiOS0          = EditorGUILayout.TextField("iOS", arController.videoConfigurationiOS0);
                arController.videoConfigurationLinux0        = EditorGUILayout.TextField("Linux", arController.videoConfigurationLinux0);
                arController.videoConfigurationMacOSX0       = EditorGUILayout.TextField("macOS", arController.videoConfigurationMacOSX0);
                arController.videoConfigurationWindows0      = EditorGUILayout.TextField("Windows", arController.videoConfigurationWindows0);
                arController.videoConfigurationWindowsStore0 = EditorGUILayout.TextField("Windows Store", arController.videoConfigurationWindowsStore0);
            }
            else
            {
                arController.videoConfigurationAndroid0      = EditorGUILayout.TextField("Android (L)", arController.videoConfigurationAndroid0);
                arController.videoConfigurationAndroid1      = EditorGUILayout.TextField("Android (R)", arController.videoConfigurationAndroid1);
                arController.videoConfigurationiOS0          = EditorGUILayout.TextField("iOS (L)", arController.videoConfigurationiOS0);
                arController.videoConfigurationiOS1          = EditorGUILayout.TextField("iOS (R)", arController.videoConfigurationiOS1);
                arController.videoConfigurationLinux0        = EditorGUILayout.TextField("Linux (L)", arController.videoConfigurationLinux0);
                arController.videoConfigurationLinux1        = EditorGUILayout.TextField("Linux (R)", arController.videoConfigurationLinux1);
                arController.videoConfigurationMacOSX0       = EditorGUILayout.TextField("macOS (L)", arController.videoConfigurationMacOSX0);
                arController.videoConfigurationMacOSX1       = EditorGUILayout.TextField("macOS (R)", arController.videoConfigurationMacOSX1);
                arController.videoConfigurationWindows0      = EditorGUILayout.TextField("Windows (L)", arController.videoConfigurationWindows0);
                arController.videoConfigurationWindows1      = EditorGUILayout.TextField("Windows (R)", arController.videoConfigurationWindows1);
                arController.videoConfigurationWindowsStore0 = EditorGUILayout.TextField("Windows Store (L)", arController.videoConfigurationWindowsStore0);
                arController.videoConfigurationWindowsStore1 = EditorGUILayout.TextField("Windows Store (R)", arController.videoConfigurationWindowsStore1);
            }
            arController.VideoIsStereo = EditorGUILayout.Toggle("Stereo Video Input", arController.VideoIsStereo);
            EditorGUILayout.HelpBox("Check this option if you plan to use two cameras to track the environment. This is not stereoscopic rendering. Note: You will have to configure both left (L) and right (R) cameras separately.", MessageType.Info);
        }

        showVideoOptions = EditorGUILayout.Foldout(showVideoOptions, "Video Background");
        if (showVideoOptions)
        {
            arController.BackgroundLayer0 = EditorGUILayout.LayerField("Background Layer", arController.BackgroundLayer0);

            ContentMode currentContentMode = arController.ContentMode;
            ContentMode newContentMode     = (ContentMode)EditorGUILayout.EnumPopup("Content Mode", currentContentMode);
            if (newContentMode != currentContentMode)
            {
                arController.ContentMode = newContentMode;
            }
            arController.ContentRotate90 = EditorGUILayout.Toggle("Rotate 90° Clockwise", arController.ContentRotate90);
            arController.ContentFlipV    = EditorGUILayout.Toggle("Flip Vertically", arController.ContentFlipV);
            arController.ContentFlipH    = EditorGUILayout.Toggle("Flip Horizontally", arController.ContentFlipH);
        }

        showTwoDTrackingOptions = EditorGUILayout.Foldout(showTwoDTrackingOptions, "2D Tracking Options");
        if (showTwoDTrackingOptions)
        {
            int[]    values = { 1, 2, 3, 4, 5, 6, 7, 8 };
            String[] names  = { "1", "2", "3", "4", "5", "6", "7", "8" };
            arController.TwoDTrackerMaxMarkerCount = EditorGUILayout.IntPopup("Maximum simultaneous trackers:", arController.TwoDTrackerMaxMarkerCount, names, values);
        }

        showSquareTrackingOptions = EditorGUILayout.Foldout(showSquareTrackingOptions, "Square Tracking Options");
        if (showSquareTrackingOptions)
        {
            // Threshold mode selection
            ARController.ARToolKitThresholdMode currentThreshMode = arController.VideoThresholdMode;
            ARController.ARToolKitThresholdMode newThreshMode     = (ARController.ARToolKitThresholdMode)EditorGUILayout.EnumPopup("Mode", currentThreshMode);
            if (newThreshMode != currentThreshMode)
            {
                arController.VideoThresholdMode = newThreshMode;
            }
            EditorGUILayout.HelpBox(ARController.ThresholdModeDescriptions[newThreshMode], MessageType.Info);

            // Show threshold slider only in manual or bracketing modes.
            if (newThreshMode == ARController.ARToolKitThresholdMode.Manual || newThreshMode == ARController.ARToolKitThresholdMode.Bracketing)
            {
                int currentThreshold = arController.VideoThreshold;
                int newThreshold     = EditorGUILayout.IntSlider("Threshold", currentThreshold, 0, 255);
                if (newThreshold != currentThreshold)
                {
                    arController.VideoThreshold = newThreshold;
                }
            }
        }

        showApplicationOptions = EditorGUILayout.Foldout(showApplicationOptions, "Additional Options");
        if (showApplicationOptions)
        {
            arController.AutoStartAR = EditorGUILayout.Toggle("Auto-Start AR.", arController.AutoStartAR);
            if (arController.AutoStartAR)
            {
                EditorGUILayout.HelpBox("ARController.StartAR() will be called during MonoBehavior.Start().", MessageType.Info);
            }
            else
            {
                EditorGUILayout.HelpBox("ARController.StartAR() will not be called during MonoBehavior.Start(); you must call it yourself.", MessageType.Warning);
            }

            arController.QuitOnEscOrBack = EditorGUILayout.Toggle("Quit on [Esc].", arController.QuitOnEscOrBack);
            if (arController.QuitOnEscOrBack)
            {
                EditorGUILayout.HelpBox("The [esc] key (Windows, macOS) or the [Back] button (Android) will quit the app.", MessageType.Info);
            }
            else
            {
                EditorGUILayout.HelpBox("The [esc] key (Windows, macOS) or the [Back] button (Android) will be ignored.", MessageType.Warning);
            }

            arController.LogLevel = (ARController.AR_LOG_LEVEL)EditorGUILayout.EnumPopup("Native Log Level", arController.LogLevel);
        }
    }
예제 #28
0
        Boolean Evaluate(CSSValueList values)
        {
            var items = new List<ContentMode>();

            foreach (var value in values)
            {
                var item = Evaluate(value);

                if (item == null)
                    return false;

                items.Add(item);
            }

            if (items.Count == 0)
                return false;
            else if (items.Count == 1)
                _mode = items[0];
            else
                _mode = new MultiContentMode(items);

            return true;
        }
예제 #29
0
        private void LoadContent()
        {
            if (ModEntry.SeasonTextures != null)
            {
                this.Monitor.Log("SeasonalImmersionMod::Entry has already been called previously, this shouldnt be happening!", LogLevel.Warn);
            }
            this.VerboseLog("Attempting to resolve content pack...");
            if (Directory.Exists(Path.Combine(ModEntry.FilePath, "ContentPack")))
            {
                this.Mode = ContentMode.Directory;
            }
            else if (File.Exists(Path.Combine(ModEntry.FilePath, "ContentPack.zip")))
            {
                try
                {
                    this.Zip  = new ZipFile(Path.Combine(ModEntry.FilePath, "ContentPack.zip"));
                    this.Mode = ContentMode.Zipped;
                }
                catch (Exception ex)
                {
                    this.Monitor.Log($"Was unable to reference ContentPack.zip file, using internal content pack as a fallback.\n{ex.Message}\n{ex.StackTrace}", LogLevel.Error);
                    this.Mode = ContentMode.Internal;
                }
            }
            else
            {
                this.Mode = ContentMode.Internal;
            }

            Stream stream = this.GetStream("manifest.json");

            if (stream == null)
            {
                switch (this.Mode)
                {
                case ContentMode.Directory:
                    this.Monitor.Log("Found `ContentPack` directory but the `manifest.json` file is missing, falling back to internal.", LogLevel.Error);
                    this.Mode = ContentMode.Internal;
                    stream    = this.GetStream("manifest.json");
                    break;

                case ContentMode.Zipped:
                    this.Monitor.Log("Found `ContentPack.zip` file but the `manifest.json` file is missing, falling back to internal.", LogLevel.Error);
                    this.Mode = ContentMode.Internal;
                    stream    = this.GetStream("manifest.json");
                    break;
                }
            }
            if (stream == null && this.Mode == ContentMode.Internal)
            {
                this.Monitor.Log("Attempted to use internal ContentPack but could not resolve manifest, disabling mod.", LogLevel.Error);
                return;
            }

            this.VerboseLog($"Content pack resolved to mode: {this.Mode}");
            ModEntry.SeasonTextures = new Dictionary <string, Dictionary <string, Texture2D> >();
            ContentPackManifest manifest = JsonConvert.DeserializeObject <ContentPackManifest>(new StreamReader(stream).ReadToEnd(), new VersionConverter());

            this.Monitor.Log($"Using the `{manifest.Name}` content pack, version {manifest.Version} by {manifest.Author}", LogLevel.Info);
            // Resolve content dir cause CA messes all stuffs up...
            List <string> Files;

            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "Resources", Game1.content.RootDirectory, "XACT", "FarmerSounds.xgs")))
            {
                Files = new List <string>(Directory.EnumerateFiles(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "Resources", Game1.content.RootDirectory, "Buildings")).Where(a => Path.GetExtension(a).Equals(".xnb")));
            }
            else
            {
                Files = new List <string>(Directory.EnumerateFiles(Path.Combine(Game1.content.RootDirectory, "Buildings")).Where(a => Path.GetExtension(a).Equals(".xnb")));
            }
            Files.AddRange(new[]
            {
                "Flooring.xnb",
                "Craftables.xnb",
                "Craftables_outdoor.xnb",
                "Craftables_indoor.xnb"
            });
            foreach (string file in Files)
            {
                Dictionary <string, Texture2D> textures = new Dictionary <string, Texture2D>();
                string name = Path.GetFileNameWithoutExtension(file);
                this.VerboseLog($"Checking if file is seasonal: {name}");
                int count = 0;
                foreach (string season in ModEntry.Seasons)
                {
                    Texture2D tex = this.GetTexture(Path.Combine(season, name + ".png"));
                    if (tex == null)
                    {
                        continue;
                    }
                    count++;
                    textures.Add(season, tex);
                }

                if (count != 4)
                {
                    if (count > 0)
                    {
                        this.Monitor.Log($"Skipping file due to the textures being incomplete: {file}", LogLevel.Warn);
                    }
                    else
                    {
                        this.VerboseLog($"Skipping file due to there being no textures for it found: {file}");
                    }
                    continue;
                }

                this.VerboseLog($"Making file seasonal: {file}");
                ModEntry.SeasonTextures.Add(name, textures);
            }

            this.Helper.Events.Player.Warped       += this.OnWarped;
            this.Helper.Events.GameLoop.DayStarted += this.OnDayStarted;
            this.Monitor.Log($"ContentPack processed, found [{ModEntry.SeasonTextures.Count}] seasonal files", LogLevel.Info);
        }
예제 #30
0
        public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(int totalSize, int readSize, ContentMode mode)
        {
            if (IsWinHttpHandler &&
                ((mode == ContentMode.SingleChunk && readSize == 0) ||
                 (mode == ContentMode.BytePerChunk)))
            {
                // WinHttpHandler seems to only do a limited amount of draining when TE is used;
                // I *think* it's not draining anything beyond the current chunk being processed.
                // So, these cases won't pass.
                return;
            }

            if (IsCurlHandler)
            {
                // CurlHandler drain behavior is very inconsistent, so just skip these tests.
                return;
            }

            await LoopbackServer.CreateClientAndServerAsync(
                async url =>
            {
                HttpClientHandler handler = CreateHttpClientHandler();

                // Set MaxConnectionsPerServer to 1.  This will ensure we will wait for the previous request to drain (or fail to)
                handler.MaxConnectionsPerServer = 1;

                using (var client = new HttpClient(handler))
                {
                    HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                    ValidateResponseHeaders(response1, totalSize, mode);

                    // Read part but not all of response
                    Stream responseStream = await response1.Content.ReadAsStreamAsync();
                    await ReadToByteCount(responseStream, readSize);

                    response1.Dispose();

                    // Issue another request.  We'll confirm that it comes on the same connection.
                    HttpResponseMessage response2 = await client.GetAsync(url);
                    ValidateResponseHeaders(response2, totalSize, mode);
                    Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
                }
            },
                async server =>
            {
                string content  = new string('a', totalSize);
                string response = GetResponseForContentMode(content, mode);
                await server.AcceptConnectionAsync(async connection =>
                {
                    await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
                    await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
                });
            });
        }
        public async Task GetAsyncLargeRequestWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(int totalSize, int readSize, ContentMode mode)
        {
            // SocketsHttpHandler will reliably drain up to 1MB; other handlers don't.
            if (!UseSocketsHttpHandler)
            {
                return;
            }

            await GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(totalSize, readSize, mode);

            return;
        }
예제 #32
0
        public async Task Controller_WithValidCloudEvent_NoContent_DeserializesUsingPipeline(ContentMode contentMode)
        {
            // Arrange
            var expectedExtensionKey   = "comexampleextension1";
            var expectedExtensionValue = Guid.NewGuid().ToString();
            var cloudEvent             = new CloudEvent
            {
                Type                   = "test-type-æøå",
                Source                 = new Uri("urn:integration-tests"),
                Id                     = Guid.NewGuid().ToString(),
                DataContentType        = "application/json",
                Data                   = new { key1 = "value1" },
                [expectedExtensionKey] = expectedExtensionValue
            };

            var httpContent = new CloudEventHttpContent(cloudEvent, contentMode, new JsonEventFormatter());

            // Act
            var result = await _factory.CreateClient().PostAsync("/api/events/receive", httpContent);

            // Assert
            string resultContent = await result.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Assert.Contains(cloudEvent.Id, resultContent);
            Assert.Contains(cloudEvent.Type, resultContent);
            Assert.Contains($"\"{expectedExtensionKey}\": \"{expectedExtensionValue}\"", resultContent);
        }
        protected static void ValidateResponseHeaders(HttpResponseMessage response, int contentLength, ContentMode mode)
        {
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            switch (mode)
            {
            case ContentMode.ContentLength:
                Assert.Equal(contentLength, response.Content.Headers.ContentLength);
                break;

            case ContentMode.SingleChunk:
            case ContentMode.BytePerChunk:
                Assert.True(response.Headers.TransferEncodingChunked);
                break;
            }
        }
예제 #34
0
        /// <summary>
        /// Converts a CloudEvent to a Kafka message.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        public static Message <string, byte[]> ToKafkaMessage(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            // TODO: Is this appropriate? Why can't we transport a CloudEvent without data in Kafka?
            Validation.CheckArgument(cloudEvent.Data is object, nameof(cloudEvent), "Only CloudEvents with data can be converted to Kafka messages");
            var    headers = MapHeaders(cloudEvent);
            string key     = (string)cloudEvent[Partitioning.PartitionKeyAttribute];

            byte[] value;
            string contentTypeHeaderValue;

            switch (contentMode)
            {
            case ContentMode.Structured:
                value = formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType);
                // TODO: What about the non-media type parts?
                contentTypeHeaderValue = contentType.MediaType;
                break;

            case ContentMode.Binary:
                value = formatter.EncodeBinaryModeEventData(cloudEvent);
                contentTypeHeaderValue = cloudEvent.DataContentType;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            if (contentTypeHeaderValue is object)
            {
                headers.Add(KafkaContentTypeAttributeName, Encoding.UTF8.GetBytes(contentTypeHeaderValue));
            }
            return(new Message <string, byte[]>
            {
                Headers = headers,
                Value = value,
                Key = key
            });
        }
예제 #35
0
    public override void OnInspectorGUI()
    {
        ARController arcontroller = (ARController)target;

        if (arcontroller == null)
        {
            return;
        }


        EditorGUILayout.LabelField("Version", "ARToolKit " + arcontroller.Version);


        EditorGUILayout.Separator();

        showVideoOptions = EditorGUILayout.Foldout(showVideoOptions, "Video Options");
        if (showVideoOptions)
        {
            arcontroller.videoCParamName0           = EditorGUILayout.TextField("Camera parameters", arcontroller.videoCParamName0);
            arcontroller.videoConfigurationWindows0 = EditorGUILayout.TextField("Video config. (Windows)", arcontroller.videoConfigurationWindows0);
            arcontroller.videoConfigurationMacOSX0  = EditorGUILayout.TextField("Video config. (Mac OS X)", arcontroller.videoConfigurationMacOSX0);
            arcontroller.videoConfigurationiOS0     = EditorGUILayout.TextField("Video config. (iOS)", arcontroller.videoConfigurationiOS0);
            arcontroller.videoConfigurationAndroid0 = EditorGUILayout.TextField("Video config. (Android)", arcontroller.videoConfigurationAndroid0);
            arcontroller.BackgroundLayer0           = EditorGUILayout.LayerField("Layer", arcontroller.BackgroundLayer0);

            arcontroller.VideoIsStereo = EditorGUILayout.Toggle("Video source is stereo", arcontroller.VideoIsStereo);
            if (arcontroller.VideoIsStereo)
            {
                arcontroller.videoCParamName1           = EditorGUILayout.TextField("Camera parameters (R)", arcontroller.videoCParamName1);
                arcontroller.videoConfigurationWindows1 = EditorGUILayout.TextField("Video config.(R) (Windows)", arcontroller.videoConfigurationWindows1);
                arcontroller.videoConfigurationMacOSX1  = EditorGUILayout.TextField("Video config.(R) (Mac OS X)", arcontroller.videoConfigurationMacOSX1);
                arcontroller.videoConfigurationiOS1     = EditorGUILayout.TextField("Video config.(R) (iOS)", arcontroller.videoConfigurationiOS1);
                arcontroller.videoConfigurationAndroid1 = EditorGUILayout.TextField("Video config.(R) (Android)", arcontroller.videoConfigurationAndroid1);
                arcontroller.BackgroundLayer1           = EditorGUILayout.LayerField("Layer (R)", arcontroller.BackgroundLayer1);
                arcontroller.transL2RName = EditorGUILayout.TextField("Stereo parameters", arcontroller.transL2RName);
            }

            arcontroller.UseNativeGLTexturingIfAvailable = EditorGUILayout.Toggle("Use native GL texturing (if available)", arcontroller.UseNativeGLTexturingIfAvailable);
            if (arcontroller.UseNativeGLTexturingIfAvailable)
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.Toggle("Allow non-RGB video internally.", false);
                EditorGUI.EndDisabledGroup();
            }
            else
            {
                arcontroller.AllowNonRGBVideo = EditorGUILayout.Toggle("Allow non-RGB video internally.", arcontroller.AllowNonRGBVideo);
            }


            ContentMode currentContentMode = arcontroller.ContentMode;
            ContentMode newContentMode     = (ContentMode)EditorGUILayout.EnumPopup("Content mode", currentContentMode);
            if (newContentMode != currentContentMode)
            {
                arcontroller.ContentMode = newContentMode;
            }
            arcontroller.ContentRotate90 = EditorGUILayout.Toggle("Rotate 90 deg.", arcontroller.ContentRotate90);
            arcontroller.ContentFlipV    = EditorGUILayout.Toggle("Flip vertically", arcontroller.ContentFlipV);
            arcontroller.ContentFlipH    = EditorGUILayout.Toggle("Flip horizontally.", arcontroller.ContentFlipH);
        }

        EditorGUILayout.Separator();

        arcontroller.NearPlane = EditorGUILayout.FloatField("Near plane", arcontroller.NearPlane);
        arcontroller.FarPlane  = EditorGUILayout.FloatField("Far plane", arcontroller.FarPlane);

        EditorGUILayout.Separator();

        showThresholdOptions = EditorGUILayout.Foldout(showThresholdOptions, "Threshold Options");
        if (showThresholdOptions)
        {
            // Threshold mode selection
            ARController.ARToolKitThresholdMode currentThreshMode = arcontroller.VideoThresholdMode;
            ARController.ARToolKitThresholdMode newThreshMode     = (ARController.ARToolKitThresholdMode)EditorGUILayout.EnumPopup("Mode:", currentThreshMode);
            if (newThreshMode != currentThreshMode)
            {
                arcontroller.VideoThresholdMode = newThreshMode;
            }

            // Info about the selected mode
            EditorGUILayout.LabelField("", ARController.ThresholdModeDescriptions[newThreshMode]);

            // Show threshold slider only in manual mode
            if (newThreshMode == ARController.ARToolKitThresholdMode.Manual)
            {
                int currentThreshold = arcontroller.VideoThreshold;
                //int newThreshold = UnityEngine.Mathf.Clamp(EditorGUILayout.IntField("Threshold: ", currentThreshold), 0, 255);
                int newThreshold = EditorGUILayout.IntSlider("Threshold: ", currentThreshold, 0, 255);
                if (newThreshold != currentThreshold)
                {
                    arcontroller.VideoThreshold = newThreshold;
                }
            }
        }

        EditorGUILayout.Separator();

        showSquareTrackingOptions = EditorGUILayout.Foldout(showSquareTrackingOptions, "Square Tracking Options");
        if (showSquareTrackingOptions)
        {
            int currentTemplateSize = arcontroller.TemplateSize;
            int newTemplateSize     = EditorGUILayout.IntField("Template size: ", currentTemplateSize);
            if (newTemplateSize != currentTemplateSize && newTemplateSize >= 16 && newTemplateSize <= 64)
            {
                arcontroller.TemplateSize = newTemplateSize;
            }
            int currentTemplateCountMax = arcontroller.TemplateCountMax;
            int newTemplateCountMax     = EditorGUILayout.IntField("Template count max.: ", currentTemplateCountMax);
            if (newTemplateCountMax != currentTemplateCountMax && newTemplateCountMax > 0)
            {
                arcontroller.TemplateCountMax = newTemplateCountMax;
            }

            // Labeling mode selection.
            ARController.ARToolKitLabelingMode currentLabelingMode = arcontroller.LabelingMode;
            ARController.ARToolKitLabelingMode newLabelingMode     = (ARController.ARToolKitLabelingMode)EditorGUILayout.EnumPopup("Marker borders:", currentLabelingMode);
            if (newLabelingMode != currentLabelingMode)
            {
                arcontroller.LabelingMode = newLabelingMode;
            }

            // Border size selection.
            float currentBorderSize = arcontroller.BorderSize;
            float newBorderSize     = UnityEngine.Mathf.Clamp(EditorGUILayout.FloatField("Border size:", currentBorderSize), 0.0f, 0.5f);
            if (newBorderSize != currentBorderSize)
            {
                arcontroller.BorderSize = newBorderSize;
            }

            // Pattern detection mode selection.
            ARController.ARToolKitPatternDetectionMode currentPatternDetectionMode = arcontroller.PatternDetectionMode;
            ARController.ARToolKitPatternDetectionMode newPatternDetectionMode     = (ARController.ARToolKitPatternDetectionMode)EditorGUILayout.EnumPopup("Pattern detection mode:", currentPatternDetectionMode);
            if (newPatternDetectionMode != currentPatternDetectionMode)
            {
                arcontroller.PatternDetectionMode = newPatternDetectionMode;
            }

            // Matrix code type selection (only when in one of the matrix modes).
            if (newPatternDetectionMode == ARController.ARToolKitPatternDetectionMode.AR_MATRIX_CODE_DETECTION ||
                newPatternDetectionMode == ARController.ARToolKitPatternDetectionMode.AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX ||
                newPatternDetectionMode == ARController.ARToolKitPatternDetectionMode.AR_TEMPLATE_MATCHING_MONO_AND_MATRIX)
            {
                ARController.ARToolKitMatrixCodeType currentMatrixCodeType = arcontroller.MatrixCodeType;
                ARController.ARToolKitMatrixCodeType newMatrixCodeType     = (ARController.ARToolKitMatrixCodeType)EditorGUILayout.EnumPopup("Matrix code type:", currentMatrixCodeType);
                if (newMatrixCodeType != currentMatrixCodeType)
                {
                    arcontroller.MatrixCodeType = newMatrixCodeType;
                }
            }

            // Image processing mode selection.
            ARController.ARToolKitImageProcMode currentImageProcMode = arcontroller.ImageProcMode;
            ARController.ARToolKitImageProcMode newImageProcMode     = (ARController.ARToolKitImageProcMode)EditorGUILayout.EnumPopup("Image processing mode:", currentImageProcMode);
            if (newImageProcMode != currentImageProcMode)
            {
                arcontroller.ImageProcMode = newImageProcMode;
            }
        }

        EditorGUILayout.Separator();

        showNFTTrackingOptions = EditorGUILayout.Foldout(showNFTTrackingOptions, "NFT Tracking Options");
        if (showNFTTrackingOptions)
        {
            arcontroller.NFTMultiMode = EditorGUILayout.Toggle("Multi-page mode", arcontroller.NFTMultiMode);
        }

        EditorGUILayout.Separator();
        showApplicationOptions = EditorGUILayout.Foldout(showApplicationOptions, "Application Options");
        if (showApplicationOptions)
        {
            arcontroller.AutoStartAR = EditorGUILayout.Toggle("Auto-start AR.", arcontroller.AutoStartAR);
            if (arcontroller.AutoStartAR)
            {
                EditorGUILayout.HelpBox("ARController.StartAR() will be called during MonoBehavior.Start().", MessageType.Info);
            }
            else
            {
                EditorGUILayout.HelpBox("ARController.StartAR() will not be called during MonoBehavior.Start(); you must call it yourself.", MessageType.Info);
            }
            arcontroller.QuitOnEscOrBack = EditorGUILayout.Toggle("Quit on [Esc].", arcontroller.QuitOnEscOrBack);
            if (arcontroller.QuitOnEscOrBack)
            {
                EditorGUILayout.HelpBox("The [esc] key (Windows, OS X) or the [Back] button (Android) will quit the app.", MessageType.Info);
            }
            else
            {
                EditorGUILayout.HelpBox("The [esc] key (Windows, OS X) or the [Back] button (Android) will be ignored.", MessageType.Info);
            }
        }
    }
예제 #36
0
 public MarkdownPlusEditorWindow(Window owner, ContentMode mode = ContentMode.FlowDocument)
 {
     InitializeComponent();
     Owner       = owner;
     ContentMode = mode;
 }