private Context CreateContext()
        {
            var conf = new Configuration();
            var sampleClassMapping = new ResourceMapping<SampleClass>(c => c.Id, "http://sampleClass/{id}");
            sampleClassMapping.ResourceType = "sampleClasses";
            sampleClassMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            sampleClassMapping.AddPropertyGetter("nestedValue", c => c.NestedValue);

            var nestedClassMapping = new ResourceMapping<NestedClass>(c => c.Id, "nested/{id}");
            nestedClassMapping.ResourceType = "nestedClasses";
            nestedClassMapping.AddPropertyGetter("someNestedValue", c => c.SomeNestedValue);

            var linkMapping = new LinkMapping<SampleClass, NestedClass>()
            {
                RelationshipName = "nestedValues",
                ResourceMapping = nestedClassMapping,
                ResourceGetter = c => c.NestedValue,
                ResourceIdGetter = c => c.NestedValueId
            };

            sampleClassMapping.Relationships.Add(linkMapping);

            conf.AddMapping(sampleClassMapping);
            conf.AddMapping(nestedClassMapping);

            return new Context
            {
                Configuration = conf,
                RoutePrefix = appUrl
            };
        }
Пример #2
0
        private void InitializeScheduler()
        {
            InitHelper.InitResources(CustomResourceCollection);
            InitHelper.InitAppointments(CustomEventList, CustomResourceCollection);

            ResourceMapping mappingsResource = this.scheduler.Storage.ResourceStorage.Mappings;

            mappingsResource.Id      = "ResID";
            mappingsResource.Caption = "Name";

            AppointmentMapping mappingsAppointment = this.scheduler.Storage.AppointmentStorage.Mappings;

            mappingsAppointment.Start          = "StartTime";
            mappingsAppointment.End            = "EndTime";
            mappingsAppointment.Subject        = "Subject";
            mappingsAppointment.AllDay         = "AllDay";
            mappingsAppointment.Description    = "Description";
            mappingsAppointment.Label          = "Label";
            mappingsAppointment.Location       = "Location";
            mappingsAppointment.RecurrenceInfo = "RecurrenceInfo";
            mappingsAppointment.ReminderInfo   = "ReminderInfo";
            mappingsAppointment.ResourceId     = "OwnerId";
            mappingsAppointment.Status         = "Status";
            mappingsAppointment.Type           = "EventType";

            this.scheduler.Storage.BeginUpdate();
            this.scheduler.Storage.ResourceStorage.DataSource    = CustomResourceCollection;
            this.scheduler.Storage.AppointmentStorage.DataSource = CustomEventList;
            this.scheduler.Storage.EndUpdate();

            this.scheduler.Start          = DateTime.Now;
            this.scheduler.ActiveViewType = DevExpress.XtraScheduler.SchedulerViewType.Day;
        }
Пример #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceDependency"/> class.
 /// </summary>
 /// <param name="resource">The resource.</param>
 /// <param name="referringTemplateObject">The parsed AWS template object relating to the resource being imported.</param>
 /// <param name="referencedTemplateObject">The parsed AWS template object relating to the referenced resource.</param>
 public ResourceDependency(ResourceMapping resource, IResource referringTemplateObject, IResource referencedTemplateObject)
 {
     this.DependencyType           = DependencyType.Resource;
     this.Resource                 = resource;
     this.ReferringTemplateObject  = referringTemplateObject;
     this.ReferencedTemplateObject = referencedTemplateObject;
 }
Пример #4
0
        private Context CreateContext()
        {
            var conf = new Configuration();
            var sampleClassMapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            sampleClassMapping.ResourceType = "sampleClasses";
            sampleClassMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            sampleClassMapping.AddPropertyGetter("nestedValue", c => c.NestedValue);


            var nestedClassMapping = new ResourceMapping <NestedClass>(c => c.Id, "nested/{id}");

            nestedClassMapping.ResourceType = "nestedClasses";
            nestedClassMapping.AddPropertyGetter("someNestedValue", c => c.SomeNestedValue);

            var linkMapping = new LinkMapping <SampleClass, NestedClass>()
            {
                RelationshipName = "nestedValues",
                ResourceMapping  = nestedClassMapping,
                ResourceGetter   = c => c.NestedValue,
                ResourceIdGetter = c => c.NestedValueId
            };

            sampleClassMapping.Relationships.Add(linkMapping);

            conf.AddMapping(sampleClassMapping);
            conf.AddMapping(nestedClassMapping);

            return(new Context
            {
                Configuration = conf,
                RoutePrefix = appUrl
            });
        }
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            ResourceMapping             resourceMappings = new ResourceMapping();
            Dictionary <string, string> mappings         = value as Dictionary <string, string>;

            if (mappings != null)
            {
                if (mappings.ContainsKey("Caption"))
                {
                    resourceMappings.Caption = mappings["Caption"];
                }
                if (mappings.ContainsKey("Color"))
                {
                    resourceMappings.Color = mappings["Color"];
                }
                if (mappings.ContainsKey("Id"))
                {
                    resourceMappings.Id = mappings["Id"];
                }
                if (mappings.ContainsKey("Image"))
                {
                    resourceMappings.Image = mappings["Image"];
                }
            }
            return(resourceMappings);
        }
Пример #6
0
        private Context CreateOneToManyConfigurationContext()
        {
            var conf = new Configuration();
            var sampleClassMapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            sampleClassMapping.ResourceType = "sampleClasses";
            sampleClassMapping.AddPropertyGetter("someValue", c => c.SomeValue);

            var nestedClassMapping = new ResourceMapping <NestedClass>(c => c.Id, "http://nested/{id}");

            nestedClassMapping.ResourceType = "nestedClasses";
            nestedClassMapping.AddPropertyGetter("someNestedValue", c => c.SomeNestedValue);

            var linkMapping = new LinkMapping <SampleClass, NestedClass>()
            {
                RelatedBaseResourceType = "nestedClasses",
                RelationshipName        = "nestedValues",
                ResourceGetter          = c => c.NestedClasses,
                ResourceMapping         = nestedClassMapping,
                IsCollection            = true,
            };

            sampleClassMapping.Relationships.Add(linkMapping);

            conf.AddMapping(sampleClassMapping);
            conf.AddMapping(nestedClassMapping);

            return(new Context
            {
                Configuration = conf,
                RequestUri = new Uri("http://route")
            });
        }
