예제 #1
0
        public async Task CreateAsync(Animal entity)
        {
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", "bearer " + token);

            var serializedAnimal = serializerService.Serialize(entity);
            var httpContent      = new StringContent(serializedAnimal, Encoding.UTF8, "application/json");

            await httpClient.PostAsync("https://petshop-animalmicroservice-api-sergio.azurewebsites.net/api/animals", httpContent);
        }
예제 #2
0
        public void DuplicateKeywordsIssue()
        {
            Component          c            = GetTestModel <Component>();
            int                nrOfKeywords = c.Fields["test"].KeywordValues.Count;
            ISerializerService service      = GetService(false);
            string             s            = service.Serialize <Component>(c);
            Component          c2           = service.Deserialize <Component>(s);
            string             s2           = service.Serialize <Component>(c2);
            Component          c3           = service.Deserialize <Component>(s2);

            Assert.IsTrue(c3.Fields["test"].KeywordValues.Count == nrOfKeywords);
        }
예제 #3
0
        public void SerializeStringFieldType()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            TypeDraft          typeDraft         = new TypeDraft();

            typeDraft.Key             = "new-key";
            typeDraft.ResourceTypeIds = new List <ResourceTypeId>();
            typeDraft.ResourceTypeIds.Add(ResourceTypeId.Category);
            typeDraft.ResourceTypeIds.Add(ResourceTypeId.CustomLineItem);
            FieldDefinition fieldDefinition = new FieldDefinition();

            fieldDefinition.Name     = "string-field";
            fieldDefinition.Required = true;
            fieldDefinition.Label    = new LocalizedString();
            fieldDefinition.Label.Add("en", "string description");
            fieldDefinition.InputHint  = TextInputHint.SingleLine;
            fieldDefinition.Type       = new StringFieldType();
            typeDraft.FieldDefinitions = new List <FieldDefinition>();
            typeDraft.FieldDefinitions.Add(fieldDefinition);
            string result              = serializerService.Serialize(typeDraft);
            JToken resultFormatted     = JValue.Parse(result);
            string serialized          = File.ReadAllText("Resources/FieldTypes/Serialized.json");
            JToken serializedFormatted = JValue.Parse(serialized);

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
예제 #4
0
        public ValueTask <ImmutableArray <(Checksum, object)> > GetAssetsAsync(
            int serviceId, ISet <Checksum> checksums, ISerializerService deserializerService, CancellationToken cancellationToken)
        {
            var results = new List <(Checksum, object)>();

            foreach (var checksum in checksums)
            {
                if (_map.TryGetValue(checksum, out var data))
                {
                    using var stream = new MemoryStream();
                    using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken))
                    {
                        _serializerService.Serialize(data, writer, cancellationToken);
                    }

                    stream.Position  = 0;
                    using var reader = ObjectReader.GetReader(stream, leaveOpen: true, cancellationToken);
                    var asset = deserializerService.Deserialize <object>(data.GetWellKnownSynchronizationKind(), reader, cancellationToken);
                    Contract.ThrowIfTrue(asset is null);
                    results.Add((checksum, asset));
                }
                else
                {
                    throw ExceptionUtilities.UnexpectedValue(checksum);
                }
            }

            return(ValueTaskFactory.FromResult(results.ToImmutableArray()));
        }
예제 #5
0
        public bool SignUp(SignUpViewModel signUpViewModel)
        {
            var userPasswordDto = new UserPasswordDto
            {
                user = new UserPasswordDto.User
                {
                    userName             = signUpViewModel.Username,
                    email                = signUpViewModel.Email,
                    emailConfirmed       = true,
                    phoneNumber          = signUpViewModel.Phone,
                    phoneNumberConfirmed = true
                },
                password = new UserPasswordDto.Password
                {
                    password        = signUpViewModel.Password,
                    confirmPassword = signUpViewModel.Password
                }
            };

            var token      = GetAdminToken();
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", "bearer " + token);
            var serializedUserPassword = serializerService.Serialize(userPasswordDto);
            var httpContent            = new StringContent(serializedUserPassword, Encoding.UTF8, "application/json");
            var result = httpClient.PostAsync("https://petshop-sergio-iammicroservice-api.azurewebsites.net/api/UsersAndRoles", httpContent).Result;

            if (!result.IsSuccessStatusCode)
            {
                return(false);
            }
            return(true);
        }
