コード例 #1
0
        public async Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            var crds = GenerateCrds(_resourceLocator).ToList();

            var fileWriter = new FileWriter(app.Out);

            foreach (var crd in crds)
            {
                var output = UseOldCrds
                    ? _serializer.Serialize((V1beta1CustomResourceDefinition)crd, Format)
                    : _serializer.Serialize(crd, Format);

                fileWriter.Add($"{crd.Metadata.Name.Replace('.', '_')}.{Format.ToString().ToLower()}", output);
            }

            fileWriter.Add(
                $"kustomization.{Format.ToString().ToLower()}",
                _serializer.Serialize(
                    new KustomizationConfig
            {
                Resources = crds
                            .Select(crd => $"{crd.Metadata.Name.Replace('.', '_')}.{Format.ToString().ToLower()}")
                            .ToList(),
                CommonLabels = new Dictionary <string, string>
                {
                    { "operator-element", "crd" },
                },
            },
                    Format));

            await fileWriter.OutputAsync(OutputPath);

            return(ExitCodes.Success);
        }
コード例 #2
0
        public virtual async Task <string> ReadAllIds(string entityTypeName)
        {
            var type = TryToGetConfiguredTypeFrom(entityTypeName);
            var getAllIdsProvider = TryToGetReadAllIdsProviderForType(type);
            var allEntitiesIds    = await getAllIdsProvider.ReadAllIds();

            return(entitySerializer.Serialize(allEntitiesIds, allEntitiesIds.GetType()));
        }
コード例 #3
0
        public async Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            var ns = _serializer.Serialize(new V1Namespace(
                                               V1Namespace.KubeApiVersion,
                                               V1Namespace.KubeKind,
                                               new V1ObjectMeta(name: "system")), Format);
            var kustomize = _serializer.Serialize(new KustomizationConfig
            {
                NamePrefix   = $"{_settings.Name}-",
                Namespace    = $"{_settings.Name}-system",
                CommonLabels = new Dictionary <string, string>
                {
                    { "operator", _settings.Name },
                },
                Resources = new List <string>
                {
                    $"./namespace.{Format.ToString().ToLower()}",
                    CrdsPath == null || OutputPath == null
                        ? "../crds"
                        : Path.GetRelativePath(OutputPath, CrdsPath).Replace('\\', '/'),
                    RbacPath == null || OutputPath == null
                        ? "../rbac"
                        : Path.GetRelativePath(OutputPath, RbacPath).Replace('\\', '/'),
                    OperatorPath == null || OutputPath == null
                        ? "../operator"
                        : Path.GetRelativePath(OutputPath, OperatorPath).Replace('\\', '/'),
                },
                Images = new List <KustomizationImage>
                {
                    new KustomizationImage
                    {
                        Name    = "operator",
                        NewName = "public-docker-image-path",
                        NewTag  = "latest",
                    },
                },
            }, Format);

            if (!string.IsNullOrWhiteSpace(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);
                await using var nsFile = File.Open(Path.Join(OutputPath,
                                                             $"namespace.{Format.ToString().ToLower()}"), FileMode.Create);
                await nsFile.WriteAsync(Encoding.UTF8.GetBytes(ns));

                await using var kustomizeFile = File.Open(Path.Join(OutputPath,
                                                                    $"kustomization.{Format.ToString().ToLower()}"), FileMode.Create);
                await kustomizeFile.WriteAsync(Encoding.UTF8.GetBytes(kustomize));
            }
            else
            {
                await app.Out.WriteLineAsync(ns);

                await app.Out.WriteLineAsync(kustomize);
            }

            return(ExitCodes.Success);
        }