Пример #7
0
        public void SetUp()
        {
            var someRelation = new RelationInfo(
                typeof(Resource).GetProperty(nameof(Resource.SomeRelation)),
                typeof(RelatedResource),
                RelationKind.BelongsTo);

            var manyRelation = new RelationInfo(
                typeof(Resource).GetProperty(nameof(Resource.ManyRelation)),
                typeof(RelatedResource),
                RelationKind.HasMany);

            _resource = new Resource();

            _mappingUnderTest = new ResourceMapping <Resource>(
                new Dictionary <string, PropertyInfo>
            {
                { "name", typeof(Resource).GetProperty(nameof(Resource.Name)) },
                { "age", typeof(Resource).GetProperty(nameof(Resource.Age)) },
            },
                new Dictionary <string, RelationInfo>
            {
                { "someRelation", someRelation },
                { "manyRelation", manyRelation }
            },
                new IdPropertyInfo("myid", typeof(Resource).GetProperty(nameof(Resource.MyId))));
        }
        private void Mutate_MapRead(Action <IntPtr> mappedDataReadAction, ResourceMapping readType)
        {
            lock (InstanceMutationLock) {
                if (IsDisposed)
                {
                    Logger.Warn("Attempted read manipulation on disposed resource of type: " + GetType().Name);
                    return;
                }
                IntPtr outDataPtr;
                uint   outUnused;
                InteropUtils.CallNative(
                    NativeMethods.ResourceFactory_MapSubresource,
                    RenderingModule.DeviceContext,
                    ResourceHandle,
                    0U,
                    readType,
                    (IntPtr)(&outDataPtr),
                    (IntPtr)(&outUnused),
                    (IntPtr)(&outUnused)
                    ).ThrowOnFailure();

                try {
                    mappedDataReadAction(outDataPtr);
                }
                finally {
                    InteropUtils.CallNative(
                        NativeMethods.ResourceFactory_UnmapSubresource,
                        RenderingModule.DeviceContext,
                        ResourceHandle,
                        0U
                        ).ThrowOnFailure();
                }
            }
        }
Пример #9
0
        //--- Constructors ---
        public CustomResource(string typeName, IDictionary <string, object> properties)
        {
            _originalTypeName = typeName ?? throw new ArgumentNullException(nameof(typeName));
            _properties       = new Dictionary <string, object>();

            // resolve custom resource service token
            if (
                !ResourceMapping.IsCloudFormationType(typeName) &&
                !typeName.StartsWith("Custom::", StringComparison.Ordinal)
                )
            {
                if (!_properties.ContainsKey("ServiceToken"))
                {
                    _properties["ServiceToken"] = FnImportValue(FnSub($"${{DeploymentPrefix}}{typeName}"));
                }
                if (!_properties.ContainsKey("ResourceType"))
                {
                    _properties["ResourceType"] = typeName;
                }
                _awsTypeName = "Custom::" + typeName.Replace("::", "");
            }
            else
            {
                _awsTypeName = typeName;
            }
            if (properties != null)
            {
                foreach (var kv in properties.Where(entry => entry.Value != null))
                {
                    _properties.Add(kv.Key, kv.Value);
                }
            }
        }
Пример #10
0
        private IConfiguration CreateConfiguration()
        {
            var mapping = new ResourceMapping <SampleClass, DummyController>(c => c.Id);

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);

            var nullableMapping = new ResourceMapping <SampleClassWithNullableProperty, DummyController>(c => c.Id);

            nullableMapping.ResourceType = "sampleClassesWithNullableProperty";
            nullableMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            nullableMapping.AddPropertyGetter("date", c => c.DateTime);

            var derivedMapping = new ResourceMapping <DerivedClass, DummyController>(c => c.Id);

            derivedMapping.ResourceType = "derivedClasses";
            derivedMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            derivedMapping.AddPropertyGetter("date", c => c.DateTime);
            derivedMapping.AddPropertyGetter("derivedProperty", c => c.DerivedProperty);

            var config = new NJsonApi.Configuration();

            config.AddMapping(mapping);
            config.AddMapping(nullableMapping);
            config.AddMapping(derivedMapping);
            return(config);
        }
Пример #11
0
        /// <summary>
        /// Renders the specified split intrinsic.
        /// </summary>
        /// <param name="splitIntrinsic">The split intrinsic.</param>
        /// <param name="template">The template.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="inputs">The list of input variables and data sources.</param>
        /// <returns>A <see cref="FunctionReference"/> to the <c>split()</c> built-in.</returns>
        private static Reference Render(
            SplitIntrinsic splitIntrinsic,
            ITemplate template,
            ResourceMapping resource,
            IList <InputVariable> inputs)
        {
            var splitArguments = new List <object> {
                splitIntrinsic.Delimiter
            };

            switch (splitIntrinsic.Source)
            {
            case IIntrinsic intrinsic:

                splitArguments.Add(Render(intrinsic, template, resource, inputs).ToJConstructor());
                break;

            default:

                splitArguments.Add(splitIntrinsic.Source.ToString());
                break;
            }

            return(new FunctionReference("split", splitArguments));
        }
