コード例 #1
0
        public void LinkFieldSerialization(IServiceProvider serviceProvider, IObjectRepositoryContainer container, string name, string path)
        {
            // Arrange
            var sut       = CreateJsonRepositorySerializer(serviceProvider, new ModelObjectSerializationContext(container));
            var link      = new LazyLink <Page>(container, new ObjectPath(UniqueId.CreateNew(), path));
            var linkField = new Field.Builder(serviceProvider)
            {
                Id      = UniqueId.CreateNew(),
                Name    = name,
                Content = FieldContent.NewLink(new FieldLinkContent(link))
            }.ToImmutable();

            // Act
            var json = Serialize(sut, linkField);

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
            {
                var deserialized         = (Field)sut.Deserialize(stream, _ => throw new NotSupportedException());
                var deserializedLazyLink = deserialized.Content.MatchOrDefault(matchLink: c => c.Target);

                // Assert
                Assert.That(deserialized.Id, Is.EqualTo(linkField.Id));
                Assert.That(deserialized.Name, Is.EqualTo(name));
                Assert.That(deserializedLazyLink.Path.Path, Is.EqualTo(path));
            }
        }
コード例 #2
0
        public void EqualsTest_CompareWithNull_NotEquals()
        {
            var firstFieldContent = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value2");

            Assert.IsFalse(firstFieldContent.Equals(null));
        }
コード例 #3
0
        public void FieldContentConstructorWithArguments_FillNameAndValue()
        {
            var fieldContent = new FieldContent("Name", "Value");

            Assert.AreEqual("Name", fieldContent.Name);
            Assert.AreEqual("Value", fieldContent.Value);
        }
コード例 #4
0
        public void EqualsTest_ValuesAreEquel_Equals()
        {
            var firstFieldContent = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value");

            Assert.IsTrue(firstFieldContent.Equals(secondFieldContent));
        }
コード例 #5
0
        public void EqualsTest_ValuesAreNotEqual_NotEquals()
        {
            var firstFieldContent = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value2");

            Assert.IsFalse(firstFieldContent.Equals(secondFieldContent));
        }
コード例 #6
0
        public void EqualsTest_CompareWithNull_NotEquals()
        {
            var firstFieldContent  = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value2");

            Assert.IsFalse(firstFieldContent.Equals(null));
        }
コード例 #7
0
        public void EqualsTest_ValuesAreNotEqual_NotEquals()
        {
            var firstFieldContent  = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value2");

            Assert.IsFalse(firstFieldContent.Equals(secondFieldContent));
        }
コード例 #8
0
        public void EqualsTest_ValuesAreEquel_Equals()
        {
            var firstFieldContent  = new FieldContent("Name", "Value");
            var secondFieldContent = new FieldContent("Name", "Value");

            Assert.IsTrue(firstFieldContent.Equals(secondFieldContent));
        }
コード例 #9
0
        public async Task <bool> Handle(PrivateSession session, UpdateFieldRequest request, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory().ApiName(apiName).Method(PrivateConnectionMethod.Update))
            {
                try
                {
                    var content = new FieldContent
                    {
                        Properties = request.Data
                                     .Where(entry => entry.Key != FieldProperty.Resource && entry.Key != FieldProperty.Name && entry.Key != FieldProperty.DataType && entry.Key != FieldProperty.Id)
                                     .ToDictionary(entry => entry.Key, PropertyValue)
                    };

                    using (var response = await connection.SendAsync(new Json.UpdateFieldRequest {
                        Update = new Dictionary <Guid, FieldContent> {
                            { request.Id.Value, content }
                        }
                    }))
                    {
                        await response.ReadAsStreamAsync();

                        return(true);
                    }
                }
                catch (ConnectionResponseException e)
                {
                    throw e.ToRequestException("Could not update field", request);
                }
            }
        }