コード例 #4
0
        public async Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            var role        = _serializer.Serialize(GenerateManagerRbac(), Format);
            var roleBinding = _serializer.Serialize(new V1ClusterRoleBinding
            {
                ApiVersion = $"{V1ClusterRoleBinding.KubeGroup}/{V1ClusterRoleBinding.KubeApiVersion}",
                Kind       = V1ClusterRoleBinding.KubeKind,
                Metadata   = new V1ObjectMeta {
                    Name = "operator-role-binding"
                },
                RoleRef  = new V1RoleRef(V1ClusterRole.KubeGroup, V1ClusterRole.KubeKind, "operator-role"),
                Subjects = new List <V1Subject>
                {
                    new V1Subject(V1ServiceAccount.KubeKind, "default", namespaceProperty: "system")
                }
            }, Format);

            if (!string.IsNullOrWhiteSpace(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);
                await using var roleFile = File.Open(Path.Join(OutputPath,
                                                               $"operator-role.{Format.ToString().ToLower()}"), FileMode.Create);
                await roleFile.WriteAsync(Encoding.UTF8.GetBytes(role));

                await using var bindingFile = File.Open(Path.Join(OutputPath,
                                                                  $"operator-role-binding.{Format.ToString().ToLower()}"), FileMode.Create);
                await bindingFile.WriteAsync(Encoding.UTF8.GetBytes(roleBinding));

                var kustomize = new KustomizationConfig
                {
                    Resources = new List <string>
                    {
                        $"operator-role.{Format.ToString().ToLower()}",
                        $"operator-role-binding.{Format.ToString().ToLower()}",
                    },
                    CommonLabels = new Dictionary <string, string>
                    {
                        { "operator-element", "rbac" },
                    },
                };
                var kustomizeOutput = Encoding.UTF8.GetBytes(_serializer.Serialize(kustomize, Format));
                await using var kustomizationFile =
                                File.Open(Path.Join(OutputPath, $"kustomization.{Format.ToString().ToLower()}"), FileMode.Create);
                await kustomizationFile.WriteAsync(kustomizeOutput);
            }
            else
            {
                await app.Out.WriteLineAsync(role);

                await app.Out.WriteLineAsync(roleBinding);
            }

            return(ExitCodes.Success);
        }
コード例 #5
0
        public async Task <int> OnExecuteAsync(CommandLineApplication app)
        {
            var crds = GenerateCrds().ToList();

            if (!string.IsNullOrWhiteSpace(OutputPath))
            {
                Directory.CreateDirectory(OutputPath);

                var kustomizeOutput = Encoding.UTF8.GetBytes(
                    _serializer.Serialize(
                        new KustomizationConfig
                {
                    Resources = crds
                                .Select(crd => $"{crd.Metadata.Name.Replace('.', '_')}.{Format.ToString().ToLower()}")
                                .ToList(),
                    CommonLabels = new Dictionary <string, string>
                    {
                        { "operator-element", "crd" },
                    },
                },
                        Format));
                await using var kustomizationFile =
                                File.Open(Path.Join(OutputPath, $"kustomization.{Format.ToString().ToLower()}"), FileMode.Create);
                await kustomizationFile.WriteAsync(kustomizeOutput);
            }

            foreach (var crd in crds)
            {
                var output = UseOldCrds
                    ? _serializer.Serialize((V1beta1CustomResourceDefinition)crd, Format)
                    : _serializer.Serialize(crd, Format);

                if (!string.IsNullOrWhiteSpace(OutputPath))
                {
                    await using var file = File.Open(
                                    Path.Join(
                                        OutputPath,
                                        $"{crd.Metadata.Name.Replace('.', '_')}.{Format.ToString().ToLower()}"),
                                    FileMode.Create);
                    await file.WriteAsync(Encoding.UTF8.GetBytes(output));
                }
                else
                {
                    await app.Out.WriteLineAsync(output);
                }
            }

            return(ExitCodes.Success);
        }
        public void FormattedValueCollectionInObjectCanBeSerializedAndDeserialized()
        {
            FormattedValueCollectionContainer formattedValueCollectionContainer = new FormattedValueCollectionContainer();
            FormattedValueCollection          formattedValueCollection          = new FormattedValueCollection();

            formattedValueCollectionContainer.FormattedValueCollection = formattedValueCollection;
            formattedValueCollection.Add("Test", "test");
            JsonSerializer serializer   = new EntitySerializer();
            MemoryStream   memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), formattedValueCollectionContainer);
            }

            FormattedValueCollectionContainer deserializedFormattedValueCollectionContainer;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedFormattedValueCollectionContainer = (FormattedValueCollectionContainer)serializer.Deserialize(new JsonTextReader(reader));
            }
            FormattedValueCollection deserializedFormattedValueCollection = (FormattedValueCollection)deserializedFormattedValueCollectionContainer.FormattedValueCollection;


            Assert.Equal(formattedValueCollectionContainer.GetType(), deserializedFormattedValueCollectionContainer.GetType());
            Assert.Equal(formattedValueCollection.Count, deserializedFormattedValueCollection.Count);
            Assert.Equal(formattedValueCollection.Keys.First(), deserializedFormattedValueCollection.Keys.First());
            Assert.Equal(formattedValueCollection.Values.First(), deserializedFormattedValueCollection.Values.First());
        }
