示例#1
0
 public CodecDefinition(IFluentTarget rootTarget, ResourceDefinition resourceDefinition, Type codecType, object configuration)
 {
     _rootTarget = rootTarget;
     ResourceDefinition = resourceDefinition;
     _codecRegistration = new CodecModel(codecType, configuration);
     ResourceDefinition.Resource.Codecs.Add(_codecRegistration);
 }
示例#2
0
 public ResourceDocument(ResourceDefinition definition,
                         ResourceMetadata?metadata = null,
                         ResourceSpec?spec         = null,
                         ResourceState?state       = null,
                         KindDescriptor?kind       = null)
 {
     Kind       = kind;
     Metadata   = metadata;
     Definition = definition;
     Spec       = spec;
     State      = state;
 }
示例#3
0
        public static string ResourceUrl(this ResourceDefinition resource, WorkContext context, bool cdnMode = false)
        {
            var result = resource != null
                ? resource.ResolveUrl(new RequireSettings
            {
                DebugMode = context.CurrentSite.ResourceDebugMode == ResourceDebugMode.Enabled,
                CdnMode   = cdnMode
            }, null)
                : null;

            return(result);
        }
        private void AddGoldMines()
        {
            Random random = new Random(93);

            ResourceDefinition resourceDefinition = new ResourceDefinition("Gold");

            for (int i = 0; i < 15; i++)
            {
                Point position = new Point(random.Next(512), random.Next(512));
                MapObjectFactory.AddMine(position, resourceDefinition);
            }
        }
示例#5
0
 public static void prevResource()
 {
     if (resources.IndexOf(resource) <= 0)
     {
         resource = resources[resources.Count - 1];
     }
     else
     {
         resource = resources[resources.IndexOf(resource) - 1];
     }
     onActiveResourceChange();
 }
示例#6
0
 public static void nextResource()
 {
     if (resources.IndexOf(resource) + 1 >= resources.Count)
     {
         resource = resources[0];
     }
     else
     {
         resource = resources[resources.IndexOf(resource) + 1];
     }
     onActiveResourceChange();
 }
        public void ParseFailureNoApplicationDefinition(ApplicationDefinitionParser parser, ILogger logger, MigrationContext context, AzureIntegrationServicesModel model, ParsedBizTalkApplicationGroup group, Exception e)
        {
            "Given a model"
            .x(() =>
            {
                model = new AzureIntegrationServicesModel();
                group = CreateGroup();
                model.MigrationSource.MigrationSourceModel = group;

                var container = new ResourceContainer()
                {
                    Key = group.Applications[0].ResourceContainerKey, Type = ModelConstants.ResourceContainerMsi, ContainerLocation = @"C:\Test\Test.msi"
                };
                model.MigrationSource.ResourceContainers.Add(container);
                var adf      = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ApplicationDefinition xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://Microsoft.BizTalk.ApplicationDeployment/ApplicationDefinition.xsd\">  <Properties>    <Property Name=\"DisplayName\" Value=\"SimpleMessagingApplication\" />    <Property Name=\"Guid\" Value=\"{319AC06C-0FAB-4B68-B2C9-2659DF322B63}\" />    <Property Name=\"Manufacturer\" Value=\"Generated by BizTalk Application Deployment\" />    <Property Name=\"Version\" Value=\"1.0.0.0\" />    <Property Name=\"ApplicationDescription\" Value=\"BizTalk Application 1\" />  </Properties>  <Resources>    <Resource Type=\"System.BizTalk:BizTalkBinding\" Luid=\"Application/SimpleMessagingApplication\">      <Properties>        <Property Name=\"IsDynamic\" Value=\"True\" />        <Property Name=\"IncludeGlobalPartyBinding\" Value=\"True\" />        <Property Name=\"ShortCabinetName\" Value=\"ITEM~0.CAB\" />        <Property Name=\"FullName\" Value=\"BindingInfo.xml\" />        <Property Name=\"Attributes\" Value=\"Archive\" />        <Property Name=\"CreationTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastAccessTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastWriteTime\" Value=\"2020-04-06 16:47:47Z\" />      </Properties>      <Files>        <File RelativePath=\"BindingInfo.xml\" Key=\"Binding\" />      </Files>    </Resource>  </Resources>  <References>    <Reference Name=\"BizTalk.System\" />    <Reference Name=\"Simple Referenced Application\" />  </References></ApplicationDefinition>";
                var resource = new ResourceDefinition()
                {
                    Key = "Applicatcation.adf.Key", Name = "ApplicationDefinition.adf", Type = ModelConstants.ResourceDefinitionApplicationDefinition, ResourceContent = adf
                };
                container.ResourceDefinitions.Add(resource);
            });

            "And a logger"
            .x(() => logger = _mockLogger.Object);

            "And a context"
            .x(() => context = new MigrationContext());

            "And a parser"
            .x(() => parser = new ApplicationDefinitionParser(model, context, logger));

            "When parsing"
            .x(() => e = Record.Exception(() => parser.Parse()));

            "Then the code should not throw an exception"
            .x(() => e.Should().BeNull());

            "And the model should be parsed with a warning."
            .x(() =>
            {
                // There should be no exception logged - this is a handled scenario.
                context.Errors.Count.Should().Be(0);

                // The application definition cannot be read and so the name should be default
                var group = (ParsedBizTalkApplicationGroup)model.MigrationSource.MigrationSourceModel;
                group.Applications[0].Application.Name.Should().Be("(Unknown)");

                // An error should be logged
                var invocation = _mockLogger.Invocations.Where(i => i.Arguments[0].ToString() == "Warning").FirstOrDefault();
                invocation.Should().NotBeNull();
                invocation.Arguments[2].ToString().Should().Contain("Unable to find the application definition");
            });
        }
        public void TestOutput()
        {
            var definition = new ResourceDefinition();

            definition.Type       = "Microsoft.Mock/mockResource";
            definition.Properties = new JObject();
            definition.Properties.Add("foo", (JToken)"bar");

            string json = JsonConvert.SerializeObject(definition);

            Assert.AreEqual("{\"type\":\"Microsoft.Mock/mockResource\",\"properties\":{\"foo\":\"bar\"}}", json);
        }