コード例 #10
0
        private void applyConfig()
        {
            IContract cntrc = myControl as IContract;

            if (cntrc.allDataAreSaved == true)
            {
                FieldContent[] allItems = new FieldContent[cntrc.allAttributes.Count];

                int i = 0;
                foreach (var item in cntrc.allAttributes.Keys.ToList())
                {
                    allItems[i] = new FieldContent(item, cntrc.allAttributes[item]);
                    i++;
                }
                var valuesToFill = new Content(allItems);

                using (var outputDocument = new TemplateProcessor(contractTempFile)
                                            .SetRemoveContentControls(true))
                {
                    outputDocument.FillContent(valuesToFill);
                    outputDocument.SaveChanges();
                }
            }
            else
            {
                MessageBox.Show("please save all fields and try again.");
            }
        }
コード例 #11
0
 /// <summary>
 /// Code used to display the field value in the DisplayForm
 /// </summary>
 /// <param name="output"></param>
 protected override void RenderFieldForDisplay(System.Web.UI.HtmlTextWriter output)
 {
     if (this.ItemFieldValue != null)
     {
         FieldContent picture = new FieldContent(this.ItemFieldValue.ToString());
         output.WriteLine(string.Format("<a href='{0}' target='_blank'><img src='{1}' style='border-width:0px;' /></a>", picture.FullUrl, picture.Thumbnail));
     }
 }
コード例 #12
0
        public void FieldContentConstructorWithArgumentsShouldFillNameAndValue()
        {
            //Given
            //When
            var fieldContent = new FieldContent(Name, Value);

            //Then
            fieldContent.Name.Should().Be(Name);
            fieldContent.Value.Should().Be(Value);
        }
コード例 #13
0
        private static Content PrepareProposalContent(ExcelFile excelFile, bool changeTemplateHeader)
        {
            var listTable        = new List <TableContent>();
            var listFieldContent = new List <FieldContent>();

            foreach (var workSheet in excelFile.Content)
            {
                switch (workSheet.Type)
                {
                case WorkSheetTypeEnum.Table:
                    var tableContent = new TableContent(workSheet.Name);
                    if (tableContent.Rows == null && changeTemplateHeader)
                    {
                        var arrayHeaderRow = new FieldContent[workSheet.HeaderRow.Cells.Count];
                        for (int column = 0; column < workSheet.HeaderRow.Cells.Count; column++)
                        {
                            arrayHeaderRow[column] = new FieldContent(workSheet.HeaderRow.Cells[column], workSheet.HeaderRow.Cells[column]);
                        }

                        tableContent.AddRow(arrayHeaderRow);
                    }

                    foreach (var row in workSheet.Rows)
                    {
                        var arrayRowField = new FieldContent[row.Cells.Count];
                        for (int column = 0; column < row.Cells.Count; column++)
                        {
                            arrayRowField[column] = new FieldContent(workSheet.HeaderRow.Cells[column], row.Cells[column]);
                        }

                        tableContent.AddRow(arrayRowField);
                    }

                    listTable.Add(tableContent);
                    break;

                case WorkSheetTypeEnum.Field:
                    foreach (var row in workSheet.Rows)
                    {
                        listFieldContent.Add(new FieldContent(row.Cells.FirstOrDefault(), row.Cells.LastOrDefault()));
                    }
                    break;

                default:
                    break;
                }
            }

            return(new Content
            {
                Tables = listTable,
                Fields = listFieldContent
            });
        }
コード例 #14
0
        public void EqualsTest_CompareWithNull_NotEquals()
        {
            //Given
            var firstFieldContent = new FieldContent(Name, Value);

            //When
            var result = firstFieldContent.Equals(null);

            //Then
            result.Should().BeFalse();
        }