コード例 #7
0
 public Task Export(Stream xmlData)
 {
     return(Task.Run(() =>
     {
         EntitySerializer.Serialize(xmlData, _db.Notes.GetAll().ToArray());
     }));
 }
コード例 #8
0
 public Task Export(Stream xmlData)
 {
     return(Task.Run(() =>
     {
         EntitySerializer.Serialize(xmlData, Programs.ToArray());
     }));
 }
コード例 #9
0
        public override string Serialize(object obj, Dictionary <int, object> moduleDictionary)
        {
            string output = "[\n";


            ICollection collection = obj as ICollection;

            int i = 0;

            foreach (var item in collection)
            {
                EntitySerializer serializer = serializers.Single(s => s.CanSerialize(item));

                output += serializer.Serialize(item, moduleDictionary);

                if (i < collection.Count - 1)
                {
                    output += "\n";
                }

                i++;
            }

            return(output + "\n]");
        }
コード例 #10
0
    public void Can_serialize_object_to_JSON_LD()
    {
        // given
        var person = new Person
        {
            Id       = new Uri("http://t-code.pl/#tomasz"),
            Name     = "Tomasz",
            LastName = "Pluskiewicz"
        };
        var @context = JObject.Parse("{ '@context': 'http://example.org/context/Person' }");

        var contextProvider = new StaticContextProvider();

        contextProvider.SetContext(typeof(Person), @context);

        // when
        IEntitySerializer serializer = new EntitySerializer(contextProvider);
        dynamic           json       = serializer.Serialize(person);

        // then
        Assert.That((string)json.name, Is.EqualTo("Tomasz"));
        Assert.That((string)json.lastName, Is.EqualTo("Pluskiewicz"));
        Assert.That((string)json["@id"], Is.EqualTo("http://t-code.pl/#tomasz"));
        Assert.That((string)json["@type"][0], Is.EqualTo("http://xmlns.com/foaf/0.1/Person"));
        Assert.That(json["@context"], Is.Not.Null);
    }
コード例 #11
0
        public void EntitySerializerConvertersCanBeEmpty()
        {
            Entity entity = new Entity("entity");

            entity.Id = Guid.NewGuid();
            List <JsonConverter> converters = new List <JsonConverter>();
            JsonSerializer       serializer = new EntitySerializer(converters);

            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), entity);
            }

            Entity deserializedEntity;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedEntity = (Entity)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(entity.LogicalName, deserializedEntity.LogicalName);
        }
コード例 #12
0
        private static void SaveEntity <TEntity>() where TEntity : Employee
        {
            var entities   = Employees.Where(e => e is TEntity).Cast <TEntity>().ToList();
            var serializer = new EntitySerializer <TEntity>(DataStoreOption);

            serializer.Serialize(entities);
        }