예제 #6
0
 public static Checksum Create <T>(WellKnownSynchronizationKind kind, T value, ISerializerService serializer)
 {
     using var stream       = SerializableBytes.CreateWritableStream();
     using var objectWriter = new ObjectWriter(stream);
     objectWriter.WriteInt32((int)kind);
     serializer.Serialize(value, objectWriter, CancellationToken.None);
     return(Create(stream));
 }
        public async Task CreateAsync(Order entity)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "bearer " + token);
            var orderSerialized = serializerService.Serialize(entity);
            var httpContent     = new StringContent(orderSerialized, Encoding.UTF8, "application/json");
            await client.PostAsync("https://worldstore-gustavo-order-microservice-api.azurewebsites.net/api/orders", httpContent);
        }
        public void CentPrecisionMoneySerialization()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            var m = Money.FromDecimal("EUR", 1234.5678M);

            var    serialize           = serializerService.Serialize(m);
            JToken resultFormatted     = JValue.Parse(serialize);
            JToken serializedFormatted = JValue.Parse(@"{""type"":""centPrecision"",""currencyCode"":""EUR"",""centAmount"":123457}");

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
        public async Task CreateAsync(Post entity)
        {
            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", "bearer " + token);
            var serializedPost = serializerService.Serialize(entity);
            var httpContent    = new StringContent(serializedPost, Encoding.UTF8, "application/json");
            await httpClient.PostAsync("https://amazinginsta-postmicroservice-api-gustavo.azurewebsites.net/api/posts", httpContent);

            //await httpClient.PostAsync("http://localhost:53913/api/posts", httpContent);
        }
예제 #10
0
        public void SendData <T>(string routingKey, string exchangeName, T data)
        {
            IBasicProperties properties = _model.CreateBasicProperties();

            properties.SetPersistent(true);
            properties.ReplyTo = routingKey;
            properties.Type    = typeof(T).AssemblyQualifiedName;

            byte[] buffer = _serializerService.Serialize(data);
            _model.BasicPublish(exchangeName, routingKey, properties, buffer);
        }
            static void WriteAsset(ObjectWriter writer, ISerializerService serializer, Checksum checksum, SolutionAsset asset, CancellationToken cancellationToken)
            {
                checksum.WriteTo(writer);
                writer.WriteInt32((int)asset.Kind);

                // null is already indicated by checksum and kind above:
                if (asset.Value is not null)
                {
                    serializer.Serialize(asset.Value, writer, cancellationToken);
                }
            }
예제 #12
0
        public void SerializeCustomField()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            var customFieldsDraft = new CustomFieldsDraft()
            {
                Fields = new Fields()
                {
                    { "foo", "bar" },
                    { "Fooz", "Bars" },
                    { "Bar", new EnumValue {
                          Key = "BarKey", Label = "BarLabel"
                      } }
                }
            };
            string result1 = serializerService.Serialize(customFieldsDraft);

            JToken resultFormatted     = JValue.Parse(result1);
            string serialized          = File.ReadAllText("Resources/CustomFields/CustomFieldsDraft.json");
            JToken serializedFormatted = JValue.Parse(serialized);

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);

            var draft = new Fields()
            {
                { "foo", "bar" },
                { "Fooz", "Bars" },
                { "Bar", new EnumValue {
                      Key = "BarKey", Label = "BarLabel"
                  } }
            };

            string result2 = serializerService.Serialize(draft);

            resultFormatted     = JValue.Parse(result2);
            serialized          = File.ReadAllText("Resources/CustomFields/Fields.json");
            serializedFormatted = JValue.Parse(serialized);
            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
예제 #13
0
        public void SerializeTextAttribute()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            string             serialized        = File.ReadAllText("Resources/Attributes/Text.json");
            ProductVariant     deserialized      = serializerService.Deserialize <ProductVariant>(serialized);

            string result          = serializerService.Serialize(deserialized.Attributes[0]);
            JToken resultFormatted = JValue.Parse(result);

            string expectedSerialized  = File.ReadAllText("Resources/Attributes/Text.json");
            JToken serializedFormatted = JObject.Parse(expectedSerialized).GetValue("attributes")[0];

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
        public void SerializeStagedOrderUpdateAction()
        {
            //Deserialize OrderEditResult (OrderEditPreviewSuccess)
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            var setCustomerEmailAction           = new SetCustomerEmailUpdateAction {
                Email = "TestEmail"
            };
            var stagedActions = new List <IStagedOrderUpdateAction>
            {
                setCustomerEmailAction
            };
            var serialized = serializerService.Serialize(stagedActions);

            Assert.NotEmpty(serialized);
        }