コード例 #15
0
ファイル: MsgBilder.cs プロジェクト: TonEnfer/MailSender
        public static void Build(List <TextParameters> param, string templatePath)
        {
            string saveDir = Path.GetDirectoryName(templatePath) + "\\Generated";

            if (!Directory.Exists(saveDir))
            {
                Directory.CreateDirectory(saveDir);
            }
            if (Path.GetExtension(templatePath) == ".txt")
            {
                string text = Encoding.Default.GetString(File.ReadAllBytes(templatePath));
                foreach (var ppp in param)
                {
                    if (text.Contains("{" + ppp.name + "}"))
                    {
                        text = text.Replace("{" + ppp.name + "}", ppp.value);
                    }
                }


                string newFilePath = saveDir + "\\" + Path.GetFileNameWithoutExtension(templatePath) + "-" +
                                     (from n in param where n.name == "MsgNumber" select n.value).First() + ".txt";

                File.WriteAllText(newFilePath, text);
            }
            else if (Path.GetExtension(templatePath) == ".docx")
            {
                var valuesToFill = new Content();
                foreach (var ppp in param)
                {
                    FieldContent f = new FieldContent(ppp.name, ppp.value);
                    valuesToFill.Fields.Add(f);
                }
                string newFilePath = saveDir + "\\" + Path.GetFileNameWithoutExtension(templatePath) + "-" +
                                     (from n in param where n.name == "MsgNumber" select n.value).First() + ".docx";

                try
                {
                    File.Copy(templatePath, newFilePath);

                    using (var outputDocument = new TemplateProcessor(newFilePath)
                                                .SetRemoveContentControls(true))
                    {
                        outputDocument.FillContent(valuesToFill);
                        outputDocument.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
コード例 #16
0
        public void ShouldCompareTwoObjects(string name, string firstValue, string secondValue, bool expectedCompareResult)
        {
            //Given
            var firstFieldContent  = new FieldContent(name, firstValue);
            var secondFieldContent = new FieldContent(name, secondValue);

            //When
            var result = firstFieldContent.Equals(secondFieldContent);

            //Then
            result.Should().Be(expectedCompareResult);
        }
コード例 #17
0
        public async Task <Guid> Handle(PrivateSession session, CreateFieldRequest request, Func <PrivateConnection> connectionFactory)
        {
            using (var connection = connectionFactory().ApiName(FIELD).Method(PrivateConnectionMethod.Create))
            {
                try
                {
                    var content = new FieldContent
                    {
                        Resource   = request.Resource,
                        Properties = request.Properties
                                     .Where(entry => entry.Key != FieldProperty.Resource && entry.Key != FieldProperty.Name && entry.Key != FieldProperty.DataType && entry.Key != FieldProperty.Id && entry.Key != FieldProperty.OptionMaster)
                                     .ToDictionary(entry => entry.Key, PropertyValue)
                    };
                    var dataType = ToDataType(request.FieldType);
                    if (DataType.Null != dataType)
                    {
                        content.DataType = dataType.ToString().ToLower();
                    }
                    if (request.Properties.ContainsKey(FieldProperty.Name))
                    {
                        content.Alias = (string)request.Properties[FieldProperty.Name];
                    }
                    if (request.Properties.ContainsKey(FieldProperty.OptionMaster))
                    {
                        if (request.Properties[FieldProperty.OptionMaster] is string)
                        {
                            var getOptionIdRequest =
                                (Option.GetOptionRequest.Builder().SelectDefault() as Option.GetOptionRequest.IBuilderWithSelect)
                                .WhereName((string)request.Properties[FieldProperty.OptionMaster]);
                            content.Properties.Add(FieldProperty.OptionMaster,
                                                   (new Option.GetOptionWithoutUsingIdHandler())
                                                   .Handle(session, getOptionIdRequest.Content, connectionFactory).Result.OptionData.Single().Key);
                        }
                        else if (request.Properties[FieldProperty.OptionMaster] is ulong || request.Properties[FieldProperty.OptionMaster] is Guid)
                        {
                            content.Properties.Add(FieldProperty.OptionMaster, request.Properties[FieldProperty.OptionMaster]);
                        }
                    }

                    using (var response = await connection.SendAsync(new Json.CreateFieldRequestData {
                        Create = content
                    }))
                    {
                        return((await response.ReadAsync <Json.CreateFieldResponse>()).Id);
                    }
                }
                catch (ConnectionResponseException e)
                {
                    throw e.ToRequestException("Could not create field", request);
                }
            }
        }
コード例 #18
0
        public static List <IContentItem> AddSimpleActions(Dictionary <string, Func <string> > dict)
        {
            var contentItems = new List <IContentItem>();


            foreach (var func in dict)
            {
                var item = new FieldContent(func.Key, func.Value());
                contentItems.Add(item);
            }

            return(contentItems);
        }
コード例 #19
0
        public void WithModifiesLink(ObjectRepository repository, Page newLinkedPage)
        {
            // Arrange
            var field = repository.Flatten().OfType <Field>().First(
                f => f.Content.Match(() => false, matchLink: l => true));

            // Act
            var modified = repository.With(field, f => f.Content, FieldContent.NewLink(new FieldLinkContent(new LazyLink <Page>(repository.Container, newLinkedPage))));
            var link     = modified.Content.MatchOrDefault(matchLink: l => l.Target);

            // Assert
            Assert.That(link.Link, Is.EqualTo(newLinkedPage));
        }
コード例 #20
0
        public void LinkWithWrongObjectPathIsDetected(IObjectRepositoryContainer container, ObjectRepository repository)
        {
            // Arrange
            var linkField = repository.Flatten().OfType <Field>().FirstOrDefault(
                f => f.Content.MatchOrDefault(matchLink: l => true));

            // Act
            var failingLink = new LazyLink <Page>(container, new ObjectPath(linkField.Repository.Id, "foo"));
            var modified    = repository.With(linkField, f => f.Content, FieldContent.NewLink(new FieldLinkContent(failingLink)));
            var result      = modified.Repository.Validate();

            // Assert
            Assert.That(result, Has.Property(nameof(ValidationResult.IsValid)).False);
            Assert.That(result.Errors, Has.Count.EqualTo(1));
            Assert.That(result.ToString(), Does.Contain("Unexisting object"));
            Assert.That(result.Errors[0], Has.Property(nameof(ValidationFailure.PropertyName)).EqualTo("Content.fieldLinkContent.<Target>k__BackingField.Path"));
            Assert.That(result.Errors[0].Context.Instance, Is.EqualTo(modified));
            Assert.That(result.Errors[0].Context.Parent.Instance, Is.EqualTo(modified.Parent));
        }
コード例 #21
0
        public void PreCommitWhenPropertyChangeGetsFired(GitHooks sut, ObjectRepository repository, IObjectRepositoryContainer <ObjectRepository> container, Signature signature, string message)
        {
            // Arrange
            repository = container.AddRepository(repository, signature, message);
            CommitStartedEventArgs lastEvent = null;

            sut.CommitStarted += (_, args) => lastEvent = args;
            var field = repository.Flatten().OfType <Field>().First(
                f => f.Content.MatchOrDefault(matchLink: l => true));

            // Act
            var page          = repository.Applications[0].Pages[1];
            var newLinkedPage = repository.Applications[1].Pages[2];
            var modified      = repository.With(c => c
                                                .Update(field, f => f.Name, "modified field name")
                                                .Update(field, f => f.Content, FieldContent.NewLink(new FieldLinkContent(new LazyLink <Page>(container, newLinkedPage))))
                                                .Update(page, p => p.Name, "modified page name"));

            container.Commit(modified.Repository, signature, message);

            // Assert
            Assert.That(lastEvent, Is.Not.Null);
            Assert.That(lastEvent.Changes, Has.Count.EqualTo(2));
        }
コード例 #22
0
 /// <summary>
 /// Code used to display the field value in the DisplayForm
 /// </summary>
 /// <param name="output"></param>
 protected override void RenderFieldForDisplay(System.Web.UI.HtmlTextWriter output)
 {
     if (this.ItemFieldValue != null)
     {
         FieldContent picture = new FieldContent(this.ItemFieldValue.ToString());
         output.WriteLine(string.Format("<a href='{0}' target='_blank'><img src='{1}' style='border-width:0px;' /></a>", picture.FullUrl, picture.Thumbnail));
     }
 }
コード例 #23
0
        public void Customize(IFixture fixture)
        {
            fixture.Register(UniqueId.CreateNew);

            var serviceProvider  = fixture.Create <IServiceProvider>();
            var containerFactory = serviceProvider.GetRequiredService <IObjectRepositoryContainerFactory>();

            var path = ContainerPath ?? RepositoryFixture.GetAvailableFolderPath();

            fixture.Customizations.Add(new ObjectRepositoryContainerSpecimenBuilder(path));
            var container = fixture.Freeze <IObjectRepositoryContainer <ObjectRepository> >();

            ObjectRepository lastRepository = default;
            var createdPages = new List <Page>();

            Page CreatePage(int position)
            {
                var page = new Page.Builder(serviceProvider)
                {
                    Id          = UniqueId.CreateNew(),
                    Name        = $"Page {position}",
                    Description = $"Description for {position}",
                    Fields      = new LazyChildren <Field>(
                        Enumerable.Range(1, FieldPerPageCount).Select(f =>
                                                                      CreateField(f))
                        .OrderBy(f => f.Id).ToImmutableList())
                }.ToImmutable();

                createdPages.Add(page);
                return(page);
            }

            Field CreateField(int position) =>
            new Field.Builder(serviceProvider)
            {
                Id      = UniqueId.CreateNew(),
                Name    = $"Field {position}",
                Content = createdPages.Any() && position % 3 == 0 ?
                          FieldContent.NewLink(new FieldLinkContent(new LazyLink <Page>(container, PickRandomPage(_ => true)))) :
                          FieldContent.Default
            }.ToImmutable();

            ObjectRepository CreateModule()
            {
                createdPages.Clear();
                lastRepository = new ObjectRepository(serviceProvider, container,
                                                      UniqueId.CreateNew(),
                                                      "Some repository",
                                                      new Version(1, 0, 0),
                                                      ImmutableList.Create <RepositoryDependency>(),
                                                      new LazyChildren <IMigration>(),
                                                      new LazyChildren <IObjectRepositoryIndex>(
                                                          ImmutableList.Create <IObjectRepositoryIndex>(new LinkFieldReferrerIndex(serviceProvider, UniqueId.CreateNew(), nameof(LinkFieldReferrerIndex)))),
                                                      new LazyChildren <Application>(
                                                          Enumerable.Range(1, ApplicationCount).Select(a =>
                                                                                                       new Application(serviceProvider, UniqueId.CreateNew(), $"Application {a}", new LazyChildren <Page>(
                                                                                                                           Enumerable.Range(1, PagePerApplicationCount).Select(p =>
                                                                                                                                                                               CreatePage(p))
                                                                                                                           .OrderBy(p => p.Id).ToImmutableList())))
                                                          .OrderBy(a => a.Id).ToImmutableList()));
                return(lastRepository);
            }

            Application PickRandomApplication() => (lastRepository ?? CreateModule()).Applications.PickRandom();
            Page PickRandomPage(Func <Page, bool> predicate) =>
            !createdPages.Any() ?
            PickRandomApplication().Pages.Last(predicate) :
            createdPages.Last(predicate);
            Field PickRandomField() => PickRandomPage(_ => true).Fields.PickRandom();

            fixture.Register(PickRandomApplication);
            fixture.Register(() => PickRandomPage(_ => true));
            fixture.Register(PickRandomField);
            fixture.Register(CreateModule);
        }