示例#9
0
        public void ExecuteJobOnce()
        {
            var settlement = new Settlement();
            var villager   = new Villager();
            var definition = new ResourceDefinition("Stone", 1);
            var job        = new CollectJob(new ResourceSource(definition, 15));

            job.AssignedVillagers.Add(villager);
            job.Execute(settlement);
            Assert.IsFalse(job.LimitReached);
            Assert.AreEqual(1, job.AssignedVillagers.Count());
            Assert.AreEqual(1, settlement.StockPile[definition]);
        }
示例#10
0
        public static HtmlString Resource(ResourceDefinition resource, WorkContext context)
        {
            var defaultSettings = new RequireSettings
            {
                DebugMode = context.CurrentSite.ResourceDebugMode == ResourceDebugMode.Enabled,
                Culture   = context.CurrentCulture,
            };

            var appPath = context.HttpContext.Request.ApplicationPath;
            var url     = resource.ResolveUrl(defaultSettings, appPath);

            return(new HtmlString(File.ReadAllText(context.HttpContext.Server.MapPath(url))));
        }
        public static void AddMine(Point position, ResourceDefinition resourceDefinition, int production = 500, JEventBus eventBus = null)
        {
            string structureName = resourceDefinition.Name + "Mine";
            StructureDefinition         structureDefinition         = new StructureDefinition(structureName, new Point(1, 1));
            Structure                   structure                   = new Structure(structureDefinition);
            AddStructureOnWorldMapEvent addStructureOnWorldMapEvent =
                new AddStructureOnWorldMapEvent(structure, position);

            addStructureOnWorldMapEvent.Params.Add("template", "Mine");
            addStructureOnWorldMapEvent.Params.Add("production", production);
            addStructureOnWorldMapEvent.Params.Add("definition", resourceDefinition);
            BaseApi.SendEvent(eventBus, addStructureOnWorldMapEvent);
        }
        public void RegisterJsonResource(ResourceDefinition resource)
        {
            var schema = new JsonSchema(resource);

            this.registeredSchema[resource.Name] = schema;

            JsonSchema baseTypeSchema;

            if (resource.BaseType != null && this.registeredSchema.TryGetValue(resource.BaseType, out baseTypeSchema))
            {
                baseTypeSchema.RegisterChildType(schema);
            }
        }
示例#13
0
        private string GetResourceField(ResourceDefinition rd)
        {
            switch (rd.ResourceKind)
            {
            case ShaderResourceKind.Texture2D:
                return($"thread texture2d<float> {rd.Name};");

            case ShaderResourceKind.Texture2DArray:
                return($"thread texture2d_array<float> {rd.Name};");

            case ShaderResourceKind.Texture2DMS:
                return($"thread texture2d_ms<float> {rd.Name};");

            case ShaderResourceKind.TextureCube:
                return($"thread texturecube<float> {rd.Name};");

            case ShaderResourceKind.Sampler:
            case ShaderResourceKind.SamplerComparison:
                return($"thread sampler {rd.Name};");

            case ShaderResourceKind.Uniform:
                return($"constant {CSharpToShaderType(rd.ValueType.Name)}& {rd.Name};");

            case ShaderResourceKind.StructuredBuffer:
                return($"constant {CSharpToShaderType(rd.ValueType.Name)}* {rd.Name};");

            case ShaderResourceKind.RWStructuredBuffer:
                return($"device {CSharpToShaderType(rd.ValueType.Name)}* {rd.Name};");

            case ShaderResourceKind.RWTexture2D:
                return($"texture2d<float, access::read_write> {rd.Name};");

            case ShaderResourceKind.DepthTexture2D:
                return($"thread depth2d<float> {rd.Name};");

            case ShaderResourceKind.DepthTexture2DArray:
                return($"thread depth2d_array<float> {rd.Name};");

            case ShaderResourceKind.AtomicBuffer:
            {
                string type = rd.ValueType.Name == "ShaderGen.AtomicBufferUInt32"
                        ? "atomic_uint"
                        : "atomic_int";
                return($"device {type}* {rd.Name};");
            }

            default:
                Debug.Fail("Invalid ResourceKind: " + rd.ResourceKind);
                throw new InvalidOperationException();
            }
        }
示例#14
0
    public static ApiResource GetResource(string name, ResourceDefinition definition)
    {
        switch (definition.Profile)
        {
        case ApplicationProfiles.API:
            return(GetAPI(name, definition));

        case ApplicationProfiles.IdentityServerJwt:
            return(GetLocalAPI(name, definition));

        default:
            throw new InvalidOperationException($"Type '{definition.Profile}' is not supported.");
        }
    }