Пример #12
0
        //public static int Refresh(int rmId)
        //{
        //    int count = 0;
        //    BrokerDB db = new BrokerDB();
        //    ResourceMapping rm = db.GetResourceMapping(rmId);
        //    if (list != null && list.Count > 0)
        //    {
        //        Add(list);
        //    }
        //    needsRefresh = false;
        //}
        public static void Add(ResourceMapping map)
        {
            if (mappingCache.ContainsKey(map.MappingID))
            {
                return;
            }
            else
            {
                mappingCache.Add(map.MappingID, map);
                if (mapKeyCache.ContainsKey(map.key))
                {
                    List<int> list = mapKeyCache[map.key];
                    if (list != null)
                    {
                        if(list.Contains(map.MappingID)){
                            throw new Exception("ResourceManager keyCache already contains mappinID " + map.MappingID);
                        }
                        else{
                            list.Add(map.MappingID);
                            mapKeyCache[map.key] = list;
                        }

                    }
                    else {
                        throw new Exception("ResourceManager keyCache key without list");
                    }
                }
                else
                {
                    List<int> newList = new List<int>();
                    newList.Add(map.MappingID);
                    mapKeyCache.Add(map.key,newList);
                }
            }
        }
Пример #13
0
 /// <summary>
 /// Renders the specified join intrinsic.
 /// </summary>
 /// <param name="joinIntrinsic">The join intrinsic.</param>
 /// <param name="template">The template.</param>
 /// <param name="resource">The resource.</param>
 /// <param name="inputs">The list of input variables and data sources.</param>
 /// <returns>A <see cref="FunctionReference"/> to an HCL join() expression.</returns>
 private static Reference Render(
     JoinIntrinsic joinIntrinsic,
     ITemplate template,
     ResourceMapping resource,
     IList <InputVariable> inputs)
 {
     return(new JoinFunctionReference(joinIntrinsic, template, inputs));
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IfIntrinsicInfo"/> class.
 /// </summary>
 /// <param name="propertyPath">The property path.</param>
 /// <param name="intrinsic">The intrinsic.</param>
 /// <param name="resourceMapping">Summary info of the resource targeted by this intrinsic.</param>
 /// <param name="evaluation">The evaluation.</param>
 public IfIntrinsicInfo(
     PropertyPath propertyPath,
     IIntrinsic intrinsic,
     ResourceMapping resourceMapping,
     object evaluation)
     : base(propertyPath, intrinsic, resourceMapping, evaluation)
 {
 }
Пример #15
0
 public static extern InteropBool ResourceFactory_MapSubresource(
     IntPtr failReason,
     DeviceContextHandle contextHandle,
     ResourceHandle resourceHandle,
     uint subresourceIndex,
     ResourceMapping mapType,
     IntPtr outResDataPtr,             // void**
     IntPtr outResDataRowLenBytes,     // uint*
     IntPtr outResDataSliceLenBytes    // uint*
     );
        /// <summary>
        /// Gets the AAS target (namespace/resource-id/dimension).
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <returns>The AAS target identifier.</returns>
        // ReSharper disable once InconsistentNaming
        protected string GetAASTarget(ResourceMapping resource)
        {
            // Manipulate the physical ID to get in the correct format
            var parts = resource.PhysicalId.Split('|');

            var resourceId = parts[0];
            var dimension  = parts[1];
            var @namespace = parts[2];

            return($"{@namespace}/{resourceId}/{dimension}");
        }
        public void ResourceConfiguration_Constructor_ShouldSetParameters()
        {
            var mapping = new ResourceMapping <ResourceA>(
                new Dictionary <string, PropertyInfo>(),
                new Dictionary <string, RelationInfo>(),
                new IdPropertyInfo("IdName", null));
            var info = new ResourceConfiguration <ResourceA>("SomeTypeName", mapping);

            Assert.That(info.ResourceType, Is.EqualTo(typeof(ResourceA)));
            Assert.That(info.TypeName, Is.EqualTo("SomeTypeName"));
            Assert.That(info.Mapping, Is.EqualTo(mapping));
        }
        private IConfiguration CreateConfiguration()
        {
            var mapping = new ResourceMapping <SampleClass, DummyController>(c => c.Id);

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);
            var config = new NJsonApi.Configuration();

            config.AddMapping(mapping);
            return(config);
        }
Пример #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IntrinsicInfo"/> class.
 /// </summary>
 /// <param name="propertyPath">The property path.</param>
 /// <param name="intrinsic">The intrinsic.</param>
 /// <param name="resourceMapping">Summary info of the resource targeted by this intrinsic.</param>
 /// <param name="evaluation">The evaluation.</param>
 public IntrinsicInfo(
     PropertyPath propertyPath,
     IIntrinsic intrinsic,
     ResourceMapping resourceMapping,
     object evaluation)
 {
     this.targetResource      = resourceMapping;
     this.intrinsic           = intrinsic;
     this.PropertyPath        = propertyPath.Clone();
     this.InitialEvaluation   = evaluation;
     this.intrinsic.ExtraData = this;
 }
Пример #20
0
        private Context CreateContext()
        {
            var conf    = new NJsonApi.Configuration();
            var mapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);
            conf.AddMapping(mapping);

            return(new Context(conf, new Uri("http://fakehost:1234/", UriKind.Absolute)));
        }
Пример #21
0
        /// <summary>
        /// Renders the object.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="template">The template.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="inputs">The list of input variables and data sources.</param>
        /// <returns>Object value which is a JConstructor if the input is an intrinsic, else the string value of the input.</returns>
        private static object RenderObject(
            object value,
            ITemplate template,
            ResourceMapping resource,
            IList <InputVariable> inputs)
        {
            if (value is IIntrinsic intrinsic)
            {
                return(Render(intrinsic, template, resource, inputs).ToJConstructor());
            }

            return(value.ToString());
        }