예제 #15
0
        protected T SerializeDeserializeModel <T>(IModel inputModel) where T : ContentModel.Model
        {
            ISerializerService serializer = GetService(compressionEnabled: false);

            string serializedData = serializer.Serialize(inputModel);

            Assert.IsNotNull(serializedData, "Serialized data");
            Console.WriteLine(serializedData);

            T deserializedModel = serializer.Deserialize <T>(serializedData);

            Assert.IsNotNull(deserializedModel, "Deserialized Model");

            return(deserializedModel);
        }
        public void ResourceIdentifierSerializationAsGeneric()
        {
            ISerializerService serializerService         = this.serializationFixture.SerializerService;
            ResourceIdentifier <ProductType> productType = new ResourceIdentifier <ProductType>
            {
                Key = "Key12",
                Id  = "f40fcd15-b1c2-4279-9cfa-f6083e6a2988"
            };
            string result              = serializerService.Serialize(productType);
            JToken resultFormatted     = JValue.Parse(result);
            string serialized          = File.ReadAllText("Resources/Types/ResourceIdentifier.json");
            JToken serializedFormatted = JValue.Parse(serialized);

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
예제 #17
0
        public async Task <InvoiceDto> CreatePaymentAsync(InvoiceDto invoice)
        {
            var token  = GetToken();
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "bearer " + token);

            var invoiceSerialized = _serializerService.Serialize(invoice);
            var httpContent       = new StringContent(invoiceSerialized, Encoding.UTF8, "application/json");
            var result            = await client.PostAsync(_baseUrl, httpContent);

            var serializedInvoice = result.Content.ReadAsStringAsync().Result;
            var paidInvoice       = _serializerService.Deserialize <InvoiceDto>(serializedInvoice);

            return(paidInvoice);
        }
예제 #18
0
        private void SerializeJson <T>(bool isCompressed) where T : IModel
        {
            ISerializerService service = GetService(isCompressed);

            for (int i = 0; i < loop; i++)
            {
                T model = GetTestModel <T>();
                Assert.IsNotNull(model, "error retrieving test model");
                string _serializedString = service.Serialize <T>(model);
                Assert.IsNotNull(_serializedString);
                if (!isCompressed)
                {
                    Assert.IsTrue(_serializedString.Contains("Test - component.title"));
                }
            }
        }
        private static SolutionAsset CloneAsset(ISerializerService serializer, SolutionAsset asset)
        {
            using var stream = SerializableBytes.CreateWritableStream();

            using (var writer = new ObjectWriter(stream, leaveOpen: true))
            {
                serializer.Serialize(asset.Value, writer, CancellationToken.None);
            }

            stream.Position  = 0;
            using var reader = ObjectReader.TryGetReader(stream);
            var recovered        = serializer.Deserialize <object>(asset.Kind, reader, CancellationToken.None);
            var assetFromStorage = new SolutionAsset(serializer.CreateChecksum(recovered, CancellationToken.None), recovered);

            Assert.Equal(asset.Checksum, assetFromStorage.Checksum);
            return(assetFromStorage);
        }
예제 #20
0
        private void SavePlaylist(string file)
        {
            var container = new PlaylistContainer {
                Files = Files.ToArray(), Shuffle = Shuffle
            };

            try
            {
                using (var stream = File.Open(file, FileMode.Create, FileAccess.ReadWrite))
                {
                    serializerService.Serialize(container, stream);
                    stream.Flush(true);
                }
            }
            catch (Exception e)
            {
                LogException(e, MethodBase.GetCurrentMethod());
            }
        }
        public void ProductDraftSerializationUsingReference()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;

            var productDraft = new ProductDraft
            {
                Name = new LocalizedString()
                {
                    { "en", "name" },
                    { "en-US", "name" }
                },
                Slug = new LocalizedString()
                {
                    { "en", "slug" }
                },
                ProductType = new Reference <ProductType>
                {
                    Id = "ProductTypeId"
                },
                TaxCategory = new Reference <TaxCategory>
                {
                    Id = "TaxCategoryId"
                },
                Categories = new List <IReference <Category> >()
                {
                    new Reference <Category>
                    {
                        Id = "CategoryId"
                    }
                },
                State = new Reference <State>
                {
                    Id = "StateId"
                }
            };

            string result              = serializerService.Serialize(productDraft);
            JToken resultFormatted     = JValue.Parse(result);
            string serialized          = File.ReadAllText("Resources/Types/ProductDraftWithReference.json");
            JToken serializedFormatted = JValue.Parse(serialized);

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
        public void SerializeCustomObjectDraft()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            var customObjectDraft = new CustomObjectDraft <CustomFooBar>
            {
                Key       = "key1",
                Container = "container1",
                Value     = new CustomFooBar
                {
                    Foo = "Bar"
                },
                Version = 1
            };
            string result              = serializerService.Serialize(customObjectDraft);
            JToken resultFormatted     = JValue.Parse(result);
            string serialized          = File.ReadAllText("Resources/CustomObjects/FooBarCustomObject.json");
            JToken serializedFormatted = JValue.Parse(serialized);

            serializedFormatted.Should().BeEquivalentTo(resultFormatted);
        }