示例#15
0
        internal override void AddResource(string setName, ResourceDefinition rd)
        {
            if (rd.ResourceKind == ShaderResourceKind.Uniform)
            {
                _uniformNames.Add(rd.Name);
            }
            if (rd.ResourceKind == ShaderResourceKind.StructuredBuffer ||
                rd.ResourceKind == ShaderResourceKind.RWStructuredBuffer)
            {
                _ssboNames.Add(rd.Name);
            }

            base.AddResource(setName, rd);
        }
示例#16
0
        /// <summary>
        /// Sorts resources by their name.
        /// </summary>
        /// <param name="x">The first item to be compared.</param>
        /// <param name="y">The second item to be compared.</param>
        /// <returns>An integer indicating the comparison between x and y.</returns>
        public static int SortResourceDefinitionsByTypeAndName(ResourceDefinition x, ResourceDefinition y)
        {
            _ = x ?? throw new ArgumentNullException(nameof(x));
            _ = y ?? throw new ArgumentNullException(nameof(y));

            if (x.Type == y.Type)
            {
                // Equal on type - sort on name
                return(string.Compare(x.Name, y.Name, true, CultureInfo.CurrentCulture));
            }
            ;

            return(string.Compare(ResourceFormatter.GetResourceDefinitionFriendlyName(x.Type), ResourceFormatter.GetResourceDefinitionFriendlyName(y.Type), true, CultureInfo.CurrentCulture));
        }
        /// <summary>
        /// Gets the ultimate full path of a resource, even if it uses CDN. Note that the paths are not uniform, they're
        /// concatenated from the resoure's paths, therefore they can well be virtual relative paths (starting with a tilde)
        /// or relative public urls.
        /// </summary>
        public static string GetFullPath(this ResourceDefinition resource)
        {
            if (string.IsNullOrEmpty(resource.Url))
            {
                return(resource.UrlCdn);
            }

            if (resource.Url.Contains("~"))
            {
                return(resource.Url);
            }

            return(Path.Combine(resource.BasePath, resource.Url));
        }
        public void ParseSuccessfulSingleFilterGroup(ApplicationDefinitionParser parser, ILogger logger, MigrationContext context, AzureIntegrationServicesModel model, ParsedBizTalkApplicationGroup group, Exception e)
        {
            "Given a model"
            .x(() =>
            {
                model = new AzureIntegrationServicesModel();
                group = CreateGroup();
                model.MigrationSource.MigrationSourceModel = group;

                var container = new ResourceContainer()
                {
                    Key = group.Applications[0].ResourceContainerKey, Type = ModelConstants.ResourceContainerMsi, ContainerLocation = @"C:\Test\Test.msi"
                };
                model.MigrationSource.ResourceContainers.Add(container);
                var adf      = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ApplicationDefinition xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://Microsoft.BizTalk.ApplicationDeployment/ApplicationDefinition.xsd\">  <Properties>    <Property Name=\"DisplayName\" Value=\"SimpleMessagingApplication\" />    <Property Name=\"Guid\" Value=\"{319AC06C-0FAB-4B68-B2C9-2659DF322B63}\" />    <Property Name=\"Manufacturer\" Value=\"Generated by BizTalk Application Deployment\" />    <Property Name=\"Version\" Value=\"1.0.0.0\" />    <Property Name=\"ApplicationDescription\" Value=\"BizTalk Application 1\" />  </Properties>  <Resources>    <Resource Type=\"System.BizTalk:BizTalkBinding\" Luid=\"Application/SimpleMessagingApplication\">      <Properties>        <Property Name=\"IsDynamic\" Value=\"True\" />        <Property Name=\"IncludeGlobalPartyBinding\" Value=\"True\" />        <Property Name=\"ShortCabinetName\" Value=\"ITEM~0.CAB\" />        <Property Name=\"FullName\" Value=\"BindingInfo.xml\" />        <Property Name=\"Attributes\" Value=\"Archive\" />        <Property Name=\"CreationTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastAccessTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastWriteTime\" Value=\"2020-04-06 16:47:47Z\" />      </Properties>      <Files>        <File RelativePath=\"BindingInfo.xml\" Key=\"Binding\" />      </Files>    </Resource>  </Resources>  <References>    <Reference Name=\"BizTalk.System\" />    <Reference Name=\"Simple Referenced Application\" />  </References></ApplicationDefinition>";
                var resource = new ResourceDefinition()
                {
                    Key = "Applicatcation.adf.Key", Name = "ApplicationDefinition.adf", Type = ModelConstants.ResourceDefinitionApplicationDefinition, ResourceContent = adf
                };
                container.ResourceDefinitions.Add(resource);

                group.Applications[0].Application.ApplicationDefinition = new ApplicationDefinitionFile(container.Key, resource.Key);
            });

            "And a logger"
            .x(() => logger = _mockLogger.Object);

            "And a context"
            .x(() => context = new MigrationContext());

            "And a parser"
            .x(() => parser = new ApplicationDefinitionParser(model, context, logger));

            "When parsing"
            .x(() => e = Record.Exception(() => parser.Parse()));

            "Then the code should not throw an exception"
            .x(() => e.Should().BeNull());

            "And the filter group should be correctly parsed."
            .x(() =>
            {
                var applicationDefinition = group.Applications[0].Application.ApplicationDefinition.ApplicationDefinition;
                applicationDefinition.Should().NotBeNull();
                applicationDefinition.Properties.Length.Should().Be(5);
                applicationDefinition.Resources.Length.Should().Be(1);
                applicationDefinition.References.Length.Should().Be(2);
            });
        }
        private static void AddChests()
        {
            Random random = new Random(1234);

            ResourceDefinition resourceDefinition = new ResourceDefinition("Chest");

            for (int i = 0; i < 10; i++)
            {
                Point    position = new Point(random.Next(512), random.Next(512));
                Resource resource = new Resource(resourceDefinition);
                AddResourceOnWorldMapEvent addResourceOnWorldMapEvent =
                    new AddResourceOnWorldMapEvent(resource, position);
                JEventBus.GetDefault().Post(addResourceOnWorldMapEvent);
            }
        }