Пример #22
0
        /// <summary>
        /// Renders this intrinsic to a <see cref="Reference"/> that can be embedded into the in-memory state file.
        /// </summary>
        /// <param name="self">The intrinsic being rendered.</param>
        /// <param name="template">Reference to CloudFormation template.</param>
        /// <param name="resource">Resource referenced by the intrinsic.</param>
        /// <param name="inputs">The list of input variables and data sources.</param>
        /// <returns>A <see cref="Reference"/> or <c>null</c> if a reference cannot be created.</returns>
        /// <exception cref="System.ArgumentNullException">self cannot be null</exception>
        public static Reference Render(
            this IIntrinsic self,
            ITemplate template,
            ResourceMapping resource,
            IList <InputVariable> inputs)
        {
            if (self == null)
            {
                throw new ArgumentNullException(nameof(self));
            }

            return(self.Render(template, resource, inputs, -1));
        }
Пример #23
0
        /// <summary>
        /// Renders the specified select intrinsic.
        /// </summary>
        /// <param name="selectIntrinsic">The select intrinsic.</param>
        /// <param name="template">The template.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="inputs">The list of input variables and data sources.</param>
        /// <returns>A <see cref="Reference"/> derivative according to what is being selected, with selection indexer.</returns>
        private static Reference Render(
            SelectIntrinsic selectIntrinsic,
            ITemplate template,
            ResourceMapping resource,
            IList <InputVariable> inputs)
        {
            if (selectIntrinsic.Items.Count == 1 && selectIntrinsic.Items[0] is IIntrinsic intrinsic)
            {
                return(intrinsic.Render(template, resource, inputs, selectIntrinsic.Index));
            }

            return(null);
        }
Пример #24
0
        private Context CreateContext()
        {
            var conf    = new NJsonApi.Configuration();
            var mapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);
            conf.AddMapping(mapping);
            var requestUri = new Uri("http://fakeUri:1234/fakecontroller");

            return(new Context(conf, requestUri));
        }
Пример #25
0
        private IConfiguration CreateConfigurationForListType()
        {
            var mapping = new ResourceMapping <SampleListClass, DummyController>(c => c.Id);

            mapping.ResourceType = "sampleListClasses";
            mapping.AddPropertyGetter("simpleAttribute", c => c.SimpleAttribute);
            mapping.AddPropertyGetter("listAttribute", c => c.ListAttribute);

            var config = new NJsonApi.Configuration();

            config.AddMapping(mapping);
            return(config);
        }
        IResourceConfiguration IResourceConfigurationBuilder.Build()
        {
            Validate();

            var attributes = _properties
                             .Where(x => !_relations.ContainsKey(x.Key) && !_idPropertyName.Equals(x.Key, StringComparison.OrdinalIgnoreCase))
                             .ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);

            var idProperty = new IdPropertyInfo(_idPropertyName, _properties[_idPropertyName]);

            var mapping = new ResourceMapping <TResource>(attributes, _relations, idProperty);

            return(new ResourceConfiguration <TResource>(_typeName, mapping));
        }
Пример #27
0
        private Context CreateContext()
        {
            var conf = new Configuration();
            var sampleClassMapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            sampleClassMapping.ResourceType = "sampleClasses";
            sampleClassMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            sampleClassMapping.AddPropertyGetter("date", c => c.DateTime);


            var nestedClassMapping = new ResourceMapping <NestedClass>(c => c.Id, "http://nestedclass/{id}");

            nestedClassMapping.ResourceType = "nestedClasses";
            nestedClassMapping.AddPropertyGetter("nestedText", c => c.NestedText);


            var deeplyNestedMapping = new ResourceMapping <DeeplyNestedClass>(c => c.Id, "http://deep/{id}");

            deeplyNestedMapping.ResourceType = "deeplyNestedClasses";
            deeplyNestedMapping.AddPropertyGetter("value", c => c.Value);


            var linkMapping = new LinkMapping <SampleClass, NestedClass>()
            {
                IsCollection     = true,
                RelationshipName = "nestedValues",
                ResourceMapping  = nestedClassMapping,
                ResourceGetter   = c => c.NestedClass,
            };

            var deepLinkMapping = new LinkMapping <NestedClass, DeeplyNestedClass>()
            {
                RelationshipName = "deeplyNestedValues",
                ResourceMapping  = deeplyNestedMapping,
                ResourceGetter   = c => c.DeeplyNestedClass
            };

            sampleClassMapping.Relationships.Add(linkMapping);
            nestedClassMapping.Relationships.Add(deepLinkMapping);

            conf.AddMapping(sampleClassMapping);
            conf.AddMapping(nestedClassMapping);
            conf.AddMapping(deeplyNestedMapping);

            return(new Context
            {
                Configuration = conf,
                RoutePrefix = string.Empty
            });
        }
Пример #28
0
        /// <summary>
        /// Renders the specified sub intrinsic.
        /// </summary>
        /// <param name="subIntrinsic">The sub intrinsic.</param>
        /// <param name="template">The template.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="inputs">The list of input variables and data sources.</param>
        /// <returns>A <see cref="InterpolationReference"/> for the interpolated string to insert.</returns>
        private static Reference Render(
            SubIntrinsic subIntrinsic,
            ITemplate template,
            ResourceMapping resource,
            IList <InputVariable> inputs)
        {
            // Build up an interpolated string as the replacement
            // Start with the !Sub intrinsic expression.
            var expression = subIntrinsic.Expression;

            var replacements = new Dictionary <string, string>();

            // Go through any intrinsics associated with this !Sub
            foreach (var nestedIntrinsic in subIntrinsic.ImplicitReferences.Cast <IReferenceIntrinsic>())
            {
                // Try to render to an HCL expression
                var reference = Render(nestedIntrinsic, template, resource, inputs);

                if (reference == null)
                {
                    return(null);
                }

                replacements.Add(nestedIntrinsic.ReferencedObject(template), reference.ReferenceExpression);
            }

            foreach (var substitution in subIntrinsic.Substitutions)
            {
                string replacement;

                if (substitution.Value is IIntrinsic intrinsic)
                {
                    replacement = Render(intrinsic, template, resource, inputs).ReferenceExpression;
                }
                else
                {
                    replacement = substitution.Value.ToString();
                }

                replacements.Add(substitution.Key, replacement);
            }

            expression = replacements.Aggregate(
                expression,
                (current, replacement) => current.Replace($"${{{replacement.Key}}}", $"${{{replacement.Value}}}"));

            // Add interpolation modification.
            return(new InterpolationReference(expression));
        }