コード例 #13
0
 public async Task CreateAsync(SimilaritiesReport similarity)
 {
     foreach (var collection in similarity.Collections)
     {
         var dto  = collection.Properties.Select(x => new ContextCollectionPropertyDbEntity(x)).ToArray();
         var json = EntitySerializer.Serialize(dto);
         if (collection.Id == 0)
         {
             using (var cmd = _uow.CreateDbCommand())
             {
                 cmd.CommandText =
                     @"INSERT INTO IncidentContextCollections (IncidentId, Name, Properties) 
               VALUES(@incidentId, @name, @props)";
                 cmd.AddParameter("incidentId", collection.IncidentId);
                 cmd.AddParameter("name", collection.Name);
                 cmd.AddParameter("props", json);
                 await cmd.ExecuteNonQueryAsync();
             }
         }
         else
         {
             using (var cmd = _uow.CreateDbCommand())
             {
                 cmd.CommandText =
                     @"UPDATE IncidentContextCollections SET Properties=@props WHERE Id = @id";
                 cmd.AddParameter("id", collection.Id);
                 cmd.AddParameter("props", json);
                 await cmd.ExecuteNonQueryAsync();
             }
         }
     }
 }
        public void OptionSetAndOtherValuesCanBeSerializedAndDeserialized()
        {
            Entity entity = new Entity("Test");

            entity["optionsetvalue"] = new OptionSetValue(9);
            entity["decimal"]        = 10m;
            entity["number"]         = 2384;
#if !XRM_8 && !XRM_7 && !XRM_6 && !XRM_5
            OptionSetValueCollection optionSetValue = new OptionSetValueCollection();
            optionSetValue.Add(new OptionSetValue(10));
            optionSetValue.Add(new OptionSetValue(20));
            entity["multioptionset"] = optionSetValue;
#endif

            JsonSerializer serializer   = new EntitySerializer();
            MemoryStream   memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), entity);
            }

            Entity deserializedEntity;
            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedEntity = (Entity)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(entity.Attributes.Count, deserializedEntity.Attributes.Count);
        }
コード例 #15
0
 public async Task UpdateAsync(Incident incident)
 {
     using (var cmd = (DbCommand)_uow.CreateCommand())
     {
         cmd.CommandText =
             @"UPDATE Incidents SET 
                 ApplicationId = @ApplicationId,
                 UpdatedAtUtc = @UpdatedAtUtc,
                 Description = @Description,
                 Solution = @Solution,
                 IsSolved = @IsSolved,
                 IsSolutionShared = @IsSolutionShared,
                 IgnoreReports = @IgnoreReports,
                 IgnoringReportsSinceUtc = @IgnoringReportsSinceUtc,
                 IgnoringRequestedBy = @IgnoringRequestedBy
                 WHERE Id = @id";
         cmd.AddParameter("Id", incident.Id);
         cmd.AddParameter("ApplicationId", incident.ApplicationId);
         cmd.AddParameter("UpdatedAtUtc", incident.UpdatedAtUtc);
         cmd.AddParameter("Description", incident.Description);
         cmd.AddParameter("IgnoreReports", incident.IgnoreReports);
         cmd.AddParameter("IgnoringReportsSinceUtc", incident.IgnoringReportsSinceUtc.ToDbNullable());
         cmd.AddParameter("IgnoringRequestedBy", incident.IgnoringRequestedBy);
         cmd.AddParameter("Solution",
                          incident.Solution == null ? null : EntitySerializer.Serialize(incident.Solution));
         cmd.AddParameter("IsSolved", incident.IsSolved);
         cmd.AddParameter("IsSolutionShared", incident.IsSolutionShared);
         await cmd.ExecuteNonQueryAsync();
     }
 }
コード例 #16
0
        protected override int CalculateSeriesCreationHash(Event master)
        {
            string s = EntitySerializer.Serialize <Event>(master);

            byte[] bytes = Encoding.UTF8.GetBytes(s);
            return((int)ComputeCRC.Compute(0U, bytes, 0, bytes.Length));
        }
コード例 #17
0
        public Task Export(Stream xmlData)
        {
            var export = Tuple.Create(_db.MediaLibary.DoQuery(), _db.MediaLibary.GetAllQuery());

            return(Task.Run(() =>
            {
                EntitySerializer.Serialize(xmlData, export);
            }));
        }