示例#20
0
        /// <summary>
        /// Called before a resource is updated in the storage layer.
        /// </summary>
        /// <remarks>
        /// Use requestContext.ApiVersion to get the API version of the request.
        /// </remarks>
        /// <param name="requestContext">The request context.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="existingResource">The existing resource.</param>
        /// <param name="updatedResourceDefinition">The updated resource definition.</param>
        Task <ResourceOperationStatus> IManagedResourceGroupWideResourceTypeRequestHandler.OnUpdateResource(
            RequestContext requestContext,
            SubscriptionNotificationDefinition subscription,
            IResourceEntity existingResource,
            ResourceDefinition updatedResourceDefinition)
        {
            ArgumentValidator.ValidateNotNull("requestContext", requestContext);
            ArgumentValidator.ValidateNotNull("subscription", subscription);
            ArgumentValidator.ValidateNotNull("existingResource", existingResource);
            ArgumentValidator.ValidateNotNull("updatedResourceDefinition", updatedResourceDefinition);

            // TODO: Implement custom logic to update the resource.

            return(Task.FromResult(ResourceOperationStatus.CompleteSynchronously(existingResource)));
        }
示例#21
0
        private static Color32 getDepositColor(ResourceDefinition definition, BodyResourceData bodyResources, double?deposit)
        {
            Color32 color;

            if (deposit != null)
            {
                var ratio = (float)(deposit.Value / bodyResources.Resources.MaxQuantity);
                color = (Color32)(definition.ColorFull * ratio + definition.ColorEmpty * (1 - ratio));
            }
            else
            {
                color = colorEmpty;
            }
            return(color);
        }
示例#22
0
        protected override void WriteStructuredBuffer(StringBuilder sb, ResourceDefinition rd, bool isReadOnly, int index)
        {
            string valueType = rd.ValueType.Name;
            string type      = valueType == "ShaderGen.AtomicBufferUInt32"
                ? "uint"
                : valueType == "ShaderGen.AtomicBufferInt32"
                    ? "int"
                    : CSharpToShaderType(rd.ValueType.Name);
            string readOnlyStr = isReadOnly ? " readonly" : " ";

            sb.AppendLine($"layout(std430, binding = {index}){readOnlyStr} buffer {rd.Name}");
            sb.AppendLine("{");
            sb.AppendLine($"    {type} field_{CorrectIdentifier(rd.Name.Trim())}[];");
            sb.AppendLine("};");
        }
示例#23
0
        public void Discover(ShapeTableBuilder builder)
        {
            var availableFeatures = _extensionManager.AvailableFeatures();
            var activeFeatures    = availableFeatures.Where(FeatureIsEnabled);
            var activeExtensions  = Once(activeFeatures);

            var hits = activeExtensions.SelectMany(extensionDescriptor =>
            {
                var basePath    = Path.Combine(extensionDescriptor.Location, extensionDescriptor.Id).Replace(Path.DirectorySeparatorChar, '/');
                var virtualPath = Path.Combine(basePath, GetFolder()).Replace(Path.DirectorySeparatorChar, '/');
                var shapes      = _virtualPathProvider.ListFiles(virtualPath)
                                  .Select(Path.GetFileName)
                                  .Where(fileName => string.Equals(Path.GetExtension(fileName), GetFileExtension(), StringComparison.OrdinalIgnoreCase))
                                  .Select(cssFileName => new
                {
                    fileName        = Path.GetFileNameWithoutExtension(cssFileName),
                    fileVirtualPath = Path.Combine(virtualPath, cssFileName).Replace(Path.DirectorySeparatorChar, '/'),
                    shapeType       = GetShapePrefix() + GetAlternateShapeNameFromFileName(cssFileName),
                    extensionDescriptor
                });
                return(shapes);
            });

            foreach (var iter in hits)
            {
                var hit = iter;
                var featureDescriptors = hit.extensionDescriptor.Features.Where(fd => fd.Id == hit.extensionDescriptor.Id);
                foreach (var featureDescriptor in featureDescriptors)
                {
                    builder.Describe(iter.shapeType)
                    .From(new Feature {
                        Descriptor = featureDescriptor
                    })
                    .BoundAs(
                        hit.fileVirtualPath,
                        shapeDescriptor => displayContext =>
                    {
                        var shape  = ((dynamic)displayContext.Value);
                        var output = displayContext.ViewContext.Writer;
                        ResourceDefinition resource            = shape.Resource;
                        string condition                       = shape.Condition;
                        Dictionary <string, string> attributes = shape.TagAttributes;
                        ResourceManager.WriteResource(output, resource, hit.fileVirtualPath, condition, attributes);
                        return(null);
                    });
                }
            }
        }