예제 #23
0
        private void SerializeXml <T>(bool isCompressed) where T : IModel
        {
            ISerializerService service = GetService(isCompressed);

            for (int i = 0; i < loop; i++)
            {
                T model = GetTestModel <T>();
                Assert.IsNotNull(model, "error retrieving test model");
                string _serializedString = service.Serialize <T>(model);
                Assert.IsNotNull(_serializedString);
                if (!isCompressed)
                {
                    if (typeof(T) == typeof(ComponentPresentation))
                    {
                        Assert.IsTrue(_serializedString.Contains(GetTestTitle <Component>()));
                    }
                    else
                    {
                        Assert.IsTrue(_serializedString.Contains(GetTestTitle <T>()));
                    }
                }
            }
        }
        public void SerializeReviewDraftInvalidLocale()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            ReviewDraft        reviewDraft       = new ReviewDraft()
            {
                Locale = "en-ZZZ"
            };
            ValidationException exception = Assert.Throws <ValidationException>(() => serializerService.Serialize(reviewDraft));

            Assert.Single(exception.Errors);
        }
예제 #25
0
 /// <summary>
 /// Serialize this instance to a string
 /// </summary>
 public virtual string Serialize()
 {
     return(_serializerService.Serialize(this));//t
 }
예제 #26
0
 /// <summary>
 /// Writes to.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="stream">The stream.</param>
 public void WriteTo(T value, Stream stream)
 {
     serializerService.Serialize(value, stream);
 }
예제 #27
0
 public override Task WriteObjectToAsync(ObjectWriter writer, CancellationToken cancellationToken)
 {
     _serializer.Serialize(_value, writer, cancellationToken);
     return(SpecializedTasks.EmptyTask);
 }
예제 #28
0
 public override Task WriteObjectToAsync(ObjectWriter writer, CancellationToken cancellationToken)
 {
     _serializer.Serialize(_value, writer, cancellationToken);
     return(Task.CompletedTask);
 }
        public void SerializeReviewDraftInvalidCountry()
        {
            ISerializerService serializerService = this.serializationFixture.SerializerService;
            CartDraft          cartDraft         = new CartDraft()
            {
                Currency = "EUR",
                Country  = "ZZ"
            };
            ValidationException exception = Assert.Throws <ValidationException>(() => serializerService.Serialize(cartDraft));

            Assert.Single(exception.Errors);
        }
예제 #30
0
        public async Task Save(Func <bool, Task <FileBase> > writeFile, FileType type, string path = null)
        {
            try
            {
                bool advancedMode = false;

                if (path == null)
                {
                    bool useExplorerBrowser = App.Settings.UseWindowsExplorer;

                    if (!useExplorerBrowser)
                    {
                        List <FileType> fileTypes = new List <FileType>();
                        fileTypes.Add(type);
                        FileBrowserView browser = new FileBrowserView(this.fileSources, fileTypes.ToArray(), FileBrowserView.Modes.Save);
                        await App.Services.Get <IViewService>().ShowDrawer(browser);

                        while (browser.IsOpen)
                        {
                            await Task.Delay(10);
                        }

                        path               = browser.FilePath;
                        advancedMode       = browser.AdvancedMode;
                        useExplorerBrowser = browser.UseFileBrowser;
                    }

                    if (useExplorerBrowser)
                    {
                        path = await App.Current.Dispatcher.InvokeAsync <string>(() =>
                        {
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.Filter         = ToFilter(type);
                            bool?result        = dlg.ShowDialog();

                            if (result != true)
                            {
                                return(null);
                            }

                            return(Path.Combine(Path.GetDirectoryName(dlg.FileName), Path.GetFileNameWithoutExtension(dlg.FileName)));
                        });
                    }

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

                path += "." + type.Extension;

                FileBase file = await writeFile.Invoke(advancedMode);

                using FileStream stream = new FileStream(path, FileMode.Create);
                if (type.Serialize != null)
                {
                    type.Serialize.Invoke(stream, file);
                }
                else
                {
                    using TextWriter writer = new StreamWriter(stream);
                    string json = serializer.Serialize(file);
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Log.Write(new Exception("Failed to save file", ex), "Files", Log.Severity.Error);
            }
        }