Пример #29
0
        private Context CreateContext()
        {
            var conf    = new Configuration();
            var mapping = new ResourceMapping <SampleClass>(c => c.Id, "http://sampleClass/{id}");

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);
            conf.AddMapping(mapping);

            return(new Context
            {
                Configuration = conf
            });
        }
Пример #30
0
        private IConfiguration CreateConfiguration()
        {
            var mapping = new ResourceMapping <SampleClass, DummyController>(c => c.Id);

            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);

            var mappingWithMeta = new ResourceMapping <SampleClassWithObjectMetadata, DummyController>(c => c.Id);

            mappingWithMeta.ResourceType = "sampleClassesWithMeta";
            mappingWithMeta.AddPropertyGetter("someValue", c => c.SomeValue);

            var mappingWithRelationshipMeta = new ResourceMapping <SampleClassWithRelationshipMetadata, DummyController>(c => c.Id);

            mappingWithRelationshipMeta.ResourceType = "sampleClassWithRelationshipMetadata";
            mappingWithRelationshipMeta.AddPropertyGetter("someValue", c => c.SomeValue);

            var mappingWithRelatedClassesWithRelationshipMeta = new ResourceMapping <SampleClassWithRelatedClassesWithRelationshipMetadata, DummyController>(c => c.Id);

            mappingWithRelatedClassesWithRelationshipMeta.ResourceType = "sampleClassWithRelatedClassesWithRelationshipMetadata";

            var relMapSingle = new RelationshipMapping <SampleClassWithRelatedClassesWithRelationshipMetadata, SampleClassWithRelationshipMetadata>();

            relMapSingle.RelationshipName = "relatedObject";
            relMapSingle.IsCollection     = false;
            relMapSingle.RelatedProperty  = new PropertyHandle <SampleClassWithRelatedClassesWithRelationshipMetadata, SampleClassWithRelationshipMetadata>(o => o.RelatedObject);
            relMapSingle.ResourceGetter   = o => o.RelatedObject;
            relMapSingle.ResourceMapping  = mappingWithRelationshipMeta;
            mappingWithRelatedClassesWithRelationshipMeta.Relationships.Add(relMapSingle);

            var relMapCollection = new RelationshipMapping <SampleClassWithRelatedClassesWithRelationshipMetadata, IList <SampleClassWithRelationshipMetadata> >();

            relMapCollection.RelationshipName = "relatedObjects";
            relMapCollection.IsCollection     = true;
            relMapCollection.RelatedProperty  = new PropertyHandle <SampleClassWithRelatedClassesWithRelationshipMetadata, IList <SampleClassWithRelationshipMetadata> >(o => o.RelatedObjects);
            relMapCollection.ResourceGetter   = o => o.RelatedObjects;
            relMapCollection.ResourceMapping  = mappingWithRelationshipMeta;
            mappingWithRelatedClassesWithRelationshipMeta.Relationships.Add(relMapCollection);

            var config = new NJsonApi.Configuration();

            config.AddMapping(mapping);
            config.AddMapping(mappingWithMeta);
            config.AddMapping(mappingWithRelationshipMeta);
            config.AddMapping(mappingWithRelatedClassesWithRelationshipMeta);
            return(config);
        }
Пример #31
0
        /// <summary>
        /// Renders the specified reference intrinsic.
        /// </summary>
        /// <param name="refIntrinsic">The reference intrinsic.</param>
        /// <param name="template">The template.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="index">The index.</param>
        /// <returns>A <see cref="Reference"/> derivative according to what is being referenced.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// Pseudo parameter \"{pseudo}\" cannot be referenced by terraform.
        /// or
        /// Reference \"{refIntrinsic.Reference}\" cannot be resolved.
        /// </exception>
        private static Reference Render(
            RefIntrinsic refIntrinsic,
            ITemplate template,
            ResourceMapping resource,
            int index)
        {
            switch (refIntrinsic.Reference)
            {
            case string pseudo when pseudo.StartsWith("AWS::"):

                if (PseudoParameterToDataBlock.ContainsKey(pseudo))
                {
                    return(PseudoParameterToDataBlock[pseudo]);
                }

                throw new InvalidOperationException(
                          $"Pseudo parameter \"{pseudo}\" cannot be referenced by terraform.");

            default:

                var param = template.Parameters.FirstOrDefault(p => p.Name == refIntrinsic.Reference);

                if (param != null)
                {
                    if (param.IsSsmParameter)
                    {
                        return(new DataSourceReference("aws_ssm_parameter", refIntrinsic.Reference, "value", true));
                    }

                    return(index < 0
                                   ? new InputVariableReference(refIntrinsic.Reference)
                                   : new InputVariableReference(refIntrinsic.Reference, index));
                }

                if (refIntrinsic.ExtraData is IntrinsicInfo intrinsicInfo)
                {
                    resource = intrinsicInfo.TargetResource;
                }

                if (resource != null && template.Resources.Any(r => r.Name == resource.LogicalId))
                {
                    return(new DirectReference(resource.Address));
                }

                throw new InvalidOperationException($"Reference \"{refIntrinsic.Reference}\" cannot be resolved.");
            }
        }