示例#24
0
        private static ResourceDefinitionForClient MapResourceDefinition(ResourceDefinition def)
        {
            return(new ResourceDefinitionForClient
            {
                MainMenuIcon = def.MainMenuIcon,
                MainMenuSortKey = def.MainMenuSortKey ?? 0m,
                MainMenuSection = def.MainMenuSection,
                TitlePlural = def.TitlePlural,
                TitlePlural2 = def.TitlePlural2,
                TitlePlural3 = def.TitlePlural3,
                TitleSingular = def.TitleSingular,
                TitleSingular2 = def.TitleSingular2,
                TitleSingular3 = def.TitleSingular3,

                IdentifierLabel = def.IdentifierLabel,
                IdentifierLabel2 = def.IdentifierLabel2,
                IdentifierLabel3 = def.IdentifierLabel3,
                IdentifierVisibility = MapVisibility(def.IdentifierVisibility),
                CurrencyVisibility = MapVisibility(def.CurrencyVisibility),
                CountUnitVisibility = MapVisibility(def.CountUnitVisibility),
                MassUnitVisibility = MapVisibility(def.MassUnitVisibility),
                VolumeUnitVisibility = MapVisibility(def.VolumeUnitVisibility),
                TimeUnitVisibility = MapVisibility(def.TimeUnitVisibility),
                DescriptionVisibility = MapVisibility(def.DescriptionVisibility),
                AvailableSinceLabel = def.AvailableSinceLabel,
                AvailableSinceLabel2 = def.AvailableSinceLabel2,
                AvailableSinceLabel3 = def.AvailableSinceLabel3,
                AvailableSinceVisibility = MapVisibility(def.AvailableSinceVisibility),
                AvailableTillLabel = def.AvailableTillLabel,
                AvailableTillLabel2 = def.AvailableTillLabel2,
                AvailableTillLabel3 = def.AvailableTillLabel3,
                AvailableTillVisibility = MapVisibility(def.AvailableTillVisibility),
                Lookup1Label = def.Lookup1Label,
                Lookup1Label2 = def.Lookup1Label2,
                Lookup1Label3 = def.Lookup1Label3,
                Lookup1Visibility = MapVisibility(def.Lookup1Visibility),
                Lookup1DefinitionId = def.Lookup1DefinitionId,
                Lookup2Label = def.Lookup2Label,
                Lookup2Label2 = def.Lookup2Label2,
                Lookup2Label3 = def.Lookup2Label3,
                Lookup2Visibility = MapVisibility(def.Lookup2Visibility),
                Lookup2DefinitionId = def.Lookup2DefinitionId,
                DueDateLabel = def.DueDateLabel,
                DueDateLabel2 = def.DueDateLabel2,
                DueDateLabel3 = def.DueDateLabel3,
                DueDateVisibility = MapVisibility(def.DueDateVisibility),
            });
        }
示例#25
0
        public int ExecuteJobToLimit(ResourceDefinition definition, int resourceAmount, int limit)
        {
            var settlement = new Settlement();
            var villager   = new Villager();
            var job        = new CollectJob(new ResourceSource(definition, resourceAmount), limit);

            job.AssignedVillagers.Add(villager);
            Assert.IsFalse(job.LimitReached);
            for (var i = 0; i < resourceAmount; i++)
            {
                job.Execute(settlement);
            }

            Assert.AreEqual(1, job.AssignedVillagers.Count());
            return(settlement.StockPile[definition]);
        }
        private static string StringifyAttributes(this ResourceDefinition resource)
        {
            if (resource.TagBuilder.Attributes.Count == 0)
            {
                return("");
            }

            var sb = new StringBuilder();

            foreach (var item in resource.TagBuilder.Attributes)
            {
                sb.Append(item.Key + "-" + item.Value);
            }

            return(sb.ToString());
        }
示例#27
0
        public ResourceDocument Patch(ResourceDocument patchDocument)
        {
            var definition = new ResourceDefinition(ResourceFieldCollection.Patch(Definition.Fields, patchDocument.Definition.Fields));
            var metadata   = (Metadata != null) ?
                             new ResourceMetadata(ResourceFieldCollection.Patch(Metadata?.Fields, patchDocument.Metadata?.Fields)) : null;
            var spec = (Spec != null) ?
                       new ResourceSpec(ResourceFieldCollection.Patch(Spec?.Fields, patchDocument.Spec?.Fields)) : null;
            var state = (State != null) ?
                        new ResourceState(ResourceFieldCollection.Patch(State?.Fields, patchDocument.State?.Fields)) : null;

            return(new ResourceDocument(
                       definition, metadata,
                       spec, state,
                       Kind
                       ));
        }
示例#28
0
        private void VerifyComplexType(ComplexType testType, ResourceDefinition resource)
        {
            Assert.AreEqual($"{this.schema.Namespace}.{testType.Name}", resource.Name, "Resource name does not match");

            // Ignore the odata.type property
            var resourceProperties = resource.Parameters.Where(p => p.Name != "@odata.type" && !p.IsNavigatable).ToList();

            Assert.AreEqual(testType.Properties.Count, resourceProperties.Count(), "Property count does not match");

            for (int i = 0; i < resourceProperties.Count; i++)
            {
                Assert.AreEqual(testType.Properties[i].Name, resourceProperties[i].Name, "Name of property does not match");
                Assert.AreEqual(testType.Properties[i].Type, resourceProperties[i].Type.ODataResourceName(), "Type of property {0} does not match", testType.Properties[i].Name);
                Assert.AreEqual(testType.Properties[i].ToDocumentationProperty(this.entityFramework, testType).Description, resourceProperties[i].Description, "Description for property {0} does not match", testType.Properties[i].Name);
            }
        }