コード例 #18
0
 public SaveState GetSaveState()
 {
     return(new SaveState
     {
         Entities = _systemContainer.EntityEngine.MutableEntities.Select(e => EntitySerializer.Serialize(e)).ToList(),
         Maps = _systemContainer.MapSystem.MapCollection.AllMaps.Select(m => MapSerializer.Serialize(m)).ToList(),
         Time = _systemContainer.TimeSystem.CurrentTime,
         Messages = _systemContainer.MessageSystem.AllMessages.Select(m => MessageSerializer.Serialize(m)).ToList()
     });
 }
コード例 #19
0
        protected override int CalculateSeriesCreationHash(Event master)
        {
            List <byte> list = new List <byte>();
            string      s    = EntitySerializer.Serialize <IList <Event> >(this.AdditionalInstancesToAdd);

            list.AddRange(Encoding.UTF8.GetBytes(s));
            list.AddRange(Encoding.UTF8.GetBytes(this.SingleEventId));
            byte[] array = list.ToArray();
            return((int)ComputeCRC.Compute(0U, array, 0, array.Count <byte>()));
        }
コード例 #20
0
        public void TestEntity_Serialize_MatchesSerializedData(int testCase)
        {
            var testEntity = GetTestEntity(testCase);

            var serialised = EntitySerializer.Serialize(testEntity);

            var expected = LoadSerializedData(testCase);

            serialised.Should().BeEquivalentTo(expected);
        }
コード例 #21
0
        public void EntityCanBeSerializedAndDeserialized()
        {
            Entity entity = new Entity("entity");

            entity.Id = Guid.NewGuid();

            EntityReference entityReference = new EntityReference("entityReference", Guid.NewGuid());

            entityReference.Name = "EntityReference";
            entity.Attributes.Add("entityReference", entityReference);
            entity.FormattedValues.Add("entityReference", entityReference.Name);
#if !XRM_7 && !XRM_6 && !XRM_5
            entity.KeyAttributes.Add("hello", "world");
#if !XRM_8
            OptionSetValueCollection optionSetValues = new OptionSetValueCollection();
            optionSetValues.Add(new OptionSetValue(1));
            optionSetValues.Add(new OptionSetValue(2));
            entity.Attributes.Add("optionSetValues", optionSetValues);
#endif
#endif
            Relationship relationship  = new Relationship("relationship");
            Entity       relatedEntity = new Entity("entity");
            relatedEntity.Id = Guid.NewGuid();
            entity.RelatedEntities.Add(relationship, new EntityCollection(new List <Entity> {
                relatedEntity
            }));
            JsonSerializer serializer = new EntitySerializer();

            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), entity);
            }

            Entity deserializedEntity;
            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedEntity = (Entity)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(entity.LogicalName, deserializedEntity.LogicalName);
            Assert.Equal(entity.Id, deserializedEntity.Id);
            Assert.Equal(entity.Attributes.Count, deserializedEntity.Attributes.Count);

#if !XRM_7 && !XRM_6 && !XRM_5
            Assert.Equal(entity.KeyAttributes.Count, deserializedEntity.KeyAttributes.Count);
#if !XRM_8
            OptionSetValueCollection deserializedOptionSetValues = entity.GetAttributeValue <OptionSetValueCollection>("optionSetValues");
            Assert.NotNull(deserializedOptionSetValues);
            Assert.Equal(optionSetValues.Count, deserializedOptionSetValues.Count);
#endif
#endif
        }
コード例 #22
0
        public void SerializeObject(object obj, string fileName)
        {
            var serializer = new ClassSerializer();

            EntitySerializer correctSerializer = serializers.Single(s => s.CanSerialize(obj));


            var result = correctSerializer.Serialize(obj, moduleDictionary);

            File.WriteAllText(fileName, result);
        }
コード例 #23
0
        public void SaveSystem_GetSaveState_WithEntity_ReturnsSaveStateWithSerialisedEntity()
        {
            var entity = new Entity(0, "New Entity", new IEntityComponent[0]);

            _mutableEntities.Add(entity);

            var result = _saveSystem.GetSaveState();

            var expected = EntitySerializer.Serialize(entity);

            result.Entities.Single().Should().Be(expected);
        }