Пример #32
0
            /// <summary>
            /// Creates an <see cref="IntrinsicInfo"/> for a Ref intrinsic.
            /// </summary>
            /// <param name="refIntrinsic">The reference intrinsic.</param>
            /// <param name="currentPath">The current path.</param>
            /// <returns>An <see cref="IntrinsicInfo"/></returns>
            private IntrinsicInfo ProcessRef(RefIntrinsic refIntrinsic, PropertyPath currentPath)
            {
                object evaluation;
                var    target = refIntrinsic.Reference;

                var param = this.Inputs.FirstOrDefault(i => i.Name == target);

                if (param != null)
                {
                    evaluation = param.IsScalar ? (object)param.ScalarIdentity : param.ListIdentity;
                    return(new IntrinsicInfo(currentPath.Clone(), refIntrinsic, null, evaluation));
                }

                if (target.StartsWith("AWS::"))
                {
                    // An unsupported AWS pseudo parameter like AWS::StackName etc.
                    throw new UnsupportedPseudoParameterWarning(
                              refIntrinsic,
                              this.currentCloudFormationResource,
                              currentPath);
                }

                var cloudFormationResource = this.CloudFormationResources
                                             .Where(r => TerraformExporterConstants.IgnoredResources.All(ir => ir != r.ResourceType))
                                             .FirstOrDefault(r => r.LogicalResourceId == target);

                if (cloudFormationResource == null)
                {
                    // If not found, then reference is to a resource that couldn't be imported eg. a custom resource
                    // or a known unsupported type.
                    throw new UnsupportedResourceWarning(refIntrinsic, this.currentCloudFormationResource, currentPath);
                }

                var targetResourceSummary = new ResourceMapping
                {
                    AwsType       = cloudFormationResource.ResourceType,
                    LogicalId     = cloudFormationResource.LogicalResourceId,
                    PhysicalId    = cloudFormationResource.PhysicalResourceId,
                    TerraformType = this.TerraformResources.First(
                        tr => tr.Name == cloudFormationResource.LogicalResourceId).Type
                };

                evaluation = cloudFormationResource.PhysicalResourceId;

                return(new IntrinsicInfo(currentPath, refIntrinsic, targetResourceSummary, evaluation));
            }
        private Context CreateContext()
        {
            var conf = new Configuration();
            var sampleClassMapping = new ResourceMapping<SampleClass>(c => c.Id, "http://sampleClass/{id}");
            sampleClassMapping.ResourceType = "sampleClasses";
            sampleClassMapping.AddPropertyGetter("someValue", c => c.SomeValue);
            sampleClassMapping.AddPropertyGetter("date", c => c.DateTime);

            var nestedClassMapping = new ResourceMapping<NestedClass>(c => c.Id, "http://nestedclass/{id}");
            nestedClassMapping.ResourceType = "nestedClasses";
            nestedClassMapping.AddPropertyGetter("nestedText", c => c.NestedText);

            var deeplyNestedMapping = new ResourceMapping<DeeplyNestedClass>(c => c.Id, "http://deep/{id}");
            deeplyNestedMapping.ResourceType = "deeplyNestedClasses";
            deeplyNestedMapping.AddPropertyGetter("value", c => c.Value);

            var linkMapping = new LinkMapping<SampleClass, NestedClass>()
            {
                IsCollection = true,
                RelationshipName = "nestedValues",
                ResourceMapping = nestedClassMapping,
                ResourceGetter = c => c.NestedClass,
            };

            var deepLinkMapping = new LinkMapping<NestedClass, DeeplyNestedClass>()
            {
                RelationshipName = "deeplyNestedValues",
                ResourceMapping = deeplyNestedMapping,
                ResourceGetter = c => c.DeeplyNestedClass
            };

            sampleClassMapping.Relationships.Add(linkMapping);
            nestedClassMapping.Relationships.Add(deepLinkMapping);

            conf.AddMapping(sampleClassMapping);
            conf.AddMapping(nestedClassMapping);
            conf.AddMapping(deeplyNestedMapping);

            return new Context
            {
                Configuration = conf,
                RoutePrefix = string.Empty
            };
        }
Пример #34
0
        public void Creates_configuration_mapping()
        {
            // Arrange
            var sampleMapping = new ResourceMapping<Post, PostsController>(c => c.Id, "sample_{id}")
            {
                ResourceType = "posts"
            };

            sampleMapping.AddPropertyGetter("value", c => c.Title);

            var conf = new NJsonApi.Configuration();

            // Act
            conf.AddMapping(sampleMapping);

            // Assert
            Assert.True(conf.IsMappingRegistered(typeof(Post)));
            Assert.NotNull(conf.GetMapping(typeof(Post)));
            Assert.False(conf.IsMappingRegistered(typeof(Author)));
            Assert.Null(conf.GetMapping(typeof(Author)));
        }
Пример #35
0
        public void Creates_configuration_mapping()
        {
            // Arrange
            var sampleMapping = new ResourceMapping<SampleClass>(c => c.Id, "sample_{id}")
            {
                ResourceType = "sampleClasses"
            };

            sampleMapping.AddPropertyGetter("value", c => c.Value);

            var conf = new Configuration();

            // Act
            conf.AddMapping(sampleMapping);

            // Assert
            conf.IsMappingRegistered(typeof(SampleClass)).ShouldBeTrue();
            conf.GetMapping(typeof(SampleClass)).ShouldNotBeNull();
            conf.IsMappingRegistered(typeof(NestedClass)).ShouldBeFalse();
            conf.GetMapping(typeof(NestedClass)).ShouldBeNull();
        }
        private void repRsrcMappings_ItemBound(Object sender, RepeaterItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                // get the current mapping
                Object o = e.Item.DataItem;
                curMapping = (ResourceMapping)o;
                Button curBtn = (Button)e.Item.FindControl("btnRemove");
                //curBtn.Attributes.Add("onClick", btnRemove_Click);
                curBtn.CommandArgument = curMapping.MappingID.ToString();
                // set key label
                Label lbl = (Label)e.Item.FindControl("keyLabel");
                lbl.Text = brokerDB.GetMappingEntryString(curMapping.Key,false);

                ////////
                ArrayList mappingValuesList = new ArrayList(curMapping.values.Length);
                for (int i = 0; i < curMapping.values.Length; i++)
                    mappingValuesList.Add(curMapping.values[i]);

                Repeater repeater = (Repeater)e.Item.FindControl("repValues2");
                repeater.ItemCreated += new RepeaterItemEventHandler(this.repValues2_ItemCreated);
                repeater.ItemDataBound += new RepeaterItemEventHandler(this.repValues2_ItemBound);
                repeater.ItemCommand += new RepeaterCommandEventHandler(this.repValues2_ItemCommand);
                repeater.DataSource = mappingValuesList;
                repeater.DataBind();
            }
        }