示例#29
0
        public void ResourceCreateNestedResourceTest()
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = serviceConfiguration.Manifest.DefaultEndpointTimeout;
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicAuthHeaderValue);

                // Create a subscription context. All resources must be created in the context of a subscription.
                using (var subscriptionContext = new SubscriptionContext(httpClient, providerNamespace: ManifestFactory.Namespace))
                {
                    // Create the resource
                    var firstRootResource = CreateRootResourceDefinition(
                        subscriptionId: subscriptionContext.SubscriptionId,
                        resourceGroup: TestResourceGroup,
                        resourceName: "firstResource");
                    ResourceDefinition resourceResponse = PutResource(
                        httpClient: httpClient,
                        resourceDefinition: firstRootResource,
                        isCreateRequest: true);
                    Assert.AreEqual(firstRootResource.Id, resourceResponse.Id);

                    // Create the first nested resource
                    var nestedResource1 = CreateNestedResourceDefinition(
                        subscriptionId: subscriptionContext.SubscriptionId,
                        resourceGroup: TestResourceGroup,
                        resourceName: "nestedResource1",
                        parentResource: firstRootResource);
                    resourceResponse = PutResource(
                        httpClient: httpClient,
                        resourceDefinition: nestedResource1,
                        isCreateRequest: true);
                    Assert.AreEqual(nestedResource1.Id, resourceResponse.Id);

                    // Create the second nested resource
                    var nestedResource2 = CreateNestedResourceDefinition(
                        subscriptionId: subscriptionContext.SubscriptionId,
                        resourceGroup: TestResourceGroup,
                        resourceName: "nestedResource2",
                        parentResource: firstRootResource);
                    resourceResponse = PutResource(
                        httpClient: httpClient,
                        resourceDefinition: nestedResource2,
                        isCreateRequest: true);
                    Assert.AreEqual(nestedResource2.Id, resourceResponse.Id);
                }
            }
        }
示例#30
0
        protected override IEnumerable <OutputImage> GetOutputImages(ResourceDefinition resource)
        {
            (var outputFileName, var ignore, var masterScale) = resource.GetConfiguration(Platform.iOS);
            if (ignore)
            {
                return(Array.Empty <OutputImage>());
            }

            // Check for appiconset
            var assetsIconSetBasePath = Path.Combine(
                "Assets.xcassets",
                $"{outputFileName}.appiconset");
            var mediaRootIconSetBasePath = Path.Combine(
                "Media.xcassets",
                $"{outputFileName}.appiconset");
            var mediaIconSetBasePath = Path.Combine(
                "Resources",
                "Assets.xcassets",
                $"{outputFileName}.appiconset");

            if (Directory.Exists(Path.Combine(Build.ProjectDirectory, assetsIconSetBasePath)))
            {
                return(GetAppIconSet(resource, assetsIconSetBasePath, outputFileName, masterScale));
            }
            else if (Directory.Exists(Path.Combine(Build.ProjectDirectory, mediaRootIconSetBasePath)))
            {
                return(GetAppIconSet(resource, mediaRootIconSetBasePath, outputFileName, masterScale));
            }
            else if (Directory.Exists(Path.Combine(Build.ProjectDirectory, mediaIconSetBasePath)))
            {
                return(GetAppIconSet(resource, mediaIconSetBasePath, outputFileName, masterScale));
            }
            else
            {
                Log.LogMessage($"Found image {resource.InputFilePath} -> Resources/{outputFileName}.png");
                // Generate App Resources
                return(ResourceSizes.Select(x => new OutputImage
                {
                    InputFile = resource.InputFilePath,
                    OutputFile = Path.Combine(Build.IntermediateOutputPath, "Resources", $"{outputFileName}{x.Key}.png"),
                    OutputLink = Path.Combine("Resources", $"{outputFileName}{x.Key}.png"),
                    Scale = masterScale * x.Value,
                    ShouldBeVisible = true,
                    WatermarkFilePath = GetWatermarkFilePath(resource)
                }));
            }
        }
示例#31
0
        public void Update()
        {
            if (HighLogic.LoadedScene != GameScenes.FLIGHT && HighLogic.LoadedScene != GameScenes.TRACKSTATION)
            {
                Destroy(gameObject);
                return;
            }

            if (!MapView.MapIsEnabled || !ShowOverlay || MapView.MapCamera == null || KethaneData.Current == null)
            {
                overlayRenderer.IsVisible = false;
                return;
            }

            overlayRenderer.IsVisible = true;

            var target = MapView.MapCamera.target;

            var newBody     = getTargetBody(target);
            var bodyChanged = (newBody != null) && (newBody != body);

            if (bodyChanged)
            {
                body = newBody;

                heightAt = getHeightRatioMap();
                bounds   = new BoundsMap(heightAt, KethaneData.GridLevel);

                overlayRenderer.SetHeightMap(heightAt);

                var radius = bodyRadii.ContainsKey(body) ? bodyRadii[body] : 1.025;
                var parent = ScaledSpace.Instance.scaledSpaceTransforms.FirstOrDefault(t => t.name == body.name);
                overlayRenderer.SetRadiusMultiplier((float)radius);
                overlayRenderer.SetTarget(parent);
            }

            if (bodyChanged || resource == null || resource.Resource != SelectedResource)
            {
                resource = KethaneController.ResourceDefinitions.Where(r => r.Resource == SelectedResource).Single();
                refreshCellColors();
            }

            var ray = MapView.MapCamera.camera.ScreenPointToRay(Input.mousePosition);

            hoverCell = Cell.Raycast(ray, KethaneData.GridLevel, bounds, heightAt, gameObject.transform);
        }