コード例 #24
0
        public void CreateReport(ErrorReportEntity report)
        {
            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            if (string.IsNullOrEmpty(report.Title) && report.Exception != null)
            {
                report.Title = report.Exception.Message;
                if (report.Title == null)
                {
                    report.Title = "[Exception message was not specified]";
                }
                else if (report.Title.Length > 100)
                {
                    report.Title = report.Title.Substring(0, 100);
                }
            }

            var collections = new List <string>();

            foreach (var context in report.ContextCollections)
            {
                var data = EntitySerializer.Serialize(context);
                if (data.Length > MaxCollectionSize)
                {
                    var tooLargeCtx = new ErrorReportContextCollection(context.Name,
                                                                       new Dictionary <string, string>()
                    {
                        {
                            "Error",
                            $"This collection was larger ({data.Length}bytes) than the threshold of {MaxCollectionSize}bytes"
                        }
                    });

                    data = EntitySerializer.Serialize(tooLargeCtx);
                }
                collections.Add(data);
            }

            _unitOfWork.Insert(report);

            var cols     = string.Join(", ", collections);
            var inboound = new InboundCollection
            {
                JsonData = $"[{cols}]",
                ReportId = report.Id
            };

            _unitOfWork.Insert(inboound);
        }
コード例 #25
0
ファイル: Readme.cs プロジェクト: rexwhitten/JsonLD.Entities
public void UsesInlineContextWhenSerializing(Type entityType)
{
    // given
    const string expected = "{ '@context': { '@base': 'http://example.com/' } }";
    var entity = Activator.CreateInstance(entityType);
    var serializer = new EntitySerializer();

    // when
    var json = serializer.Serialize(entity);

    // then
    Assert.That(JToken.DeepEquals(json, JObject.Parse(expected)), "Actual object is {0}", json);
}
コード例 #26
0
ファイル: Readme.cs プロジェクト: serialseb/JsonLD.Entities
    public void SerializesTypesPropertyAsAtTypes(Type type, string expectedJson)
    {
        // given
        var expected   = JObject.Parse(expectedJson);
        var entity     = Activator.CreateInstance(type);
        var serializer = new EntitySerializer();

        // when
        var json = serializer.Serialize(entity);

        // then
        Assert.That(JToken.DeepEquals(json, expected), "Actual object was {0}", json);
    }
コード例 #27
0
ファイル: Readme.cs プロジェクト: rexwhitten/JsonLD.Entities
public void SerializesTypesPropertyAsAtTypes(Type type, string expectedJson)
{
    // given
    var expected = JObject.Parse(expectedJson);
    var entity = Activator.CreateInstance(type);
    var serializer = new EntitySerializer();

    // when
    var json = serializer.Serialize(entity);

    // then
    Assert.That(JToken.DeepEquals(json, expected), "Actual object was {0}",  json);
}
コード例 #28
0
ファイル: Readme.cs プロジェクト: lambdakris/JsonLD.Entities
    public void UsesInlineContextPropertyWhenSerializing(Type entityType)
    {
        // given
        const string expected   = "{ '@context': { '@base': 'http://example.com/' } }";
        var          entity     = Activator.CreateInstance(entityType);
        var          serializer = new EntitySerializer();

        // when
        var json = serializer.Serialize(entity);

        // then
        Assert.True(JToken.DeepEquals(json, JObject.Parse(expected)), $"Actual object is {json}");
    }
コード例 #29
0
ファイル: Readme.cs プロジェクト: lambdakris/JsonLD.Entities
    public void UsesGetContextMethodSerializing()
    {
        // given
        const string expected   = "{ '@context': { '@base': 'http://example.com/test/' } }";
        var          entity     = new ContextInlineMethod("test");
        var          serializer = new EntitySerializer();

        // when
        var json = serializer.Serialize(entity);

        // then
        Assert.True(JToken.DeepEquals(json, JObject.Parse(expected)), $"Actual object is {json}");
    }