Пример #37
0
 /// <summary>
 /// Deletes the resourceMapping and any qualifiers and grants related to the mapping
 /// </summary>
 /// <param name="mapping">Resource Mapping to be deleted</param>
 /// <returns><code>true</code> if the mapping has been deleted successfully</returns>
 public bool DeleteResourceMapping(ResourceMapping mapping)
 {
     return DeleteResourceMapping(mapping.MappingID);
 }
Пример #38
0
        protected ResourceMapping InsertResourceMapping(DbConnection connection, string keyType, object key, string[] valueTypes, object[] values)
        {
            if (valueTypes == null || values == null)
                throw new ArgumentException("Arguments cannot be null", "valueTypes and values");

            if (valueTypes.Length != values.Length)
                throw new ArgumentException("Parameter Arrays \"valueTypes\" and \"values\" should be of the same length");

            ResourceMappingKey mappingKey = new ResourceMappingKey(keyType, key);
            // insert key into database

            try
            {
                connection.Open();
                DbCommand cmd = FactoryDB.CreateCommand("ResourceMapKey_Insert", connection);
                cmd.CommandType = CommandType.StoredProcedure;

                // Get the key type id
                int keyTypeID = ResourceMappingTypes.GetResourceMappingTypeID(keyType);
                if (keyTypeID == -1)
                    throw new ArgumentException("Value for key type is invalid");

                int keyID = -1;

                // if the key is a string, add the string to the strings table
                if (keyType.Equals(ResourceMappingTypes.STRING))
                {
                    DbCommand cmd2 = FactoryDB.CreateCommand("ResourceMapString_Insert", connection);
                    cmd2.CommandType = CommandType.StoredProcedure;

                    // populate parameters
                    cmd2.Parameters.Add(FactoryDB.CreateParameter("@string_Value", key, DbType.String, 2048));

                    keyID = Convert.ToInt32(cmd2.ExecuteScalar());
                }

                // if the key is a Resource Type, add the string to the ResourceTypes table
                else if (keyType.Equals(ResourceMappingTypes.RESOURCE_TYPE))
                {
                    DbCommand cmd2 = FactoryDB.CreateCommand("ResourceMapResourceType_Insert", connection);
                    cmd2.CommandType = CommandType.StoredProcedure;

                    cmd2.Parameters.Add(FactoryDB.CreateParameter("@resourceType_Value", key, DbType.String, 256));

                    keyID = Convert.ToInt32(cmd2.ExecuteScalar());
                }

                else
                    keyID = ResourceMappingEntry.GetId(key);

                if (keyID == -1)
                    throw new ArgumentException("Value for key is invalid");

                // populate stored procedure parameters
                cmd.Parameters.Add(FactoryDB.CreateParameter( "@MappingKey_Type", keyTypeID, DbType.Int32));
                cmd.Parameters.Add(FactoryDB.CreateParameter( "@MappingKey", keyID, DbType.Int32));

                // execute the command
                int mappingID = Convert.ToInt32(cmd.ExecuteScalar());

                //
                // insert mapping values
                //
                ResourceMappingValue[] mappingValues = new ResourceMappingValue[values.Length];
                for (int i = 0; i < mappingValues.Length; i++)
                {
                    mappingValues[i] = new ResourceMappingValue(valueTypes[i], values[i]);

                    // Get the value type id
                    int valueTypeID = ResourceMappingTypes.GetResourceMappingTypeID(valueTypes[i]);
                    if (valueTypeID == -1)
                        throw new ArgumentException("Value for value type \"" + i + "\" is invalid");

                    int valueID = -1;

                    // if the value is a string, add the string to the strings table
                    if (valueTypes[i].Equals(ResourceMappingTypes.STRING))
                    {
                        DbCommand cmd2 = FactoryDB.CreateCommand("ResourceMapString_Insert", connection);
                        cmd2.CommandType = CommandType.StoredProcedure;

                        // populate parameters
                        cmd2.Parameters.Add(FactoryDB.CreateParameter("@string_Value", (string)values[i], DbType.String, 2048));

                        valueID = Convert.ToInt32(cmd2.ExecuteScalar());
                    }

                    // if the key is a Resource Type, add the string to the ResourceTypes table
                    else if (valueTypes[i].Equals(ResourceMappingTypes.RESOURCE_TYPE))
                    {
                        DbCommand cmd2 = FactoryDB.CreateCommand("ResourceMapResourceType_Insert", connection);
                        cmd2.CommandType = CommandType.StoredProcedure;

                        cmd2.Parameters.Add(FactoryDB.CreateParameter("@resourceType_Value", (string)values[i], DbType.String, 256));
                        valueID = Convert.ToInt32(cmd2.ExecuteScalar());
                    }

                    else
                        valueID = ResourceMappingEntry.GetId(values[i]);

                    if (valueID == -1)
                        throw new ArgumentException("Value \"" + i + "\" is invalid");

                    cmd = FactoryDB.CreateCommand("ResourceMapValue_Insert", connection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    //cmd.Parameters.Clear();

                    // populate stored procedure parameters
                    cmd.Parameters.Add(FactoryDB.CreateParameter( "@Mapping_ID", mappingID, DbType.Int32));
                    cmd.Parameters.Add(FactoryDB.CreateParameter( "@MappingValue_Type", valueTypeID, DbType.Int32));
                    cmd.Parameters.Add(FactoryDB.CreateParameter( "@MappingValue", valueID, DbType.Int32));

                    // execute the command
                    int mapValueID = Convert.ToInt32(cmd.ExecuteScalar());
                }

                // create new mapping object
                ResourceMapping mapping = new ResourceMapping(mappingID, mappingKey, mappingValues);

                return mapping;
            }

            catch (DbException e)
            {
                writeEx(e);
                throw;
            }

            finally
            {
                connection.Close();
            }
        }
Пример #39
0
        // THis is not supported, an attempt to re-do resources using int's instead of strings
        //public int InsertResourceMap(int keyType, int keyValue,
        //    int type0, object value0, int type1, object value1, int type2, object value2)
        //{
        //    int id = -1;
        //    DbConnection connection  = CreateConnection();
        //      // command executes the "InsertResourceMap" stored procedure
        //        DbCommand cmd = FactoryDB.CreateCommand("InsertResourceMap", connection);
        //        cmd.CommandType = CommandType.StoredProcedure;
        //        DbParameter paramType = null;
        //        DbParameter paramValue = null;
        //        // Need to do this in pairs
        //        paramType = cmd.Parameters.Add(FactoryDB.CreateParameter("@keyType", DbType.Int);
        //        paramValue = cmd.Parameters.Add(FactoryDB.CreateParameter("@keyValue", DbType.Int);
        //        paramType.Value = keyType;
        //        paramValue.Value = keyValue;
        //        paramType = cmd.Parameters.Add(FactoryDB.CreateParameter("@Type0", DbType.Int);
        //        paramValue = cmd.Parameters.Add(FactoryDB.CreateParameter("@value0", DbType.Int);
        //        paramType.Value = type0;
        //        paramValue.Value = value0;
        //    paramType = cmd.Parameters.Add(FactoryDB.CreateParameter("@type1", DbType.Int);
        //    paramValue = cmd.Parameters.Add(FactoryDB.CreateParameter("@value1", DbType.Int);
        //    if(ResourceMap.IsResourceMapType(type1)){
        //        paramType.Value = type1;
        //        paramValue.Value = value1;
        //    }
        //    else{
        //        paramType.Value = DBNull.Value;
        //        paramValue.Value =  DBNull.Value;
        //    }
        //    paramType = cmd.Parameters.Add(FactoryDB.CreateParameter("@type2", DbType.Int);
        //    paramValue = cmd.Parameters.Add(FactoryDB.CreateParameter("@value2", DbType.Int);
        //   if(ResourceMap.IsResourceMapType(type2)){
        //        paramType.Value = type2;
        //        paramValue.Value = value2;
        //    }
        //    else{
        //        paramType.Value = DBNull.Value;
        //        paramValue.Value =  DBNull.Value;
        //    }
        //    try
        //    {
        //        // execute the command
        //        id = Convert.ToInt32(cmd.ExecuteScalar());
        //    }
        //    catch (DbException e)
        //    {
        //        writeEx(e);
        //        throw;
        //    }
        //    finally
        //    {
        //        connection.Close();
        //    }
        //    return id;
        //}
        public string ResourceMappingToString(ResourceMapping mapping)
        {
            StringBuilder s = new StringBuilder();
            //s.Append(mapping.MappingID + " ");
            s.Append(GetMappingEntryString(mapping.key, true) + "-> ");

            //if (mapping.values.Length > 1)
            //    s.Append("(");

            // print all values except last
            for (int i = 0; i < mapping.values.Length; i++)
            {
                if (i > 0 && i < mapping.values.Length)
                    s.Append(", ");
                s.Append(GetMappingEntryString(mapping.values[i], true));

            }

            //// print last value
            //if (mapping.values[mapping.values.Length - 1].Type.Equals(ResourceMappingTypes.RESOURCE_MAPPING))
            //    s.Append("(" + mapping.values[mapping.values.Length - 1] + ":" + mapping.values[mapping.values.Length - 1].Entry + ")");
            //else
            //    s.Append("(" + mapping.values[mapping.values.Length - 1].TypeName + ":" + GetMappingEntryString(mapping.values[mapping.values.Length - 1]) + ")");

            //if (mapping.values.Length > 1)
            //    s.Append(")");
            return s.ToString();
        }
Пример #40
0
        private Context CreateContext()
        {
            var conf = new Configuration();
            var mapping = new ResourceMapping<SampleClass>(c => c.Id, "http://sampleClass/{id}");
            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);
            conf.AddMapping(mapping);

            return new Context
            {
                Configuration = conf,
                RoutePrefix = string.Empty
            };
        }
Пример #41
0
        private IConfiguration CreateConfiguration()
        {
            var mapping = new ResourceMapping<SampleClass, DummyController>(c => c.Id, "http://sampleClass/{id}");
            mapping.ResourceType = "sampleClasses";
            mapping.AddPropertyGetter("someValue", c => c.SomeValue);
            mapping.AddPropertyGetter("date", c => c.DateTime);

            var config = new NJsonApi.Configuration();
            config.AddMapping(mapping);
            return config;
        }
Пример #42
0
 public static bool Update(ResourceMapping rm)
 {
     bool status = false;
     if(mappingCache.ContainsKey(rm.MappingID)){
         mappingCache.Remove(rm.MappingID);
         mappingCache.Add(rm.MappingID,rm);
         status = true;
     }
     else{
         throw new Exception("Update ResourceMapping rm not in cache");
     }
     return status;
 }