示例#32
0
        private void updateMapView()
        {
            if (!MapView.MapIsEnabled || !ShowOverlay || MapView.MapCamera == null || KethaneData.Current == null)
            {
                gameObject.renderer.enabled = false;
                return;
            }

            gameObject.renderer.enabled = true;

            var target = MapView.MapCamera.target;

            var newBody = getTargetBody(target);
            var bodyChanged = (newBody != null) && (newBody != body);
            if (bodyChanged)
            {
                body = newBody;

                refreshMesh();
                refreshCollider();

                var radius = bodyRadii.ContainsKey(body) ? bodyRadii[body] : 1.025;
                var parent = ScaledSpace.Instance.scaledSpaceTransforms.FirstOrDefault(t => t.name == body.name);
                if (parent != null)
                {
                    gameObject.transform.parent = parent;
                }
                gameObject.transform.localScale = Vector3.one * 1000f * (float)radius;
                gameObject.transform.localPosition = Vector3.zero;
                gameObject.transform.localRotation = Quaternion.identity;
            }

            if (bodyChanged || resource == null || resource.Resource != SelectedResource)
            {
                resource = KethaneController.ResourceDefinitions.Where(r => r.Resource == SelectedResource).Single();
                refreshCellColors();
            }

            var ray = MapView.MapCamera.camera.ScreenPointToRay(Input.mousePosition);
            hoverCell = Cell.Raycast(ray, KethaneData.GridLevel, bounds, heightAt, gameObject.transform);
        }
 public void RegisterJsonResource(ResourceDefinition resource)
 {
     var schema = new JsonSchema(resource);
     this.registeredSchema[resource.Metadata.ResourceType] = schema;
 }
    public List<ResourceDefinition> ReadJavaScriptResource(string filePath)
    {
        string inputString;

        List<ResourceDefinition> lstResDef = new List<ResourceDefinition>();

        using (StreamReader streamReader = File.OpenText(filePath))
        {
            inputString = streamReader.ReadLine();
            while (inputString != null)
            {

                string regexPattern = "(\"(?<key>[^\"]+)\"\\s*:\\s*\"(?<value>[^\"]+)\")|(\'(?<key>[^\']+)\'\\s*:\\s*\'(?<value>[^\']+)\')";
                Regex regex = new Regex(regexPattern, RegexOptions.IgnorePatternWhitespace);
                if (regex.IsMatch(inputString))
                {
                    Match match = regex.Match(inputString);

                    string key = match.Groups[3].Value.Trim();
                    string value = match.Groups[4].Value.Trim();
                    ResourceDefinition resDef = new ResourceDefinition();
                    resDef.Key = key;
                    resDef.Value = value;
                    lstResDef.Add(resDef);
                }

                inputString = streamReader.ReadLine();
            }

        }

        return lstResDef;
    }
示例#35
0
 public JsonSchema(ResourceDefinition resource)
 {
     this.Metadata = resource.Metadata;
     this.ExpectedProperties = this.BuildSchemaFromJson(resource.JsonExample, resource.Parameters);
     this.OriginalResource = resource;
 }
    public List<ResourceDefinition> ReadResourceFile(string filePath)
    {
        string defaultFile = filePath;
        defaultFile = LocalizationHelper.GetDefaultFilePath(filePath);

        Dictionary<string, string> resxDict = new Dictionary<string, string>();
        Dictionary<string, string> resxDictDef = new Dictionary<string, string>();

        if (resxDictDef.Count == 0)
        {
            //this.divNoData.Visible = true;
        }
        else if (resxDictDef.Count > 0)
        {

            //this.divNoData.Visible = false;
        }
        if (File.Exists(filePath))
        {
            resxDict = ResXHelper.ReadResX(filePath);
            resxDictDef = ResXHelper.ReadResX(defaultFile);
        }
        else
        {
            resxDictDef = ResXHelper.ReadResX(defaultFile);
        }
        List<ResourceDefinition> resxList = new List<ResourceDefinition>();
        foreach (KeyValuePair<string, string> kvp in resxDict)
        {
            if (kvp.Value != "")
            {
                ResourceDefinition obj = new ResourceDefinition();
                obj.Key = kvp.Key;
                obj.Value = kvp.Value;
                resxList.Add(obj);
            }

        }
        List<ResourceDefinition> resxListFinal = new List<ResourceDefinition>();
        foreach (KeyValuePair<string, string> kvp in resxDictDef)
        {
            if (kvp.Value != "")
            {
                int index = resxList.FindIndex(
                    delegate(ResourceDefinition objDef)
                    {
                        return (objDef.Key == kvp.Key);
                    }
                    );
                if (index > -1)
                {
                    ResourceDefinition obj = new ResourceDefinition();
                    obj.Key = kvp.Key;
                    obj.Value = resxList[index].Value;
                    obj.DefaultValue = kvp.Value;
                    resxListFinal.Add(obj);
                }
            }
        }
        return resxListFinal;
    }
    public void GetResxKeyValueList(ref List<ResourceDefinition> lstResDef)
    {
        foreach (GridViewRow row in gdvResxKeyValue.Rows)
        {
            ResourceDefinition obj = new ResourceDefinition();
            obj.Key = ((Label)row.FindControl("lblKey")).Text;
            obj.Value = ((TextBox)row.FindControl("txtResxValue")).Text;
            lstResDef.Add(obj);

        }
    }