コード例 #30
0
        public async Task CreateAsync(CollectionMetadata entity)
        {
            var props = EntitySerializer.Serialize(entity.Properties);

            using (var cmd = _unitOfWork.CreateDbCommand())
            {
                cmd.CommandText =
                    @"INSERT INTO CollectionMetadata (Name, ApplicationId, Properties) VALUES(@Name, @ApplicationId, @Properties)";
                cmd.AddParameter("Name", entity.Name);
                cmd.AddParameter("ApplicationId", entity.ApplicationId);
                cmd.AddParameter("Properties", props);
                await cmd.ExecuteNonQueryAsync();
            }
        }
コード例 #31
0
        public async Task UpdateAsync(CollectionMetadata collection)
        {
            var props = EntitySerializer.Serialize(collection.Properties);

            using (var cmd = _unitOfWork.CreateDbCommand())
            {
                cmd.CommandText = @"UPDATE CollectionMetadata SET Properties = @Properties
                                    WHERE Id = @id";

                cmd.AddParameter("Id", collection.Id);
                cmd.AddParameter("Properties", props);
                await cmd.ExecuteNonQueryAsync();
            }
        }
コード例 #32
0
        protected override Event InitialMasterOperation()
        {
            string       rawData            = EntitySerializer.Serialize <ICalendarInteropSeriesAction>(this.actionToPropagate);
            Event        initialMasterValue = this.actionToPropagate.GetInitialMasterValue();
            IActionQueue actionQueue        = initialMasterValue;
            ActionInfo   actionInfo         = new ActionInfo(this.actionToPropagate.CommandId, DateTime.UtcNow, this.actionToPropagate.GetType().Name, rawData);

            actionQueue.ActionsToAdd = new ActionInfo[]
            {
                actionInfo
            };
            Event @event = base.ExecuteOnMasterWithConflictRetries(new Func <Event, Event>(this.actionToPropagate.InitialMasterOperation), initialMasterValue, true);

            this.precedingAction = SeriesInlineInterop.GetPrecedingActionFromQueue(@event);
            return(@event);
        }
コード例 #33
0
ファイル: Readme.cs プロジェクト: rexwhitten/JsonLD.Entities
public void Can_serialize_class_instance_to_literal()
{
    // given
    var entity = new RequestLogItem { Ip = IPAddress.Parse("148.9.20.34") };
    var contextProvider = new StaticContextProvider();
    var context = JObject.Parse(@"
{
    'ip': {
        '@id': 'http://rdfs.org/sioc/ns#ip_address'
    }
}");
    contextProvider.SetContext(typeof(RequestLogItem), context);

    // when
    IEntitySerializer serializer = new EntitySerializer(contextProvider);
    dynamic jsonLd = serializer.Serialize(entity);

    // then
    Assert.That((string)jsonLd.ip, Is.EqualTo("148.9.20.34"));
}
コード例 #34
0
ファイル: Readme.cs プロジェクト: rexwhitten/JsonLD.Entities
public void Can_serialize_object_to_JSON_LD()
{
    // given
    var person = new Person
        {
            Id = new Uri("http://t-code.pl/#tomasz"),
            Name = "Tomasz",
            LastName = "Pluskiewicz"
        };
    var @context = JObject.Parse("{ '@context': 'http://example.org/context/Person' }");

    var contextProvider = new StaticContextProvider();
    contextProvider.SetContext(typeof(Person), @context);

    // when
    IEntitySerializer serializer = new EntitySerializer(contextProvider);
    dynamic json = serializer.Serialize(person);

    // then
    Assert.That((string)json.name, Is.EqualTo("Tomasz"));
    Assert.That((string)json.lastName, Is.EqualTo("Pluskiewicz"));
    Assert.That((string)json["@id"], Is.EqualTo("http://t-code.pl/#tomasz"));
    Assert.That((string)json["@type"][0], Is.EqualTo("http://xmlns.com/foaf/0.1/Person"));
    Assert.That(json["@context"], Is.Not.Null);
}