示例#38
0
 private static Color32 getDepositColor(ResourceDefinition definition, BodyResourceData bodyResources, double? deposit)
 {
     Color32 color;
     if (deposit != null)
     {
         var ratio = (float)(deposit.Value / bodyResources.Resources.MaxQuantity);
         color = (Color32)(definition.ColorFull * ratio + definition.ColorEmpty * (1 - ratio));
     }
     else
     {
         color = colorEmpty;
     }
     return color;
 }
    public List<ResourceDefinition> ReadXMLResource(string filePath)
    {
        string defaultFile = filePath;
        defaultFile = LocalizationHelper.GetDefaultFilePath(filePath);

        List<ResourceDefinition> xmlList = new List<ResourceDefinition>();
        List<ResourceDefinition> xmlListDef = new List<ResourceDefinition>();
        List<ResourceDefinition> xmlListFinal = new List<ResourceDefinition>();


        if (File.Exists(filePath))
        {
            xmlList = ReadXml(filePath);
            xmlListDef = ReadXml(defaultFile);
        }
        else
        {
            xmlListDef = ReadXml(defaultFile);
        }
        List<ResourceDefinition> resxListFinal = new List<ResourceDefinition>();
        foreach (ResourceDefinition kvp in xmlListDef)
        {
            if (kvp.Value != "")
            {
                int index = xmlList.FindIndex(
                    delegate(ResourceDefinition objDef)
                    {
                        return (objDef.Key == kvp.Key);
                    }
                    );
                if (index > -1)
                {
                    ResourceDefinition obj = new ResourceDefinition();
                    obj.Key = kvp.Key;
                    obj.Value = xmlList[index].Value;
                    obj.DefaultValue = kvp.Value;
                    xmlListFinal.Add(obj);
                }
            }

        }
        return xmlListFinal;
    }
示例#40
0
 public CodecDefinition(ResourceDefinition resourceDefinition, Type codecType, object configuration)
 {
     ResourceDefinition = resourceDefinition;
     this.codecRegistration = new CodecModel(codecType, configuration);
     ResourceDefinition.Registration.Codecs.Add(this.codecRegistration);
 }
示例#41
0
        public void Update()
        {
            if (HighLogic.LoadedScene != GameScenes.FLIGHT && HighLogic.LoadedScene != GameScenes.TRACKSTATION)
            {
                Destroy(gameObject);
                return;
            }

            if (!MapView.MapIsEnabled || !ShowOverlay || MapView.MapCamera == null || KethaneData.Current == null)
            {
                overlayRenderer.IsVisible = false;
                return;
            }

            overlayRenderer.IsVisible = true;

            var target = MapView.MapCamera.target;

            var newBody = getTargetBody(target);
            var bodyChanged = (newBody != null) && (newBody != body);
            if (bodyChanged)
            {
                body = newBody;

                heightAt = getHeightRatioMap();
                bounds = new BoundsMap(heightAt, KethaneData.GridLevel);

                overlayRenderer.SetHeightMap(heightAt);

                var radius = bodyRadii.ContainsKey(body) ? bodyRadii[body] : 1.025;
                var parent = ScaledSpace.Instance.scaledSpaceTransforms.FirstOrDefault(t => t.name == body.name);
                overlayRenderer.SetRadiusMultiplier((float)radius);
                overlayRenderer.SetTarget(parent);
            }

            if (bodyChanged || resource == null || resource.Resource != SelectedResource)
            {
                resource = KethaneController.ResourceDefinitions.Where(r => r.Resource == SelectedResource).Single();
                refreshCellColors();
            }

            var ray = MapView.MapCamera.camera.ScreenPointToRay(Input.mousePosition);
            hoverCell = Cell.Raycast(ray, KethaneData.GridLevel, bounds, heightAt, gameObject.transform);
        }
    public List<ResourceDefinition> ReadXml(string filePath)
    {
         List<ResourceDefinition> resxList = new List<ResourceDefinition>();
        string xmlFile = filePath;
        string defaultFile = LocalizationHelper.GetDefaultFilePath(filePath);

        if (File.Exists(xmlFile))
        {
            XmlDocument currentDocument = new XmlDocument();
            try
            {
                currentDocument.Load(xmlFile);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            XmlNodeList nodeList = currentDocument.DocumentElement.ChildNodes;
            IDictionary<string, string> keyValuePairList = new Dictionary<string, string>();
            foreach (XmlNode node in nodeList)
            {
                Displaychild(node, currentDocument.DocumentElement, keyValuePairList);
            }

            foreach (KeyValuePair<string, string> kvp in keyValuePairList)
            {

                ResourceDefinition obj = new ResourceDefinition();
                obj.Key = kvp.Key;
                obj.Value = kvp.Value.Replace("\"", "");
                resxList.Add(obj);

            }
        }
        return resxList;

    }