content
stringlengths
23
1.05M
namespace MessageBoard.Backend.Services.Sorting { using System; using System.Collections.Generic; using System.Linq; public static class PropertySorter<TSource> { public static IPropertySorter<TSource> For<TKey> ( Func<TSource, TKey> propertySelector ) => new PropertySorter<TSource, TKey>(propertySelector); } public class PropertySorter<TSource, TKey> : IPropertySorter<TSource> { private readonly Func<TSource, TKey> _propertySelector; public PropertySorter ( Func<TSource, TKey> propertySelector ) => _propertySelector = propertySelector ?? throw new ArgumentNullException(nameof(propertySelector)); public IOrderedEnumerable<TSource> Sort ( IEnumerable<TSource> items, SortDirection direction ) => direction == SortDirection.Asc ? items.OrderBy(_propertySelector) : items.OrderByDescending(_propertySelector); public IOrderedEnumerable<TSource> FineSort ( IOrderedEnumerable<TSource> items, SortDirection direction ) => direction == SortDirection.Asc ? items.ThenBy(_propertySelector) : items.ThenByDescending(_propertySelector); } }
using AppDynamics.Dexter.ReportObjects; using CsvHelper.Configuration; namespace AppDynamics.Dexter.ReportObjectMaps { public class MethodCallLineReportMap : ClassMap<MethodCallLine> { public MethodCallLineReportMap() { int i = 0; Map(m => m.Controller).Index(i); i++; Map(m => m.ApplicationName).Index(i); i++; Map(m => m.TierName).Index(i); i++; Map(m => m.TierType).Index(i); i++; Map(m => m.NodeName).Index(i); i++; Map(m => m.AgentType).Index(i); i++; Map(m => m.BTName).Index(i); i++; Map(m => m.BTType).Index(i); i++; Map(m => m.SegmentUserExperience).Index(i); i++; Map(m => m.SnapshotUserExperience).Index(i); i++; Map(m => m.RequestID).Index(i); i++; Map(m => m.SegmentID).Index(i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.Occurred), i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.OccurredUtc), i); i++; Map(m => m.Type).Index(i); i++; Map(m => m.Framework).Index(i); i++; Map(m => m.FullNameIndent).Index(i); i++; Map(m => m.Exec).Index(i); i++; Map(m => m.ExecTotal).Index(i); i++; Map(m => m.ExecToHere).Index(i); i++; Map(m => m.Wait).Index(i); i++; Map(m => m.WaitTotal).Index(i); i++; Map(m => m.Block).Index(i); i++; Map(m => m.BlockTotal).Index(i); i++; Map(m => m.CPU).Index(i); i++; Map(m => m.CPUTotal).Index(i); i++; Map(m => m.ExecRange).Index(i); i++; Map(m => m.ExitCalls).Index(i); i++; Map(m => m.NumExits).Index(i); i++; Map(m => m.HasErrors).Index(i); i++; Map(m => m.SEPs).Index(i); i++; Map(m => m.NumSEPs).Index(i); i++; Map(m => m.MIDCs).Index(i); i++; Map(m => m.NumMIDCs).Index(i); i++; Map(m => m.NumChildren).Index(i); i++; Map(m => m.ElementType).Index(i); i++; Map(m => m.SequenceNumber).Index(i); i++; Map(m => m.Depth).Index(i); i++; Map(m => m.PrettyName).Index(i); i++; Map(m => m.FullName).Index(i); i++; Map(m => m.Class).Index(i); i++; Map(m => m.Method).Index(i); i++; Map(m => m.LineNumber).Index(i); i++; Map(m => m.ApplicationID).Index(i); i++; Map(m => m.TierID).Index(i); i++; Map(m => m.NodeID).Index(i); i++; Map(m => m.BTID).Index(i); i++; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using GovUk.Education.ExploreEducationStatistics.Admin.Services; using GovUk.Education.ExploreEducationStatistics.Admin.Services.Interfaces; using GovUk.Education.ExploreEducationStatistics.Common.Extensions; using GovUk.Education.ExploreEducationStatistics.Common.Model; using GovUk.Education.ExploreEducationStatistics.Common.Services.Interfaces; using GovUk.Education.ExploreEducationStatistics.Common.Services.Interfaces.Security; using GovUk.Education.ExploreEducationStatistics.Common.Tests.Extensions; using GovUk.Education.ExploreEducationStatistics.Common.Tests.Utils; using GovUk.Education.ExploreEducationStatistics.Common.Utils; using GovUk.Education.ExploreEducationStatistics.Content.Model; using GovUk.Education.ExploreEducationStatistics.Content.Model.Database; using GovUk.Education.ExploreEducationStatistics.Content.Model.Extensions; using Microsoft.EntityFrameworkCore; using Moq; using Xunit; using static GovUk.Education.ExploreEducationStatistics.Admin.Tests.Services.DbUtils; using static GovUk.Education.ExploreEducationStatistics.Admin.Validators.ValidationErrorMessages; using static GovUk.Education.ExploreEducationStatistics.Common.BlobContainers; using static GovUk.Education.ExploreEducationStatistics.Common.Model.FileType; using static GovUk.Education.ExploreEducationStatistics.Common.Services.FileStoragePathUtils; using static GovUk.Education.ExploreEducationStatistics.Common.Services.FileStorageUtils; using static GovUk.Education.ExploreEducationStatistics.Common.Tests.Utils.MockFormTestUtils; using File = GovUk.Education.ExploreEducationStatistics.Content.Model.File; namespace GovUk.Education.ExploreEducationStatistics.Admin.Tests.Services { public class ReleaseFileServiceTests { [Fact] public async Task Delete() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var chartFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart } }; var imageFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "image.png", Type = Image } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile, imageFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path())) .Returns(Task.CompletedTask); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, ancillaryFile.File.Id); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path()), Times.Once); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.Null( await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); // Check that other files remain untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(chartFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(chartFile.File.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(imageFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(imageFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_FileFromAmendment() { var release = new Release(); var amendmentRelease = new Release { PreviousVersionId = release.Id }; var ancillaryFile = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary, }; var releaseFile = new ReleaseFile { Release = release, File = ancillaryFile }; var amendmentReleaseFile = new ReleaseFile { Release = amendmentRelease, File = ancillaryFile }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddRangeAsync(release, amendmentRelease); await contentDbContext.AddRangeAsync(ancillaryFile); await contentDbContext.AddRangeAsync(releaseFile, amendmentReleaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(amendmentRelease.Id, ancillaryFile.Id); Assert.True(result.IsRight); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the file is unlinked from the amendment Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(amendmentReleaseFile.Id)); // Check that the file and link to the previous version remain untouched Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(releaseFile.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_InvalidFileType() { var release = new Release(); var dataFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "data.csv", Type = FileType.Data, SubjectId = Guid.NewGuid() } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(dataFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, dataFile.File.Id); Assert.True(result.IsLeft); ValidationTestUtil.AssertValidationProblem(result.Left, FileTypeInvalid); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the file remains untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(dataFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(dataFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_ReleaseNotFound() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(ancillaryFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(Guid.NewGuid(), ancillaryFile.File.Id); result.AssertNotFound(); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the file remains untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_FileNotFound() { var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, Guid.NewGuid()); result.AssertNotFound(); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_MultipleFiles() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var chartFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart } }; var imageFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "image.png", Type = Image } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile, imageFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path())) .Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path())) .Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, imageFile.Path())) .Returns(Task.CompletedTask); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, new List<Guid> { ancillaryFile.File.Id, chartFile.File.Id, imageFile.File.Id }); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path()), Times.Once); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path()), Times.Once); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, imageFile.Path()), Times.Once); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(chartFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(chartFile.File.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(imageFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(imageFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_MultipleFilesWithAnInvalidFileType() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var dataFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "data.csv", Type = FileType.Data, SubjectId = Guid.NewGuid() } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile, dataFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, new List<Guid> { ancillaryFile.File.Id, dataFile.File.Id }); Assert.True(result.IsLeft); ValidationTestUtil.AssertValidationProblem(result.Left, FileTypeInvalid); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that all the files remain untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(dataFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(dataFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_MultipleFilesWithReleaseNotFound() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var chartFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart } }; var imageFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "image.png", Type = Image } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile, imageFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(Guid.NewGuid(), new List<Guid> { ancillaryFile.File.Id, chartFile.File.Id, imageFile.File.Id }); result.AssertNotFound(); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that all the files remain untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(chartFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(chartFile.File.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(imageFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(imageFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_MultipleFilesWithAFileNotFound() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(release.Id, new List<Guid> { ancillaryFile.File.Id, // Include an unknown id Guid.NewGuid() }); result.AssertNotFound(); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the files remain untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Delete_MultipleFilesWithAFileFromAmendment() { var release = new Release(); var amendmentRelease = new Release { PreviousVersionId = release.Id }; var ancillaryFile = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary }; var chartFile = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart }; var ancillaryReleaseFile = new ReleaseFile { Release = release, File = ancillaryFile }; var ancillaryAmendmentReleaseFile = new ReleaseFile { Release = amendmentRelease, File = ancillaryFile }; var chartAmendmentReleaseFile = new ReleaseFile { Release = amendmentRelease, File = chartFile }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddRangeAsync(release, amendmentRelease); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile); await contentDbContext.AddRangeAsync(ancillaryReleaseFile, ancillaryAmendmentReleaseFile, chartAmendmentReleaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path())) .Returns(Task.CompletedTask); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Delete(amendmentRelease.Id, new List<Guid> { ancillaryFile.Id, chartFile.Id }); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path()), Times.Once); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the ancillary file is unlinked from the amendment Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(ancillaryAmendmentReleaseFile.Id)); // Check that the ancillary file and link to the previous version remain untouched Assert.NotNull( await contentDbContext.Files.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryReleaseFile.Id)); // Check that the chart file and link to the amendment are removed Assert.Null(await contentDbContext.Files.FindAsync(chartFile.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(chartAmendmentReleaseFile.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task DeleteAll() { var release = new Release(); var ancillaryFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var chartFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart } }; var dataFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "data.csv", Type = FileType.Data, SubjectId = Guid.NewGuid() } }; var imageFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "image.png", Type = Image } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile, dataFile, imageFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path())) .Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path())) .Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, imageFile.Path())) .Returns(Task.CompletedTask); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.DeleteAll(release.Id); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, ancillaryFile.Path()), Times.Once); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path()), Times.Once); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, imageFile.Path()), Times.Once); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(ancillaryFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(ancillaryFile.File.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(chartFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(chartFile.File.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(imageFile.Id)); Assert.Null(await contentDbContext.Files.FindAsync(imageFile.File.Id)); // Check that data files remain untouched Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(dataFile.Id)); Assert.NotNull(await contentDbContext.Files.FindAsync(dataFile.File.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task DeleteAll_ReleaseNotFound() { var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext()) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.DeleteAll(Guid.NewGuid()); result.AssertNotFound(); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task DeleteAll_NoFiles() { var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.DeleteAll(release.Id); Assert.True(result.IsRight); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task DeleteAll_FileFromAmendment() { var release = new Release(); var amendmentRelease = new Release { PreviousVersionId = release.Id }; var ancillaryFile = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary }; var chartFile = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart }; var ancillaryReleaseFile = new ReleaseFile { Release = release, File = ancillaryFile }; var ancillaryAmendmentReleaseFile = new ReleaseFile { Release = amendmentRelease, File = ancillaryFile }; var chartAmendmentReleaseFile = new ReleaseFile { Release = amendmentRelease, File = chartFile }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddRangeAsync(release, amendmentRelease); await contentDbContext.AddRangeAsync(ancillaryFile, chartFile); await contentDbContext.AddRangeAsync(ancillaryReleaseFile, ancillaryAmendmentReleaseFile, chartAmendmentReleaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path())) .Returns(Task.CompletedTask); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.DeleteAll(amendmentRelease.Id); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.DeleteBlob(PrivateReleaseFiles, chartFile.Path()), Times.Once); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { // Check that the ancillary file is unlinked from the amendment Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(ancillaryAmendmentReleaseFile.Id)); // Check that the ancillary file and link to the previous version remain untouched Assert.NotNull(await contentDbContext.Files.FindAsync(ancillaryFile.Id)); Assert.NotNull(await contentDbContext.ReleaseFiles.FindAsync(ancillaryReleaseFile.Id)); // Check that the chart file and link to the amendment are removed Assert.Null(await contentDbContext.Files.FindAsync(chartFile.Id)); Assert.Null(await contentDbContext.ReleaseFiles.FindAsync(chartAmendmentReleaseFile.Id)); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task ListAll_NoFiles() { var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.ListAll(release.Id, Ancillary, Chart); Assert.True(result.IsRight); Assert.Empty(result.Right); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task ListAll_ReleaseNotFound() { var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext()) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.ListAll(Guid.NewGuid(), Ancillary, Chart); result.AssertNotFound(); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task ListAll() { var release = new Release(); var ancillaryFile1 = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary_1.pdf", Type = Ancillary } }; var ancillaryFile2 = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "Ancillary 2.pdf", Type = Ancillary } }; var chartFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "chart.png", Type = Chart } }; var dataFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "data.csv", Type = FileType.Data, SubjectId = Guid.NewGuid() } }; var imageFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "image.png", Type = Image } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddRangeAsync(ancillaryFile1, ancillaryFile2, chartFile, dataFile, imageFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.CheckBlobExists(PrivateReleaseFiles, It.IsIn( ancillaryFile1.Path(), ancillaryFile2.Path(), chartFile.Path(), imageFile.Path()))) .ReturnsAsync(true); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, ancillaryFile1.Path())) .ReturnsAsync(new BlobInfo( path: ancillaryFile1.Path(), size: "10 Kb", contentType: "application/pdf", contentLength: 0L, meta: GetAncillaryFileMetaValues( name: "Ancillary Test File 1"), created: null)); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, ancillaryFile2.Path())) .ReturnsAsync(new BlobInfo( path: ancillaryFile2.Path(), size: "10 Kb", contentType: "application/pdf", contentLength: 0L, meta: GetAncillaryFileMetaValues( name: "Ancillary Test File 2"), created: null)); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, chartFile.Path())) .ReturnsAsync(new BlobInfo( path: chartFile.Path(), size: "20 Kb", contentType: "image/png", contentLength: 0L, meta: new Dictionary<string, string>(), created: null)); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, imageFile.Path())) .ReturnsAsync(new BlobInfo( path: imageFile.Path(), size: "30 Kb", contentType: "image/png", contentLength: 0L, meta: new Dictionary<string, string>(), created: null)); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.ListAll(release.Id, Ancillary, Chart, Image); Assert.True(result.IsRight); blobStorageService.Verify(mock => mock.CheckBlobExists(PrivateReleaseFiles, It.IsIn( ancillaryFile1.Path(), ancillaryFile2.Path(), chartFile.Path(), imageFile.Path())), Times.Exactly(4)); blobStorageService.Verify(mock => mock.GetBlob(PrivateReleaseFiles, It.IsIn( ancillaryFile1.Path(), ancillaryFile2.Path(), chartFile.Path(), imageFile.Path())), Times.Exactly(4)); var fileInfoList = result.Right.ToList(); Assert.Equal(4, fileInfoList.Count); Assert.Equal(ancillaryFile1.File.Id, fileInfoList[0].Id); Assert.Equal("pdf", fileInfoList[0].Extension); Assert.Equal("ancillary_1.pdf", fileInfoList[0].FileName); Assert.Equal("Ancillary Test File 1", fileInfoList[0].Name); Assert.Equal(ancillaryFile1.Path(), fileInfoList[0].Path); Assert.Equal("10 Kb", fileInfoList[0].Size); Assert.Equal(Ancillary, fileInfoList[0].Type); Assert.Equal(ancillaryFile2.File.Id, fileInfoList[1].Id); Assert.Equal("pdf", fileInfoList[1].Extension); Assert.Equal("Ancillary 2.pdf", fileInfoList[1].FileName); Assert.Equal("Ancillary Test File 2", fileInfoList[1].Name); Assert.Equal(ancillaryFile2.Path(), fileInfoList[1].Path); Assert.Equal("10 Kb", fileInfoList[1].Size); Assert.Equal(Ancillary, fileInfoList[1].Type); Assert.Equal(chartFile.File.Id, fileInfoList[2].Id); Assert.Equal("png", fileInfoList[2].Extension); Assert.Equal("chart.png", fileInfoList[2].FileName); Assert.Equal("chart.png", fileInfoList[2].Name); Assert.Equal(chartFile.Path(), fileInfoList[2].Path); Assert.Equal("20 Kb", fileInfoList[2].Size); Assert.Equal(Chart, fileInfoList[2].Type); Assert.Equal(imageFile.File.Id, fileInfoList[3].Id); Assert.Equal("png", fileInfoList[3].Extension); Assert.Equal("image.png", fileInfoList[3].FileName); Assert.Equal("image.png", fileInfoList[3].Name); Assert.Equal(imageFile.Path(), fileInfoList[3].Path); Assert.Equal("30 Kb", fileInfoList[3].Size); Assert.Equal(Image, fileInfoList[3].Type); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Stream() { var release = new Release(); var releaseFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(releaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); var blob = new BlobInfo( path: null, size: null, contentType: "application/pdf", contentLength: 0L, meta: null, created: null); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, releaseFile.Path())) .ReturnsAsync(blob); blobStorageService.Setup(mock => mock.DownloadToStream(PrivateReleaseFiles, releaseFile.Path(), It.IsAny<MemoryStream>())) .ReturnsAsync(new MemoryStream()); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Stream(release.Id, releaseFile.File.Id); Assert.True(result.IsRight); blobStorageService.Verify( mock => mock.GetBlob(PrivateReleaseFiles, releaseFile.Path()), Times.Once()); blobStorageService.Verify( mock => mock.DownloadToStream(PrivateReleaseFiles, releaseFile.Path(), It.IsAny<MemoryStream>()), Times.Once()); Assert.Equal("application/pdf", result.Right.ContentType); Assert.Equal("ancillary.pdf", result.Right.FileDownloadName); Assert.IsType<MemoryStream>(result.Right.FileStream); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Stream_MixedCaseFilename() { var release = new Release(); var releaseFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "Ancillary 1.pdf", Type = Ancillary } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(releaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); var blob = new BlobInfo( path: null, size: null, contentType: "application/pdf", contentLength: 0L, meta: null, created: null); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, releaseFile.Path())) .ReturnsAsync(blob); blobStorageService.Setup(mock => mock.DownloadToStream(PrivateReleaseFiles, releaseFile.Path(), It.IsAny<MemoryStream>())) .ReturnsAsync(new MemoryStream()); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Stream(release.Id, releaseFile.File.Id); Assert.True(result.IsRight); blobStorageService.Verify( mock => mock.GetBlob(PrivateReleaseFiles, releaseFile.Path()), Times.Once()); blobStorageService.Verify( mock => mock.DownloadToStream(PrivateReleaseFiles, releaseFile.Path(), It.IsAny<MemoryStream>()), Times.Once()); Assert.Equal("application/pdf", result.Right.ContentType); Assert.Equal("Ancillary 1.pdf", result.Right.FileDownloadName); Assert.IsType<MemoryStream>(result.Right.FileStream); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Stream_ReleaseNotFound() { var release = new Release(); var releaseFile = new ReleaseFile { Release = release, File = new File { RootPath = Guid.NewGuid(), Filename = "ancillary.pdf", Type = Ancillary } }; var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.AddAsync(releaseFile); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext()) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Stream(Guid.NewGuid(), releaseFile.File.Id); result.AssertNotFound(); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task Stream_FileNotFound() { var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); await using (var contentDbContext = InMemoryApplicationDbContext()) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object); var result = await service.Stream(release.Id, Guid.NewGuid()); result.AssertNotFound(); } MockUtils.VerifyAllMocks(blobStorageService); } [Fact] public async Task UploadAncillary() { const string filename = "ancillary.pdf"; const string uploadName = "Ancillary Test File"; var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var formFile = CreateFormFileMock(filename).Object; var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); var fileUploadsValidatorService = new Mock<IFileUploadsValidatorService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.UploadFile(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Ancillary))), formFile, It.Is<IDictionary<string, string>>(metadata => metadata[BlobInfoExtensions.NameKey] == uploadName) )).Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Ancillary))))) .ReturnsAsync(new BlobInfo( path: "ancillary/file/path", size: "10 Kb", contentType: "application/pdf", contentLength: 0L, meta: GetAncillaryFileMetaValues( name: uploadName), created: null)); fileUploadsValidatorService.Setup(mock => mock.ValidateFileForUpload(formFile, Ancillary)) .ReturnsAsync(Unit.Instance); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object, fileUploadsValidatorService: fileUploadsValidatorService.Object); var result = await service.UploadAncillary(release.Id, formFile, uploadName); Assert.True(result.IsRight); fileUploadsValidatorService.Verify(mock => mock.ValidateFileForUpload(formFile, Ancillary), Times.Once); blobStorageService.Verify(mock => mock.UploadFile(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Ancillary))), formFile, It.Is<IDictionary<string, string>>(metadata => metadata[BlobInfoExtensions.NameKey] == uploadName) ), Times.Once); blobStorageService.Verify(mock => mock.GetBlob(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Ancillary)))), Times.Once); Assert.True(result.Right.Id.HasValue); Assert.Equal("pdf", result.Right.Extension); Assert.Equal("ancillary.pdf", result.Right.FileName); Assert.Equal("Ancillary Test File", result.Right.Name); Assert.Contains(FilesPath(release.Id, Ancillary), result.Right.Path); Assert.Equal("10 Kb", result.Right.Size); Assert.Equal(Ancillary, result.Right.Type); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var releaseFile = await contentDbContext.ReleaseFiles .Include(rf => rf.File) .SingleOrDefaultAsync(rf => rf.ReleaseId == release.Id && rf.File.Filename == filename && rf.File.Type == Ancillary ); Assert.NotNull(releaseFile); } MockUtils.VerifyAllMocks(blobStorageService, fileUploadsValidatorService); } [Fact] public async Task UploadChart() { const string filename = "chart.png"; var release = new Release(); var contentDbContextId = Guid.NewGuid().ToString(); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { await contentDbContext.AddAsync(release); await contentDbContext.SaveChangesAsync(); } var formFile = CreateFormFileMock(filename).Object; var blobStorageService = new Mock<IBlobStorageService>(MockBehavior.Strict); var fileUploadsValidatorService = new Mock<IFileUploadsValidatorService>(MockBehavior.Strict); blobStorageService.Setup(mock => mock.UploadFile(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Chart))), formFile, null )).Returns(Task.CompletedTask); blobStorageService.Setup(mock => mock.GetBlob(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Chart))))) .ReturnsAsync(new BlobInfo( path: "chart/file/path", size: "20 Kb", contentType: "image/png", contentLength: 0L, meta: new Dictionary<string, string>(), created: null)); fileUploadsValidatorService.Setup(mock => mock.ValidateFileForUpload(formFile, Chart)) .ReturnsAsync(Unit.Instance); await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var service = SetupReleaseFileService(contentDbContext: contentDbContext, blobStorageService: blobStorageService.Object, fileUploadsValidatorService: fileUploadsValidatorService.Object); var result = await service.UploadChart(release.Id, formFile); Assert.True(result.IsRight); fileUploadsValidatorService.Verify(mock => mock.ValidateFileForUpload(formFile, Chart), Times.Once); blobStorageService.Verify(mock => mock.UploadFile(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Chart))), formFile, null ), Times.Once); blobStorageService.Verify(mock => mock.GetBlob(PrivateReleaseFiles, It.Is<string>(path => path.Contains(FilesPath(release.Id, Chart)))), Times.Once); Assert.True(result.Right.Id.HasValue); Assert.Equal("png", result.Right.Extension); Assert.Equal("chart.png", result.Right.FileName); Assert.Equal("chart.png", result.Right.Name); Assert.Contains(FilesPath(release.Id, Chart), result.Right.Path); Assert.Equal("20 Kb", result.Right.Size); Assert.Equal(Chart, result.Right.Type); } await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId)) { var releaseFile = await contentDbContext.ReleaseFiles .Include(rf => rf.File) .SingleOrDefaultAsync(rf => rf.ReleaseId == release.Id && rf.File.Filename == filename && rf.File.Type == Chart ); Assert.NotNull(releaseFile); } MockUtils.VerifyAllMocks(blobStorageService, fileUploadsValidatorService); } private static ReleaseFileService SetupReleaseFileService( ContentDbContext contentDbContext, IPersistenceHelper<ContentDbContext> contentPersistenceHelper = null, IBlobStorageService blobStorageService = null, IFileRepository fileRepository = null, IFileUploadsValidatorService fileUploadsValidatorService = null, IReleaseFileRepository releaseFileRepository = null, IUserService userService = null) { return new ReleaseFileService( contentDbContext ?? new Mock<ContentDbContext>().Object, contentPersistenceHelper ?? new PersistenceHelper<ContentDbContext>(contentDbContext), blobStorageService ?? new Mock<IBlobStorageService>().Object, fileRepository ?? new FileRepository(contentDbContext), fileUploadsValidatorService ?? new Mock<IFileUploadsValidatorService>().Object, releaseFileRepository ?? new ReleaseFileRepository(contentDbContext), userService ?? MockUtils.AlwaysTrueUserService().Object ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; //|5|1|a|s|p|x namespace WpfPagesApp { /// <summary> /// PageBar.xaml 的交互逻辑 /// </summary> public partial class PageBar : UserControl { //圆点直径 readonly int ellipse_Diameter = 8; //圆点间距 readonly int ellipse_Peripheral = 6; //圆点列表 readonly List<Ellipse> ellipseList = new List<Ellipse>(); public PageBar() { InitializeComponent(); } public void CreatePageEllipse(int pagecout) { canvas1.Children.Clear(); ellipseList.Clear(); //设置控件长度 canvas1.Width = this.Width = ellipse_Peripheral + (ellipse_Diameter + ellipse_Peripheral) * pagecout; //画点 for (int i = 1; i <= pagecout; i++) { Ellipse ellipse = new Ellipse(); ellipse.Width = ellipse.Height = ellipse_Diameter; ellipse.StrokeThickness = 0; ellipse.Fill = new SolidColorBrush(Colors.Gray); Canvas.SetLeft(ellipse, ellipse_Peripheral * i + ellipse_Diameter * (i - 1)); Canvas.SetTop(ellipse, 1); canvas1.Children.Add(ellipse); ellipseList.Add(ellipse); } } public void SelectPage(int pageselect) { if (ellipseList.Count >= pageselect) { for (int i = 0; i < ellipseList.Count; i++) { if (i == pageselect - 1) ellipseList[i].Fill = new SolidColorBrush(Colors.Lime); else ellipseList[i].Fill = new SolidColorBrush(Colors.Gray); } } } } }
using System; using Microsoft.Xna.Framework; namespace BananaTheGame.Terrain.Generators { public class TestTerrainGenerator : IChunkGenerator { public void Generate(Chunk chunk) { //generate(chunk); testGroundGen(chunk); } private void testGroundGen(Chunk chunk) { for (byte x = 0; x < Chunk.SIZE; x++) { for (byte y = 0; y < Chunk.SIZE; y++) { Tile tile = new Tile(TileType.Grass, new Vector2Int(x, y)); chunk.Add(tile); } } } } }
using System.Threading.Tasks; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { public class DerivedServiceType : ServiceType, IDerivedServiceType { public Task<string> DerivedServiceTypeMethod1() { return Task.FromResult("DerivedServiceTypeMethod1"); } public Task<string> H1Method() { return Task.FromResult("H1"); } public Task<string> H2Method() { return Task.FromResult("H2"); } public Task<string> H3Method() { return Task.FromResult("H3"); } } }
using System; namespace MIP.SharePoint.API.Model.Attributes { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class SPFieldAttribute : Attribute { public string Name { get; } public Type Type { get; } public SPFieldAttribute(string name) : this(name, null) { } public SPFieldAttribute(string name, Type type) { this.Name = name; this.Type = type; } } }
using System; using System.Collections.Generic; using System.Linq; using Funcky.Extensions; using Funcky.Test.TestUtils; using Xunit; using Xunit.Sdk; namespace Funcky.Test.Extensions.EnumerableExtensions { public class ForEachTest { [Fact] public void ForEachIsEvaluatedEagerly() { var doNotEnumerate = new FailOnEnumerateSequence<object>(); Assert.Throws<XunitException>(() => doNotEnumerate.ForEach(Functional.NoOperation)); Assert.Throws<XunitException>(() => doNotEnumerate.ForEach(UnitNoOperation)); } [Fact] public void ForEachOnAnEmptyListCallsNothing() { Enumerable .Empty<int>() .ForEach(ActionWithException); Enumerable .Empty<int>() .ForEach(UnitActionWithException); } [Fact] public void ForEachExecutesTheActionNTimesWithCorrectValues() { var state = new List<int>(); Enumerable .Range(0, 42) .ForEach(state.Add); Assert.Equal(Enumerable.Range(0, 42), state); } [Fact] public void ForEachWithUnitActionExecutesTheActionNTimesWithCorrectValues() { var state = new List<int>(); Enumerable .Range(0, 42) .ForEach(UnitAdd(state)); Assert.Equal(Enumerable.Range(0, 42), state); } private static void ActionWithException(int i) => throw new XunitException("Should not execute"); private static Unit UnitActionWithException(int i) => throw new XunitException("Should not execute"); private static Func<int, Unit> UnitAdd(ICollection<int> state) => i => { state.Add(i); return Unit.Value; }; private static Unit UnitNoOperation<T>(T value) => Unit.Value; } }
using Microsoft.AspNetCore.Http; namespace SIL.XForge.Services { public class HttpRequestAccessor : IHttpRequestAccessor { private readonly IHttpContextAccessor _httpContextAccessor; public HttpRequestAccessor(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public PathString Path => _httpContextAccessor.HttpContext.Request.Path; public HostString Host => _httpContextAccessor.HttpContext.Request.Host; } }
using UnityEngine; // ReSharper disable once CheckNamespace namespace STRV.Variables.Persistance { public abstract class ValueSerializer: ScriptableObject { /// Loads data from local storage into the given target public abstract bool Load(ISerializable target); /// Saves the current local cache into the persistent storage public abstract bool Save(ISerializable value); } }
using Exchange.Rates.Ecb.Polling.Api.Options; using GreenPipes; using MassTransit; using MassTransit.ConsumeConfigurators; using MassTransit.Definition; using Microsoft.Extensions.Options; namespace Exchange.Rates.Ecb.Polling.Api.Consumers.Definitions { // Consumer definitions can be explicitely registered or discovered automatically using the AddConsumers public class SubmitExchangeRateSymbolsDefinition : ConsumerDefinition<SubmitExchangeRateSymbolsConsumer> { public SubmitExchangeRateSymbolsDefinition(IOptions<MassTransitOptions> options) { // Override the default endpoint name, for whatever reason EndpointName = options.Value.QueueName; // Limit the number of messages consumed concurrently // this applies to the consumer only, not the endpoint ConcurrentMessageLimit = 16; } protected override void ConfigureConsumer(IReceiveEndpointConfigurator endpointConfigurator, IConsumerConfigurator<SubmitExchangeRateSymbolsConsumer> consumerConfigurator) { endpointConfigurator.UseMessageRetry(r => r.Interval(5, 1000)); endpointConfigurator.UseInMemoryOutbox(); } } }
namespace LibClang.Intertop { /// <summary> /// Defines the <see cref="CXPlatformAvailability" /> /// </summary> public struct CXPlatformAvailability { /// <summary> /// Defines the Platform /// </summary> public CXString Platform; /// <summary> /// Defines the Introduced /// </summary> public CXVersion Introduced; /// <summary> /// Defines the Deprecated /// </summary> public CXVersion Deprecated; /// <summary> /// Defines the Obsoleted /// </summary> public CXVersion Obsoleted; /// <summary> /// Defines the Unavailable /// </summary> public int Unavailable; /// <summary> /// Defines the Message /// </summary> public CXString Message; } }
using DiffWit.Utils; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using System; namespace DiffWit { public partial class App : Application { private Window _currentWindow; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { _currentWindow = new MainWindow(); _currentWindow.Activate(); } //protected override void OnActivated(IActivatedEventArgs args) //{ // switch (args.Kind) // { // case ActivationKind.CommandLineLaunch: // { // var cmdLineArgs = args as CommandLineActivatedEventArgs; // var operation = cmdLineArgs.Operation; // HandleCommandLineActivation(operation.Arguments, operation.CurrentDirectoryPath); // } // break; // default: // break; // } //} //private void HandleCommandLineActivation(string arguments, string currentDirectory) //{ // Frame rootFrame = Window.Current.Content as Frame; // if (rootFrame == null) // { // rootFrame = new Frame(); // Window.Current.Content = rootFrame; // } // // var parsedCommands = CommandLineParser.ParseUntrustedArgs(arguments); // if (parsedCommands != null && parsedCommands.Count > 0) // { // rootFrame.Navigate(typeof(MainPage), parsedCommands); // } // else // { // rootFrame.Navigate(typeof(MainPage)); // } // // Window.Current.Activate(); //} } }
using BL.Rentas; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Win.Rentas { public partial class RegistrarVuelo : Form { RegistrarVueloBL _vuelos; public RegistrarVuelo() { InitializeComponent(); _vuelos = new RegistrarVueloBL(); listaRegistroVueloBindingSource.DataSource = _vuelos.ObtenerRegistroVuelo(); } private void listaRegistroVueloDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { } } }
using System; namespace UnrealEngine { public partial class UPlatformEventsComponent:UActorComponent { /// <summary> /// Check whether the platform supports convertible laptops. /// Note: This does not necessarily mean that the platform is a convertible laptop. /// For example, convertible laptops running Windows 7 or older will return false, /// and regular laptops running Windows 8 or newer will return true. /// @return true for convertible laptop platforms, false otherwise. /// @see IsInLaptopMode, IsInTabletMode /// </summary> public extern bool SupportsConvertibleLaptops(); /// <summary> /// Check whether a convertible laptop is laptop mode. /// @return true if in tablet mode, false otherwise or if not a convertible laptop. /// @see IsInLaptopMode, SupportsConvertibleLaptops /// </summary> public extern bool IsInTabletMode(); /// <summary> /// Check whether a convertible laptop is laptop mode. /// @return true if in laptop mode, false otherwise or if not a convertible laptop. /// @see IsInTabletMode, SupportsConvertibleLaptops /// </summary> public extern bool IsInLaptopMode(); } }
using System; using System.Globalization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SpeedTest; namespace SpeedTestLogger { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services, IHostEnvironment environment) { var singleRun = bool.Parse(Configuration["singleRun"]); var userId = Configuration["userId"]; var loggerId = Int32.Parse(Configuration["loggerId"]); var uploadResults = bool.Parse(Configuration["uploadResults"]); services.AddTransient<LoggerHostConfiguration>(provider => new LoggerHostConfiguration { SingleRun = singleRun, UserId = userId, LoggerId = loggerId, UploadResults = uploadResults, }); var apiUrl = new Uri(Configuration["speedTestApiUrl"]); services.AddTransient<SpeedTestApiClient>(provider => new SpeedTestApiClient(apiUrl)); var kubeMQAddress = Configuration["KubeMQ_ServerAddress"]; var kubeMQChannel = Configuration["KubeMQ_Channel"]; services.AddTransient<KubeMQClient>(provider => new KubeMQClient(kubeMQAddress, loggerId, kubeMQChannel)); var useDummyData = Configuration.GetValue<bool>("useDummyData"); var loggerLocation = new RegionInfo(Configuration["loggerLocationCountryCode"]); services.AddTransient<SpeedTestRunner>(provider => new SpeedTestRunner( new SpeedTestClient(), loggerLocation, useDummyData)); services.AddHostedService<LoggerHost>(); } } }
using System.Threading.Tasks; namespace PlantHunter.Mobile.Core.Services.Chart { public interface IChartService { Task<Microcharts.Chart> GetTemperatureChartAsync(); Task<Microcharts.Chart> GetGreenChartAsync(); } }
using Orchard.Data.Migration; using Orchard.ContentManagement.MetaData; using Orchard.Core.Contents.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Laser.Orchard.PaymentGateway.Models; namespace Laser.Orchard.PaymentGateway { public class PaymentMigrations : DataMigrationImpl { public int Create() { SchemaBuilder.CreateTable("PaymentRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<string>("PosName") .Column<string>("Reason") .Column<DateTime>("CreationDate") .Column<DateTime>("UpdateDate") .Column<string>("PosUrl") .Column<decimal>("Amount") .Column<string>("Currency") .Column<bool>("Success") .Column<string>("Error") .Column<string>("TransactionId") .Column<string>("ReturnUrl") .Column("Info", System.Data.DbType.String, x => x.Unlimited()) .Column<int>("ContentItemId") ); return 1; } public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition( typeof(PayButtonPart).Name, p => p.Attachable() ); return 2; } public int UpdateFrom2() { SchemaBuilder.AlterTable("PaymentRecord", table => table.DropColumn("ReturnUrl")); return 3; } public int UpdateFrom3() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AlterColumn("PosUrl", col => col.WithType(System.Data.DbType.String).Unlimited())); return 4; } public int UpdateFrom4() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("UserId", System.Data.DbType.Int32)); return 5; } public int UpdateFrom5() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("CustomRedirectUrl", System.Data.DbType.String, x => x.Unlimited())); SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("CustomRedirectSchema", System.Data.DbType.String, x => x.Unlimited())); return 6; } public int UpdateFrom6() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn<bool>("PaymentTransactionComplete") ); return 7; } public int UpdateFrom7() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("Guid", System.Data.DbType.String, x => x.Unlimited())); return 8; } public int UpdateFrom8() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("APIFilters", System.Data.DbType.String, x => x.Unlimited())); return 9; } public int UpdateFrom9() { SchemaBuilder.AlterTable("PaymentRecord", table => table.AddColumn("PaymentUniqueKey", System.Data.DbType.String)); return 10; } } }
using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Certes { public partial class AcmeContextIntegration { public class CertificateWithES256Tests : AcmeContextIntegration { public CertificateWithES256Tests(ITestOutputHelper output) : base(output) { } [Fact] public Task CanGenerateCertificateWithEC256() => CanGenerateCertificateWithEC(KeyAlgorithm.ES256); } } }
using System; using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using OpenRasta.Hosting.AspNetCore; using Tests.Infrastructure; using Xunit; namespace Tests.Hosting.Owin { public class hosting_on_asp_net_core_in_map : IDisposable { readonly HttpClient client; readonly TestServer server; public hosting_on_asp_net_core_in_map() { server = new TestServer( new WebHostBuilder() .Configure(app => app.Map("/api", api => api.UseOpenRasta(new TaskApi())))); client = server.CreateClient(); } [Fact] public async void can_get_list_of_tasks() { var response = await client.GetAsync("api/tasks"); response.EnsureSuccessStatusCode(); } public void Dispose() { server?.Dispose(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Tobii.G2OM; using Tobii.XR; using UnityEngine.Events; [System.Serializable] public class GazeEvent : UnityEvent<float, string> { } public class GazeFocus : MonoBehaviour, IGazeFocusable { [SerializeField] UnityEvent m_GazeActivedEvent; [SerializeField] UnityEvent m_GazeDeactivedEvent; public void GazeFocusChanged(bool hasFocus) { // if hasFocus is true; create a unity event // start unity event if (hasFocus) { Debug.Log("Gaze Focus Changed to true"); m_GazeActivedEvent?.Invoke(); } else { Debug.Log("Gaze Focus Changed to false"); m_GazeDeactivedEvent?.Invoke(); } // if has focus becomes false, start coroutine for countdown to start another unity event } }
using FluentAssertions; using PhotoBlogger.Constants; using Xunit; namespace PhotoBlogger.Tests.Constants { public class ViewKeyTests { [Fact] public void Title_ShouldBeTitle() { ViewKey.Title.Should().Be("Title"); } } }
using AutoMapper; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Moq; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Test.Core; using Test.Domain; using Test.Domain.Entity; using Test.Domain.Extend; using Test.Service.Dto; using Test.Service.Impl; using Test.Service.Infrastructure; using Test.Service.Interface; using Test.Service.QueryModel; using Xunit; namespace Test.XUnitTest { public class TestUnitTest : BaseUnitTest { Mock<DbSet<ArticleType>> _mockSet { get; set; } Mock<TestDBContext> _mockContext { get; set; } IArticleTypeSvc _mockSvc { get; set; } public TestUnitTest() : base() { _serviceCollection.AddScoped<IDbContextExtendSvc, DbContextExtendSvc>(); BuilderServiceProvider(); var mapper = _serviceProvider.GetService<IMapper>(); var dbContextExtendSvc = _serviceProvider.GetService<IDbContextExtendSvc>(); var list = new List<ArticleType>() { new ArticleType(){ Id=1,Name="1",EditerName="123",CreateTime=DateTime.Now}, new ArticleType(){ Id=1,Name="2",EditerName="223",CreateTime=DateTime.Now}, }; _mockSet = new Mock<DbSet<ArticleType>>().SetupList(list); _mockContext = new Mock<TestDBContext>(); _mockContext.Setup(x => x.ArticleType).Returns(_mockSet.Object); _mockSvc = new ArticleTypeSvc(mapper, _mockContext.Object, dbContextExtendSvc); } [Fact] public void AddSingleTest() { var data = new ArticleTypeDto() { Name = "251", EditerName = "test", CreateTime = DateTime.Now }; _mockSvc.AddSingle(data); _mockContext.Verify(x => x.Add(It.IsAny<ArticleType>()), Times.Once()); _mockContext.Verify(x => x.SaveChanges(), Times.Once()); } [Fact] public async Task GetPageDatasAsyncTest() { var result= await _mockSvc.GetPageDatasAsync(new ArticleTypeQueryModel() { OrderByColumn="CreateTime"}); Assert.Equal(2, result.Count); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using NISOCountries.Core; namespace NISOCountries.Tests { [TestClass] public class ISOCountryLookupTests { [TestMethod] public void ISOCountryLookup_AutoDetectCode_WorksForAllCombinations() { var target = new ISOCountryLookup<TestCountry>(new TestCountryReader().GetDefault()); TestCountry result; Assert.IsTrue(target.TryGet("TC", out result)); Assert.AreEqual("TestCountry", result.CountryName); Assert.IsTrue(target.TryGet("TST", out result)); Assert.AreEqual("TestCountry", result.CountryName); Assert.IsTrue(target.TryGet("001", out result)); Assert.AreEqual("TestCountry", result.CountryName); Assert.IsFalse(target.TryGet("XX", out result)); Assert.IsFalse(target.TryGet("XXX", out result)); Assert.IsFalse(target.TryGet("999", out result)); } [TestMethod] public void ISOCountryLookup_AutoDetectCode_IsNotCaseSensitive() { var target = new ISOCountryLookup<TestCountry>(new TestCountryReader().GetDefault(), true); TestCountry result; Assert.IsTrue(target.TryGet("TC", out result)); Assert.IsTrue(target.TryGet("tc", out result)); Assert.IsTrue(target.TryGet("Tc", out result)); Assert.IsTrue(target.TryGet("TST", out result)); Assert.IsTrue(target.TryGet("tst", out result)); Assert.IsTrue(target.TryGet("TsT", out result)); } [TestMethod] public void ISOCountryLookup_AutoDetectCode_IsCaseSensitive() { var target = new ISOCountryLookup<TestCountry>(new TestCountryReader().GetDefault(), false); TestCountry result; Assert.IsTrue(target.TryGet("TC", out result)); Assert.IsFalse(target.TryGet("tc", out result)); Assert.IsFalse(target.TryGet("Tc", out result)); Assert.IsTrue(target.TryGet("TST", out result)); Assert.IsFalse(target.TryGet("tst", out result)); Assert.IsFalse(target.TryGet("TsT", out result)); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using IdOps.IdentityServer.Model; namespace IdOps.IdentityServer.Storage { public interface IUserClaimRuleRepository { Task<IEnumerable<UserClaimRule>> GetAllAsync(CancellationToken cancellationToken); Task<UpdateResourceResult> UpdateAsync(UserClaimRule apiResource, CancellationToken cancellationToken); } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using MikuMikuLibrary.IO.Common; namespace MikuMikuLibrary.IO.Sections.Enrs { public class EnrsBinaryWriter : EndianBinaryWriter { private readonly long mBeginPosition; private readonly List<byte> mBitArray; private void SetBitArrayValue( long offset, byte value ) { if ( offset < 0 ) return; int index = ( int ) ( offset / 4 ); while ( mBitArray.Count < index + 1 ) mBitArray.Add( 0xFF ); int bitOffset = ( int ) ( ( offset % 4 ) * 2 ); mBitArray[ index ] = BitHelper.Pack( mBitArray[ index ], value, bitOffset, bitOffset + 2 ); } private int GetBitArrayValue( long offset ) { int index = ( int ) ( offset / 4 ); if ( index < 0 || index >= mBitArray.Count ) return 3; int bitOffset = ( int ) ( ( offset % 4 ) * 2 ); return BitHelper.Unpack( mBitArray[ index ], bitOffset, bitOffset + 2 ); } public override void Write( short value ) { if ( EndiannessHelper.Swap( value ) != value ) SetBitArrayValue( Position - mBeginPosition, ( int ) ValueType.Int16 ); base.Write( value ); } public override unsafe void Write( ushort value ) => Write( *( short* ) &value ); public override void Write( int value ) { if ( EndiannessHelper.Swap( value ) != value ) SetBitArrayValue( Position - mBeginPosition, ( int ) ValueType.Int32 ); base.Write( value ); } public override unsafe void Write( uint value ) => Write( *( int* ) &value ); public override void Write( long value ) { if ( EndiannessHelper.Swap( value ) != value ) SetBitArrayValue( Position - mBeginPosition, ( int ) ValueType.Int64 ); base.Write( value ); } public override unsafe void Write( ulong value ) => Write( *( long* ) &value ); public override unsafe void Write( float value ) => Write( *( int* ) &value ); public override unsafe void Write( double value ) => Write( *( long* ) &value ); public List<ScopeDescriptor> CreateScopeDescriptors( long dataSize ) { var scopeDescriptors = new List<ScopeDescriptor>(); var fieldDescriptors = new List<FieldDescriptor>(); for ( long offset = 0; offset < dataSize; ) { int type = GetBitArrayValue( offset ); if ( type == 3 ) { offset++; continue; } var fieldDescriptor = new FieldDescriptor { Position = offset, ValueType = ( ValueType ) type, RepeatCount = 1 }; int byteSize = 2 << type; for ( ; offset < dataSize; ) { offset += byteSize; if ( GetBitArrayValue( offset ) != type ) break; fieldDescriptor.RepeatCount++; } fieldDescriptors.Add( fieldDescriptor ); } // TODO: Optimize var scopeDescriptor = new ScopeDescriptor { Position = fieldDescriptors[ 0 ].Position, RepeatCount = 1 }; scopeDescriptor.FieldDescriptors.AddRange( fieldDescriptors ); scopeDescriptors.Add( scopeDescriptor ); return scopeDescriptors; } public EnrsBinaryWriter( Stream input, Encoding encoding, Endianness endianness, bool leaveOpen, long beginPosition ) : base( input, encoding, endianness, leaveOpen ) { mBeginPosition = beginPosition; mBitArray = new List<byte>( 1024 * 1024 ); } } }
using System.Collections.Generic; namespace SST.Application.Users.Queries.GetUsers { public class UsersListVm { public IList<UserDto> Users { get; set; } } }
using System.Text; namespace TestStack.BDDfy.Reporters.Serializers { // http://www.limilabs.com/blog/json-net-formatter public class JsonFormatter { StringWalker _walker; IndentWriter _writer = new IndentWriter(); StringBuilder _currentLine = new StringBuilder(); bool _quoted; public JsonFormatter(string json) { _walker = new StringWalker(json); ResetLine(); } public void ResetLine() { _currentLine.Length = 0; } public string Format() { while (MoveNextChar()) { if (this._quoted == false && this.IsOpenBracket()) { this.WriteCurrentLine(); this.AddCharToLine(); this.WriteCurrentLine(); _writer.Indent(); } else if (this._quoted == false && this.IsCloseBracket()) { this.WriteCurrentLine(); _writer.UnIndent(); this.AddCharToLine(); } else if (this._quoted == false && this.IsColon()) { this.AddCharToLine(); this.WriteCurrentLine(); } else { AddCharToLine(); } } this.WriteCurrentLine(); return _writer.ToString(); } private bool MoveNextChar() { bool success = _walker.MoveNext(); if (this.IsApostrophe()) { this._quoted = !_quoted; } return success; } public bool IsApostrophe() { return this._walker.CharAtIndex() == '"'; } public bool IsOpenBracket() { return this._walker.CharAtIndex() == '{' || this._walker.CharAtIndex() == '['; } public bool IsCloseBracket() { return this._walker.CharAtIndex() == '}' || this._walker.CharAtIndex() == ']'; } public bool IsColon() { return this._walker.CharAtIndex() == ','; } private void AddCharToLine() { this._currentLine.Append(_walker.CharAtIndex()); } private void WriteCurrentLine() { string line = this._currentLine.ToString().Trim(); if (line.Length > 0) { _writer.WriteLine(line); } this.ResetLine(); } } public class IndentWriter { StringBuilder _sb = new StringBuilder(); int _indent; public void Indent() { _indent++; } public void UnIndent() { if (_indent > 0) _indent--; } public void WriteLine(string line) { _sb.AppendLine(CreateIndent() + line); } private string CreateIndent() { StringBuilder indentString = new StringBuilder(); for (int i = 0; i < _indent; i++) indentString.Append(" "); return indentString.ToString(); } public override string ToString() { return _sb.ToString(); } } public class StringWalker { string _s; public int Index { get; set; } public StringWalker(string s) { _s = s; Index = -1; } public bool MoveNext() { if (Index == _s.Length - 1) return false; Index++; return true; } public char CharAtIndex() { return _s[Index]; } }; }
using System.Collections.Generic; using Newtonsoft.Json; namespace apiClientDotNet.Models { public class UserInfoList { [JsonProperty("users")] public List<UserInfo> Users { get; set; } } }
namespace Griffin.Net.Authentication.Messages { /// <summary> /// Finaly step of the authentication process. /// </summary> public interface IAuthenticateReply { /// <summary> /// Returns wether the user may login or not /// </summary> AuthenticateReplyState State { get; } /// <summary> /// Token created by the server to prove it's identity /// </summary> /// <remarks> /// <para> /// It's generated with the help of the client salt and the password hash that is stored for the user. /// </para> /// </remarks> string AuthenticationToken { get; } } }
using System; using System.Collections.Generic; using OpenDMS.Storage.Security; namespace OpenDMS.Storage.SearchProviders { public interface IResourceResult { DateTime? CheckedOutAt { get; set; } string CheckedOutTo { get; set; } DateTime LastCommit { get; set; } string LastCommitter { get; set; } System.Collections.Generic.List<string> Tags { get; set; } string Title { get; set; } List<UsageRight> UsageRights { get; set; } SearchProviders.ResourceResult MakeResource(); } }
using System; using Xunit; namespace WmcSoft { public class SemVerTests { [Fact] public void CanCreateSemVerFromVersion() { var version = new Version(1, 2, 3, 4); var semver = (SemVer)version; Assert.Equal(version.Major, semver.Major); Assert.Equal(version.Minor, semver.Minor); Assert.Equal(version.Build, semver.Patch); } [Fact] public void CanDeconstructSemVer() { var semver = new SemVer(1, 2, 3); var (major, minor, patch) = semver; Assert.Equal(1, major); Assert.Equal(2, minor); Assert.Equal(3, patch); } [Theory] [InlineData(1, 2, 3, null, "1.2.3")] [InlineData(2, 0, 0, null, "2.0.0")] public void CanConvertSemVerToString(int major, int minor, int patch, string prerelease, string expected) { var semver = new SemVer(major, minor, patch, prerelease); var actual = semver.ToString(); Assert.Equal(expected, actual); } [Theory] [InlineData(1, 2, 3, null, "1.2.4")] public void CanIncrement(int major, int minor, int patch, string prerelease, string expected) { var semver = new SemVer(major, minor, patch, prerelease); semver++; var actual = semver.ToString(); Assert.Equal(expected, actual); } [Fact] public void CanCompare() { SemVer v0 = null; SemVer w0 = null; var v1 = new SemVer(1, 2, 3); var v2 = new SemVer(1, 2, 4); var v3 = new SemVer(1, 3, 3); var v4 = new SemVer(2, 2, 3); Assert.True(v1 < v2); Assert.True(v2 > v1); Assert.True(v1 <= v2); Assert.True(v2 >= v1); Assert.True(v2 < v3); Assert.True(v3 < v4); Assert.False(v1 < v0); Assert.False(v0 > v1); Assert.True(v1 <= v2); Assert.True(v2 >= v1); Assert.True(v0 == w0); Assert.False(v0 != w0); } [Theory] [InlineData("1.2.3", 1, 2, 3, null, null)] [InlineData("2.0.0", 2, 0, 0, null, null)] //[InlineData("1.0.0-alpha+001", 1, 0, 0, "alpha", "001", Skip = "Not ready")] public void CanParseStrict(string s, int major, int minor, int patch, string prerelease, string build) { var v = SemVer.Parse(s); Assert.True(v.Major == major); Assert.True(v.Minor == minor); Assert.True(v.Patch == patch); Assert.True(v.Prerelease == prerelease); Assert.True(v.Build == build); } } }
using UnityEngine; namespace LevelGeneration { [System.Serializable] public class Area { public bool generated; public GameObject parent; public GridGeneration.GridTile tileInfo; public DoorWay entrance; public DoorWay exit; public Area(GameObject g, GridGeneration.GridTile tile) { parent = g; tileInfo = tile; parent.transform.position = tile.position; parent.tag = "Area"; } } }
 namespace CreatorSpace.IntegrationTests.Tiers.Commands { using System.Threading.Tasks; using CreatorSpace.Application.Common.Exceptions; using CreatorSpace.Application.Tiers.Commands.DeleteTier; using CreatorSpace.Domain.Models; using FluentAssertions; using NUnit.Framework; using static Testing; public class DeleteTierTests : TestBase { [Test] public async Task ShouldRequireId() { await RunAsAdministratorAsync(); var command = new DeleteTierCommand(); FluentActions.Invoking(() => SendAsync(command)) .Should() .Throw<ValidationException>() .Where(ex => ex.Errors.Count == 1 && ex.Errors.ContainsKey(nameof(command.Id))); } [Test] public async Task ShouldDeleteTier() { await RunAsAdministratorAsync(); var tier = await TierHelpers.AddTier(); var command = new DeleteTierCommand { Id = tier.Id, }; await SendAsync(command); var deleted = await FindAsync<Tier>(command.Id); deleted.Should().BeNull(); } } }
using System; using Godot; namespace StateMachine { public class State : Node { public Action<float> OnProcess { get; set; } public Action<float> OnPhysicsProcess { get; set; } public Action OnEnter { get; set; } public Action OnExit { get; set; } public Action<InputEvent> OnInput { get; set; } public StateMachine StateMachine { get; set; } public override string ToString() { return Name; } } }
namespace EnvironmentAssessment.Common.VimApi { public class VirtualControllerOption : VirtualDeviceOption { protected IntOption _devices; protected string[] _supportedDevice; public IntOption Devices { get { return this._devices; } set { this._devices = value; } } public string[] SupportedDevice { get { return this._supportedDevice; } set { this._supportedDevice = value; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Nomad.DotNet.Model { public class Resources: ApiObject<Resources> { public int Cpu { get; set; } public int MemoryMb { get; set; } public int DiskMb { get; set; } public int Iops { get; set; } public IList<NetworkResource> Networks { get; set; } = new List<NetworkResource>(); } }
using System; namespace MSR.CVE.BackMaker { public class HeapBool { private bool b; public bool value { get { return this.b; } set { this.b = value; } } public HeapBool(bool initialValue) { this.b = initialValue; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using LightBlue.Standalone; namespace LightBlue.Tests.Standalone { public enum DirectoryType { Account = 0, BlobStorage = 1, Container = 2, QueueStorage = 3, Queue = 4 } public abstract class StandaloneAzureTestsBase { public const string MetadataDirectory = ".meta"; protected readonly string BasePath; private readonly string _appDataDirectory; protected StandaloneAzureTestsBase(DirectoryType directoryType) { _appDataDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var lightBlueDirectory = Path.Combine(_appDataDirectory, "LightBlue"); var accountDirectory = Path.Combine(lightBlueDirectory, "dev"); var blobDirectory = Path.Combine(accountDirectory, "blob"); var queuesDirectory = Path.Combine(accountDirectory, "queuse"); StandaloneEnvironment.LightBlueDataDirectory = lightBlueDirectory; Directory.CreateDirectory(blobDirectory); Directory.CreateDirectory(queuesDirectory); switch (directoryType) { case DirectoryType.Account: BasePath = accountDirectory; break; case DirectoryType.BlobStorage: BasePath = blobDirectory; break; case DirectoryType.Container: var containerDirectory = Path.Combine(blobDirectory, "container"); Directory.CreateDirectory(Path.Combine(containerDirectory, MetadataDirectory)); BasePath = containerDirectory; break; case DirectoryType.QueueStorage: BasePath = queuesDirectory; break; case DirectoryType.Queue: var queueDirectory = Path.Combine(queuesDirectory, "queue"); Directory.CreateDirectory(Path.Combine(queueDirectory, MetadataDirectory)); BasePath = queueDirectory; break; } } protected Uri BasePathUri { get { return new Uri(BasePath); } } public static IEnumerable<object[]> BlobNames { get { yield return new object[] {"someblob"}; yield return new object[] {@"with\path\blob"}; yield return new object[] {"with/alternate/separator"}; } } public void Dispose() { StandaloneEnvironment.SetStandardLightBlueDataDirectory(); if (string.IsNullOrWhiteSpace(_appDataDirectory) || !Directory.Exists(_appDataDirectory)) { return; } var tries = 0; while (tries++ < 2) try { Directory.Delete(_appDataDirectory, true); return; } catch (IOException) {} catch (UnauthorizedAccessException) {} } protected static void CreateBlobContent(StandaloneAzureBlockBlob blob) { var buffer = Encoding.UTF8.GetBytes("Some content"); blob.UploadFromByteArrayAsync(buffer, 0, buffer.Length).Wait(); } } }
using System; using System.Globalization; namespace Microsoft.VisualStudio.TextTemplating { /// <summary> /// Utility class to produce culture-oriented representation of an object as a string. /// </summary> public static class ToStringHelper { private static IFormatProvider formatProviderField = CultureInfo.InvariantCulture; /// <summary> /// Gets or sets format provider to be used by ToStringWithCulture method. /// </summary> public static IFormatProvider FormatProvider { get => formatProviderField; set { if (value == null) return; formatProviderField = value; } } /// <summary> /// This is called from the compile/run appdomain to convert objects within an expression block to a string /// </summary> public static string ToStringWithCulture(object objectToConvert) { if (objectToConvert == null) throw new ArgumentNullException(nameof(objectToConvert)); var t = objectToConvert.GetType(); var method = t.GetMethod("ToString", new[] { typeof(IFormatProvider) }); if (method == null) return objectToConvert.ToString(); return (string) method.Invoke(objectToConvert, new object[] {formatProviderField}); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RightLEDView : MonoBehaviour { public GameObject panelUEexecuted; public GameObject panelBrandfallControlAb; public GameObject panelBMZReset; private Image imageUEExecuted; private Image imageBrandFallControlAb; private Image imageBMZReset; private Color imageUEExecutedBeforeTest; private Color imageBrandFallControlAbTest; private Color imageBMZResetTest; // Start is called before the first frame update void Start() { imageUEExecuted = panelUEexecuted.GetComponent<Image>(); imageBrandFallControlAb = panelBrandfallControlAb.GetComponent<Image>(); imageBMZReset = panelBMZReset.GetComponent<Image>(); } // Update is called once per frame void Update() { } public void switchTestOn() { imageUEExecutedBeforeTest = imageUEExecuted.color; imageBrandFallControlAbTest = imageBrandFallControlAb.color; imageBMZResetTest = imageBMZReset.color; imageUEExecuted.color = Color.red; imageBrandFallControlAb.color = Color.yellow; imageBMZReset.color = Color.red; } public void switchTestOff() { imageUEExecuted.color = imageUEExecutedBeforeTest; imageBrandFallControlAb.color = imageBrandFallControlAbTest; imageBMZReset.color = imageBMZResetTest; } public void switchLEDUEExecutedOn() { imageUEExecuted.color = Color.red; } public void switchLEDUEExecutedOff() { imageUEExecuted.color = Color.grey; } public void switchLEDBrandFallControlAbOn() { imageBrandFallControlAb.color = Color.yellow; } public void switchLEDBrandFallControlAbOff() { imageBrandFallControlAb.color = Color.grey; } public void switchImageBMZResetOn() { imageBMZReset.color = Color.red; } public void switchBMZResetOff() { imageBMZReset.color = Color.grey; } public bool brandfallLEDOn() { return imageBrandFallControlAb.color == Color.yellow; } }
using System; using System.Text; using System.Globalization; namespace LinqToDB.DataProvider.Access { using Mapping; using SqlQuery; using System.Data.Linq; public class AccessMappingSchema : MappingSchema { public AccessMappingSchema() : this(ProviderName.Access) { } protected AccessMappingSchema(string configuration) : base(configuration) { SetDataType(typeof(DateTime), DataType.DateTime); SetDataType(typeof(DateTime?), DataType.DateTime); SetValueToSqlConverter(typeof(bool), (sb,dt,v) => sb.Append(v)); SetValueToSqlConverter(typeof(Guid), (sb,dt,v) => sb.Append("'").Append(((Guid)v).ToString("B")).Append("'")); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql(sb, (DateTime)v)); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string), 255)); SetValueToSqlConverter(typeof(String), (sb,dt,v) => ConvertStringToSql (sb, v.ToString())); SetValueToSqlConverter(typeof(Char), (sb,dt,v) => ConvertCharToSql (sb, (char)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("chr(") .Append(value) .Append(")") ; } static void ConvertStringToSql(StringBuilder stringBuilder, string value) { DataTools.ConvertStringToSql(stringBuilder, "+", null, AppendConversion, value, null); } static void ConvertCharToSql(StringBuilder stringBuilder, char value) { DataTools.ConvertCharToSql(stringBuilder, "'", AppendConversion, value); } static void ConvertDateTimeToSql(StringBuilder stringBuilder, DateTime value) { var format = value.Hour == 0 && value.Minute == 0 && value.Second == 0 ? "#{0:yyyy-MM-dd}#" : "#{0:yyyy-MM-dd HH:mm:ss}#"; stringBuilder.AppendFormat(format, value); } } }
namespace FairlayDotNetClient.Private.Datatypes { public class UserOrder { public int BidOrAsk; public long MarketID; public int RunnerID; public long OrderID; public string MatchedSubUser; public override string ToString() => BidOrAsk + " "+ MarketID + " "+ RunnerID + "-"; } }
namespace Bloggable.Services.Common.Cache { using System; using System.Collections.Generic; using System.Linq; using Bloggable.Common.Constants; using Bloggable.Data.Contracts.Repositories; using Bloggable.Data.Models; using Bloggable.Services.Common.Cache.Contracts; public class CacheItemsProviderService : ICacheItemsProviderService { private readonly ICacheService cache; private readonly IRepository<Setting> settings; public CacheItemsProviderService(ICacheService cache, IRepository<Setting> settings) { if (cache == null) { throw new ArgumentNullException(nameof(cache)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } this.cache = cache; this.settings = settings; } public IDictionary<string, string> GetSettings(int cacheSeconds) { var forumCategories = this.cache.Get( CacheConstants.Settings, () => this.settings.All().ToDictionary(s => s.Id, s => s.Value), cacheSeconds); return forumCategories; } } }
public enum SearchResultType { //Latest tweets recent, //Most popular tweets popular, //A mix of both popular and recent tweets mixed }
using cv19ResSupportV3.V3.Gateways; using cv19ResSupportV3.V3.UseCase; using cv19ResSupportV3.V4.Factories; using cv19ResSupportV3.V4.UseCase.Interface; namespace cv19ResSupportV3.V4.UseCase { public class CreateResidentsUseCase : ICreateResidentsUseCase { private readonly IResidentGateway _gateway; public CreateResidentsUseCase(IResidentGateway gateway) { _gateway = gateway; } public ResidentResponseBoundary Execute(ResidentRequestBoundary request) { var gwResponse = _gateway.CreateResident(request.ToCommand()); return gwResponse.ToResponse(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Makaretu.Dns { [TestClass] public class DnsObjectTest { [TestMethod] public void Length_EmptyMessage() { var message = new Message(); Assert.AreEqual(Message.MinLength, message.Length()); } [TestMethod] public void Clone() { var m1 = new Message { Questions = { new Question { Name = "example.com" } } }; var m2 = (Message)m1.Clone(); CollectionAssert.AreEqual(m1.ToByteArray(), m2.ToByteArray()); } [TestMethod] public void Clone_Typed() { var m1 = new Message { Questions = { new Question { Name = "example.com" } } }; var m2 = m1.Clone<Message>(); CollectionAssert.AreEqual(m1.ToByteArray(), m2.ToByteArray()); } } }
using Data.Base; using Data.Enums; namespace Data { public class Pineapple : ProductOfNature { public Pineapple() : base("Pineapple", Kinds.Fruit, Measurings.PerItem, null) { } } }
@model BaristaBuddyMVC.Models.EditItemViewModel @{ ViewData["Title"] = "Add Item"; } <h1>Add Item</h1> <h4>Item</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Ingredients" class="control-label"></label> <input asp-for="Ingredients" class="form-control" /> <span asp-validation-for="Ingredients" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ItemImageUrl" class="control-label"></label> <input asp-for="ItemImageUrl" class="form-control" /> <span asp-validation-for="ItemImageUrl" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Price" class="control-label"></label> <input asp-for="Price" class="form-control" /> <span asp-validation-for="Price" class="text-danger"></span> </div> <div class="form-group"> <ul> @for(var i=0; i<Model.ItemModifiers.Count; i++) { <li> <label> @Html.CheckBoxFor(_=> Model.ItemModifiers[i].Selected) @Html.DisplayFor(_=> Model.ItemModifiers[i].Name) @Html.HiddenFor(_ => Model.ItemModifiers[i].Id) @Html.HiddenFor(_ => Model.ItemModifiers[i].Name) </label> @Html.EditorFor(_ => Model.ItemModifiers[i].AdditionalCost) </li> } </ul> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> <div> <a asp-action="Index" asp-route-storeId="@ViewContext.RouteData.Values["StoreId"]">Return to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
public class OptionsData { public float generalVolume; public float musicVolume; public float effectsVolume; }
// <auto-generated> // Auto-generated by StoneAPI, do not modify. // </auto-generated> namespace Dropbox.Api.TeamLog { using sys = System; using col = System.Collections.Generic; using re = System.Text.RegularExpressions; using enc = Dropbox.Api.Stone; /// <summary> /// <para>Received files for file request.</para> /// </summary> public class FileRequestReceiveFileDetails { #pragma warning disable 108 /// <summary> /// <para>The encoder instance.</para> /// </summary> internal static enc.StructEncoder<FileRequestReceiveFileDetails> Encoder = new FileRequestReceiveFileDetailsEncoder(); /// <summary> /// <para>The decoder instance.</para> /// </summary> internal static enc.StructDecoder<FileRequestReceiveFileDetails> Decoder = new FileRequestReceiveFileDetailsDecoder(); /// <summary> /// <para>Initializes a new instance of the <see cref="FileRequestReceiveFileDetails" /// /> class.</para> /// </summary> /// <param name="submittedFileNames">Submitted file names.</param> /// <param name="fileRequestId">File request id. Might be missing due to historical /// data gap.</param> /// <param name="fileRequestDetails">File request details. Might be missing due to /// historical data gap.</param> /// <param name="submitterName">The name as provided by the submitter.</param> /// <param name="submitterEmail">The email as provided by the submitter.</param> public FileRequestReceiveFileDetails(col.IEnumerable<string> submittedFileNames, string fileRequestId = null, FileRequestDetails fileRequestDetails = null, string submitterName = null, string submitterEmail = null) { var submittedFileNamesList = enc.Util.ToList(submittedFileNames); if (submittedFileNames == null) { throw new sys.ArgumentNullException("submittedFileNames"); } if (fileRequestId != null) { if (fileRequestId.Length < 1) { throw new sys.ArgumentOutOfRangeException("fileRequestId", "Length should be at least 1"); } if (!re.Regex.IsMatch(fileRequestId, @"\A(?:[-_0-9a-zA-Z]+)\z")) { throw new sys.ArgumentOutOfRangeException("fileRequestId", @"Value should match pattern '\A(?:[-_0-9a-zA-Z]+)\z'"); } } if (submitterEmail != null) { if (submitterEmail.Length > 255) { throw new sys.ArgumentOutOfRangeException("submitterEmail", "Length should be at most 255"); } } this.SubmittedFileNames = submittedFileNamesList; this.FileRequestId = fileRequestId; this.FileRequestDetails = fileRequestDetails; this.SubmitterName = submitterName; this.SubmitterEmail = submitterEmail; } /// <summary> /// <para>Initializes a new instance of the <see cref="FileRequestReceiveFileDetails" /// /> class.</para> /// </summary> /// <remarks>This is to construct an instance of the object when /// deserializing.</remarks> [sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)] public FileRequestReceiveFileDetails() { } /// <summary> /// <para>Submitted file names.</para> /// </summary> public col.IList<string> SubmittedFileNames { get; protected set; } /// <summary> /// <para>File request id. Might be missing due to historical data gap.</para> /// </summary> public string FileRequestId { get; protected set; } /// <summary> /// <para>File request details. Might be missing due to historical data gap.</para> /// </summary> public FileRequestDetails FileRequestDetails { get; protected set; } /// <summary> /// <para>The name as provided by the submitter.</para> /// </summary> public string SubmitterName { get; protected set; } /// <summary> /// <para>The email as provided by the submitter.</para> /// </summary> public string SubmitterEmail { get; protected set; } #region Encoder class /// <summary> /// <para>Encoder for <see cref="FileRequestReceiveFileDetails" />.</para> /// </summary> private class FileRequestReceiveFileDetailsEncoder : enc.StructEncoder<FileRequestReceiveFileDetails> { /// <summary> /// <para>Encode fields of given value.</para> /// </summary> /// <param name="value">The value.</param> /// <param name="writer">The writer.</param> public override void EncodeFields(FileRequestReceiveFileDetails value, enc.IJsonWriter writer) { WriteListProperty("submitted_file_names", value.SubmittedFileNames, writer, enc.StringEncoder.Instance); if (value.FileRequestId != null) { WriteProperty("file_request_id", value.FileRequestId, writer, enc.StringEncoder.Instance); } if (value.FileRequestDetails != null) { WriteProperty("file_request_details", value.FileRequestDetails, writer, global::Dropbox.Api.TeamLog.FileRequestDetails.Encoder); } if (value.SubmitterName != null) { WriteProperty("submitter_name", value.SubmitterName, writer, enc.StringEncoder.Instance); } if (value.SubmitterEmail != null) { WriteProperty("submitter_email", value.SubmitterEmail, writer, enc.StringEncoder.Instance); } } } #endregion #region Decoder class /// <summary> /// <para>Decoder for <see cref="FileRequestReceiveFileDetails" />.</para> /// </summary> private class FileRequestReceiveFileDetailsDecoder : enc.StructDecoder<FileRequestReceiveFileDetails> { /// <summary> /// <para>Create a new instance of type <see cref="FileRequestReceiveFileDetails" /// />.</para> /// </summary> /// <returns>The struct instance.</returns> protected override FileRequestReceiveFileDetails Create() { return new FileRequestReceiveFileDetails(); } /// <summary> /// <para>Set given field.</para> /// </summary> /// <param name="value">The field value.</param> /// <param name="fieldName">The field name.</param> /// <param name="reader">The json reader.</param> protected override void SetField(FileRequestReceiveFileDetails value, string fieldName, enc.IJsonReader reader) { switch (fieldName) { case "submitted_file_names": value.SubmittedFileNames = ReadList<string>(reader, enc.StringDecoder.Instance); break; case "file_request_id": value.FileRequestId = enc.StringDecoder.Instance.Decode(reader); break; case "file_request_details": value.FileRequestDetails = global::Dropbox.Api.TeamLog.FileRequestDetails.Decoder.Decode(reader); break; case "submitter_name": value.SubmitterName = enc.StringDecoder.Instance.Decode(reader); break; case "submitter_email": value.SubmitterEmail = enc.StringDecoder.Instance.Decode(reader); break; default: reader.Skip(); break; } } } #endregion } }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace FabricObserver.Utilities { public sealed class ErrorWarningProperty { // CPU/Memory public const string TotalCpuTime = "Total CPU Time"; public const string TotalMemoryConsumptionMB = "Memory Consumption MB"; public const string TotalMemoryConsumptionPct = "Memory Consumption %"; // Disk... public const string DiskAverageQueueLength = "Average Disk Queue Length"; public const string DiskSpaceUsagePercentage = "Disk Space Consumption %"; public const string DiskSpaceUsageMB = "Disk Space Consumption MB"; public const string DiskSpaceAvailableMB = "Disk Space Available MB"; public const string DiskSpaceTotalMB = "Disk Space Total MB"; // Network public const string InternetConnectionFailure = "Outbound Internet Connection Failure"; public const string TotalActiveFirewallRules = "Total Active Firewall Rules"; public const string TotalActivePorts = "Total Active Ports"; public const string TotalEphemeralPorts = "Total Ephemeral Active Ports"; } }
using System; using System.Collections.Generic; namespace GOAP.Helper { public static class OperatorHelper { static string[] op_array_name = { "OperatorSet",//0 "OperatorEqual",//1 "OperatorUnequal",//2 "OperatorEqualHight",//3 "OperatorEqualLess",//4 "OperatorHight",//5 "OperatorLess",//6 "OperatorAddOne",//7 "OperatorRemoveOne",//8 "OperatorAdd",//9 "OperatorRemove"//10 }; static string[] op_array_name_symbol = { "=",//0 "==",//1 "!=",//2 ">=",//3 "<=",//4 ">",//5 "<",//6 "++",//7 "--",//8 "+=",//9 "-="//10 }; private static Dictionary<int, List<string>> operator_data = new Dictionary<int, List<string>>() { {operator_name,new List<string>(op_array_name)}, {operator_symbol,new List<string>(op_array_name_symbol)} }; const int operator_name = 0; const int operator_symbol = 1; const int op_set = 0; const int op_equal = 1; const int op_unequal = 2; const int op_equal_or_hight = 3; const int op_equal_or_less =4; const int op_hight =5; const int op_less =6; const int op_add_one = 7; const int op_remove_one = 8; const int op_add = 9; const int op_remove = 10; public static List<string> GetCheckOperatorForType(Type type) { List<string> ret = new List<string>(); if(type == typeof(bool)) { ret.Add(operator_data[operator_symbol][op_equal]); ret.Add(operator_data[operator_symbol][op_unequal]); } if (type == typeof(float) || type == typeof(int)) { ret.Add(operator_data[operator_symbol][op_equal]); ret.Add(operator_data[operator_symbol][op_unequal]); ret.Add(operator_data[operator_symbol][op_equal_or_hight]); ret.Add(operator_data[operator_symbol][op_equal_or_less]); ret.Add(operator_data[operator_symbol][op_hight]); ret.Add(operator_data[operator_symbol][op_less]); } if (typeof(UnityEngine.Object).IsAssignableFrom(type)) { ret.Add(operator_data[operator_symbol][op_equal]); ret.Add(operator_data[operator_symbol][op_unequal]); } return ret; } public static List<string> GetSetOperatorForType(Type type) { List<string> ret = new List<string>(); if (type == typeof(bool)) { ret.Add(operator_data[operator_symbol][op_set]); } if (type == typeof(float) || type == typeof(int)) { ret.Add(operator_data[operator_symbol][op_set]); ret.Add(operator_data[operator_symbol][op_add_one]); ret.Add(operator_data[operator_symbol][op_remove_one]); ret.Add(operator_data[operator_symbol][op_add]); ret.Add(operator_data[operator_symbol][op_remove]); } if (typeof(UnityEngine.Object).IsAssignableFrom(type)) { ret.Add(operator_data[operator_symbol][op_set]); } return ret; } public static string GetSymbolName(string symbol) { int index = operator_data[operator_symbol].IndexOf(symbol); if(index==-1) return "<b>NULL</b>"; return operator_data[operator_name][index]; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace Prime.Models { [Table("BusinessDay")] public class BusinessDay : BaseAuditable, IValidatableObject { [Key] [JsonIgnore] public int Id { get; set; } public int SiteId { get; set; } [JsonIgnore] public Site Site { get; set; } public DayOfWeek Day { get; set; } public TimeSpan StartTime { get; set; } public TimeSpan EndTime { get; set; } /// <summary> /// Does the supplied time fall between the Start Time and End Time? /// </summary> public bool IsOpen(TimeSpan time) { return time >= StartTime && time <= EndTime; } /// <summary> /// Does the supplied time fall between the Start Time and End Time? /// Only the time portion of the input parameter is considered. /// </summary> public bool IsOpen(DateTimeOffset time) { return IsOpen(time.TimeOfDay); } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (StartTime >= EndTime) { yield return new ValidationResult($"Start Time must be before End Time"); } } } }
using SocialNetwork.Kata.Model; namespace SocialNetwork.Kata.Repo { interface IRepo { public User GetOrAdd(string name); public User GetOrNull(string name); } }
using System; using UCLouvain.KAOSTools.Propagators.BDD; using UCLouvain.KAOSTools.Propagators.Tests; using UCLouvain.KAOSTools.Core; using System.Linq; using UCLouvain.KAOSTools.Core.SatisfactionRates; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Environments; namespace UCLouvain.KAOSTools.Propagators.Benchmark { [MySuperJob()] public class PatternVSBDD { KAOSModel model; Goal root; BDDBasedPropagator p3; [Params(/*10,100,*/1000,10000,100000)] public int NbGoals { get; set; } [Params(/*10,*/100,1000,10000)] public int NbObstructions { get; set; } [Params(/*10,100,*/1000,10000,100000)] public int NbObstacles { get; set; } public PatternVSBDD () { } [GlobalSetup] public void Setup () { var options = new RandomModelOptions { NbGoals = NbGoals, NbObstructions = NbObstructions, NbObstacles = NbObstacles }; var generator = new RandomModelGenerator (options); model = generator.Generate (); root = model.RootGoals ().Single (); p3 = new BDDBasedPropagator (model); p3.PreBuildObstructionSet (root); } [Benchmark] public DoubleSatisfactionRate PatternBasedComputation () { var p1 = new PatternBasedPropagator (model); return (DoubleSatisfactionRate) p1.GetESR (root); } [Benchmark] public DoubleSatisfactionRate BDDBasedComputation () { var p2 = new BDDBasedPropagator (model); return (DoubleSatisfactionRate) p2.GetESR (root); } [Benchmark] public DoubleSatisfactionRate BDDBasedComputationPrebuilt () { return (DoubleSatisfactionRate) p3.GetESR (root); } } }
using System; namespace LateBindingApi.Excel.Enums { public enum MsoAlertIconType { msoAlertIconNoIcon = 0, msoAlertIconCritical = 1, msoAlertIconQuery = 2, msoAlertIconWarning = 3, msoAlertIconInfo = 4 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace CoreWCF.Security { internal class WSSecurityPolicy11 : WSSecurityPolicy { public const string WsspNamespace = @"http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"; } }
using FluentAssertions; using HomeCloud.Maps.Application.Database; using HomeCloud.Maps.Application.Database.Collections; using HomeCloud.Maps.Domain.Tours; using HomeCloud.Maps.Infrastructure.Database.Collection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using static OneOf.Types.TrueFalseOrNull; namespace HomeCloud.Maps.UnitTests.Backend.Infrastructure.Database.Collections { [Collection("DB")] public class TourInfoCollectionTests : DatabaseTestBase<ITourInfoCollection, TourInfo> { public TourInfoCollectionTests(DatabaseFixture databaseFixture) : base(databaseFixture) { } protected override ICollectionBase<TourInfo> GetCollection(IRepository repository) => repository.TourInfoCollection; [Fact] public Task TourInfo_InsertAsync() => InsertAsync(); [Fact] public Task TourInfo_InsertManyAsync() => InsertManyAsync(); [Fact] public Task FirstAsync_ShouldReturnTour() => FirstAsync_ShouldReturnElement(expected => Repository.TourInfoCollection.FirstAsync(expected.UserId, expected.TourId)); [Theory] [InlineData("test-userid", "test-tourid")] public Task FirstAsync_ShouldReturnNull(string userId, string tourId) => FirsAsync_ShouldReturnNull(() => Repository.TourInfoCollection.FirstAsync(userId, tourId)); [Theory] [InlineData("Hausberg", "berg")] [InlineData("Feldberg - Bad Homburg", "Feld")] [InlineData("Feldberg - Bad", "feld")] [InlineData("Feldberg", "eld")] [InlineData("Feldberg - Bad Homburg", "- Bad ho")] [InlineData("Feldberg - Bad Homburg", "Feldberg - Bad Homburg")] public async Task FindPageAsync_SearchWithFilter_ShouldFindTour(string tourName, string filter) { // Arrange var data = Fixture.CreateList<TourInfo>(10); var expected = data.Skip(5).First(); expected.Name = tourName; await Repository.TourInfoCollection.InsertManyAsync(data); // Act var (Page, Count) = await Repository.TourInfoCollection .FindPageAsync(expected.UserId, 0, 10, filter); // Assert Page.Should().HaveCount(1); var actual = Page.First(); actual.Should().BeEquivalentTo(expected, options => options.AddDateTimeCloseToExpected()); } [Fact] public async Task FindPageAsync_SearchWithoutFilter() { // Arrange const string userId = "userid-test"; var data = Fixture.CreateList<TourInfo>(10); var expected = new[] { data.First(), data.Skip(5).First(), data.Last() }.ToList(); expected.ForEach(x => x.UserId = userId); await Repository.TourInfoCollection.InsertManyAsync(expected); // Act var (actual, count) = await Repository.TourInfoCollection .FindPageAsync(userId, 0, 10, new Null()); // Assert count.Should().Be(3); actual.Should().BeEquivalentTo(expected, options => options.AddDateTimeCloseToExpected()); } [Theory] [InlineData("Hausberg", "berg")] [InlineData("Feldberg - Bad Homburg", "Feld")] [InlineData("Feldberg - Bad", "feld")] [InlineData("Feldberg", "eld")] [InlineData("Feldberg - Bad Homburg", "- Bad ho")] [InlineData("Feldberg - Bad Homburg", "Feldberg - Bad Homburg")] public async Task FindPageAsync_ShouldReturnTotalCount(string tourName, string filter) { // Arrange const string userId = "userId-test"; const int pageSize = 10; var data = Fixture.CreateList<TourInfo>(61).ToList(); var fromUser = data.Take(50).ToList(); fromUser.ForEach(x => x.UserId = userId); var expected = fromUser.Take(29).ToList(); expected.ForEach(x => x.Name += tourName); await Repository.TourInfoCollection.InsertManyAsync(data); // Act var (page, count) = await Repository.TourInfoCollection.FindPageAsync(userId, 0, pageSize, filter); // Assert count.Should().Be(29); } [Theory] [InlineData("Hausberg", "berg")] [InlineData("Feldberg - Bad Homburg", "Feld")] [InlineData("Feldberg - Bad", "feld")] [InlineData("Feldberg", "eld")] [InlineData("Feldberg - Bad Homburg", "- Bad ho")] [InlineData("Feldberg - Bad Homburg", "Feldberg - Bad Homburg")] public async Task FindPageAsync_ShouldReturnCorrectPagination(string tourName, string filter) { // Arrange const string userId = "userId-test"; const int pageSize = 10; var data = Fixture.CreateList<TourInfo>(61).ToList(); var fromUser = data.Take(50).ToList(); fromUser.ForEach(x => x.UserId = userId); var expected = fromUser.Take(29).ToList(); expected.ForEach(x => x.Name += tourName); var expectedPageOne = expected.Take(10).ToList(); var expectedPageTwo = expected.Skip(10).Take(10).ToList(); var expectedPageThree = expected.Skip(20).ToList(); await Repository.TourInfoCollection.InsertManyAsync(data); // Act var (actualPageOne, _) = await Repository.TourInfoCollection.FindPageAsync(userId, 0, pageSize, filter); var (actualPageTwo, _) = await Repository.TourInfoCollection.FindPageAsync(userId, 1, pageSize, filter); var (actualPageThree, _) = await Repository.TourInfoCollection.FindPageAsync(userId, 2, pageSize, filter); // Assert actualPageOne.Should().HaveCount(10); actualPageOne.Should().BeEquivalentTo(expectedPageOne, options => options.AddDateTimeCloseToExpected()); actualPageTwo.Should().HaveCount(10); actualPageTwo.Should().BeEquivalentTo(expectedPageTwo, options => options.AddDateTimeCloseToExpected()); actualPageThree.Should().HaveCount(9); actualPageThree.Should().BeEquivalentTo(expectedPageThree, options => options.AddDateTimeCloseToExpected()); } } }
using Substrate.Nbt; using System; using System.Collections.Generic; namespace NBTModel.Interop { public static class FormRegistry { public delegate bool CreateNodeAction(CreateTagFormData data); public delegate bool EditByteArrayAction(ByteArrayFormData data); public delegate bool EditRestrictedStringAction(RestrictedStringFormData data); public delegate bool EditStringAction(StringFormData data); public delegate bool EditTagScalarAction(TagScalarFormData data); public static EditStringAction EditString { get; set; } public static EditRestrictedStringAction RenameTag { get; set; } public static EditTagScalarAction EditTagScalar { get; set; } public static EditByteArrayAction EditByteArray { get; set; } public static CreateNodeAction CreateNode { get; set; } public static Action<string> MessageBox { get; set; } } public class TagScalarFormData { public TagScalarFormData(TagNode tag) { Tag = tag; } public TagNode Tag { get; } } public class StringFormData { public StringFormData(string value) { Value = value; } public string Value { get; set; } public bool AllowEmpty { get; set; } } public class RestrictedStringFormData : StringFormData { public RestrictedStringFormData(string value) : base(value) { } public List<string> RestrictedValues { get; } = new List<string>(); } public class CreateTagFormData { public CreateTagFormData() { RestrictedNames = new List<string>(); } public TagType TagType { get; set; } public bool HasName { get; set; } public List<string> RestrictedNames { get; } public TagNode TagNode { get; set; } public string TagName { get; set; } } public class ByteArrayFormData { public string NodeName { get; set; } public int BytesPerElement { get; set; } public byte[] Data { get; set; } } }
using Exiled.Events.EventArgs; using System.Linq; namespace TabletTesla.Handlers { class Player { public void OnTeslaGate(TriggeringTeslaEventArgs ev) { if (ev.Player.Inventory.items.Any(item => item.id == ItemType.WeaponManagerTablet)) { ev.IsTriggerable = false; } } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class MonsterController : MonoBehaviour { [HideInInspector] public static MonsterController instance; public List<GameObject> Monsters; public Transform parentTransform; public GameObject monsterPrefab; void Awake() { instance = this; } public void Initialize() { DestroyOldMonsters(); GenerateMonsters(); } private void DestroyOldMonsters() { foreach (var monster in Monsters) { Destroy(monster); } } private void GenerateMonsters() { Monsters = new List<GameObject>(); var openCells = LevelController.instance.Map.GetAllCells().Where(c => c.IsWalkable).ToArray(); for (var i = 0; i < 10; i++) { var walkable = openCells[Random.Range(0, openCells.Length)]; var monster = Instantiate(monsterPrefab, new Vector3(walkable.X, 0, walkable.Y), Quaternion.identity); monster.name = $"{monster.name} - Level {GameController.level}"; monster.transform.SetParent(parentTransform); Monsters.Add(monster); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Azure.Storage.Blobs.Models; using Azure.Storage.Blobs.Specialized; using Microsoft.Health.Fhir.Anonymizer.Core; namespace Microsoft.Health.Fhir.Anonymizer.AzureDataFactoryPipeline.src { public class FhirBlobConsumer : IFhirDataConsumer<string> { private static byte[] _newLine = Encoding.UTF8.GetBytes("\r\n"); private BlockBlobClient _blobClient; private List<Task> _runningTasks; private List<string> _blockIds; private MemoryStream _currentStream; public FhirBlobConsumer(BlockBlobClient blobClient) { _blobClient = blobClient; _runningTasks = new List<Task>(); _blockIds = new List<string>(); _currentStream = new MemoryStream(); } public int UploadBlockThreshold { get; set; } = FhirAzureConstants.DefaultUploadBlockThreshold; public int ConcurrentCount { get; set; } = FhirAzureConstants.DefaultConcurrentCount; public IProgress<long> ProgressHandler { set; private get; } = null; public int BlockUploadTimeoutInSeconds { get; set; } = FhirAzureConstants.DefaultBlockUploadTimeoutInSeconds; public int BlockUploadTimeoutRetryCount { get; set; } = FhirAzureConstants.DefaultBlockUploadTimeoutRetryCount; public async Task<int> ConsumeAsync(IEnumerable<string> data) { int result = 0; foreach (string item in data) { byte[] byteData = Encoding.UTF8.GetBytes(item); await _currentStream.WriteAsync(byteData, 0, byteData.Length).ConfigureAwait(false); await _currentStream.WriteAsync(_newLine, 0, _newLine.Length).ConfigureAwait(false); if (_currentStream.Length >= UploadBlockThreshold) { await AddCurrentStreamToUploadTaskListAsync().ConfigureAwait(false); } result++; } return result; } public async Task CompleteAsync() { if (_currentStream.Length > 0) { await AddCurrentStreamToUploadTaskListAsync().ConfigureAwait(false); } await Task.WhenAll(_runningTasks).ConfigureAwait(false); foreach (var task in _runningTasks) { // If there's any error throw exception here. await task.ConfigureAwait(false); } await _blobClient.CommitBlockListAsync(_blockIds).ConfigureAwait(false); } private async Task AddCurrentStreamToUploadTaskListAsync() { while (_runningTasks.Count > ConcurrentCount) { await Task.WhenAny(_runningTasks).ConfigureAwait(false); foreach (var task in _runningTasks.FindAll(t => t.IsCompleted)) { // If there's any error throw exception here. await task.ConfigureAwait(false); } _runningTasks.RemoveAll(t => t.IsCompleted); } string blockId = GenerateBlockId(_blockIds.Count); _runningTasks.Add(StageBlockAsync(blockId, _currentStream)); _blockIds.Add(blockId); _currentStream = new MemoryStream(); } private async Task StageBlockAsync( string blockId, MemoryStream stream) { await OperationExecutionHelper.InvokeWithTimeoutRetryAsync<BlockInfo>( async () => { using MemoryStream uploadStream = new MemoryStream(); stream.Position = 0; await stream.CopyToAsync(uploadStream).ConfigureAwait(false); uploadStream.Position = 0; return await _blobClient.StageBlockAsync(blockId, uploadStream).ConfigureAwait(false); }, TimeSpan.FromSeconds(BlockUploadTimeoutInSeconds), BlockUploadTimeoutRetryCount, isRetrableException: OperationExecutionHelper.IsRetrableException).ConfigureAwait(false); ProgressHandler?.Report(stream.Length); await stream.DisposeAsync().ConfigureAwait(false); } private static string GenerateBlockId(int index) { byte[] id = new byte[48]; // 48 raw bytes => 64 byte string once Base64 encoded BitConverter.GetBytes(index).CopyTo(id, 0); return Convert.ToBase64String(id); } } }
using System; using Xamarin.Forms; namespace SimpleMasterDetailTabbed { public class AboutView : BaseView { public AboutView () { this.Content = new StackLayout() { Orientation = StackOrientation.Vertical, Children = { new Label { Text = "About View!", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, }, new Button { Text = "Show FeedbackView", Command = new Command(p => { // Solution #1 // MainView mv = new MainView(); // mv.Detail = new NavigationPage(new FeedbackView()); // // App.Current.MainPage = mv; // Solution #2 FeedbackView fv = new FeedbackView(); MessagingCenter.Send<FeedbackView> (fv, "OpenInDetail"); }) } } }; } } }
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace Prolliance.Membership.ServicePoint.Mgr.Views { public partial class UserDetail { /// <summary> /// aspForm 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm aspForm; /// <summary> /// app 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl app; /// <summary> /// role 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl role; /// <summary> /// ctl_Account 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ctl_Account; /// <summary> /// ctl_Name 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ctl_Name; /// <summary> /// ctl_Email 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ctl_Email; /// <summary> /// positionList 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.CheckBoxList positionList; /// <summary> /// ctl_MobilePhone 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ctl_MobilePhone; /// <summary> /// ctl_OfficePhone 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox ctl_OfficePhone; /// <summary> /// ctl_IsActive 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.RadioButtonList ctl_IsActive; /// <summary> /// tableArea 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl tableArea; /// <summary> /// dataList 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Repeater dataList; /// <summary> /// save 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button save; } }
namespace DaoGen_Tool { partial class Form1 { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.gbxDataProviders = new System.Windows.Forms.GroupBox(); this.rbnHiRDB = new System.Windows.Forms.RadioButton(); this.rbnODB = new System.Windows.Forms.RadioButton(); this.rbnOLE = new System.Windows.Forms.RadioButton(); this.rbnPstgrs = new System.Windows.Forms.RadioButton(); this.rbnMySQL = new System.Windows.Forms.RadioButton(); this.rbnDB2 = new System.Windows.Forms.RadioButton(); this.rbnODP = new System.Windows.Forms.RadioButton(); this.rbnSQL = new System.Windows.Forms.RadioButton(); this.lblConnectionString = new System.Windows.Forms.Label(); this.txtConnString = new System.Windows.Forms.TextBox(); this.lbxTables = new System.Windows.Forms.ListBox(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.cbxDebug = new System.Windows.Forms.CheckBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.dataGridView2 = new System.Windows.Forms.DataGridView(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.dataGridView3 = new System.Windows.Forms.DataGridView(); this.gbxSchemaDetails = new System.Windows.Forms.GroupBox(); this.btnGetSchemaInfo = new System.Windows.Forms.Button(); this.cmbSchemaInfo = new System.Windows.Forms.ComboBox(); this.lblSchemaInfo = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btnSetPrimaryKey = new System.Windows.Forms.Button(); this.btnLoadColumn = new System.Windows.Forms.Button(); this.btnDelTable = new System.Windows.Forms.Button(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.cmbEncoding = new System.Windows.Forms.ComboBox(); this.btnDaoDefinitionGen = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.btnListTable = new System.Windows.Forms.Button(); this.btnDaoAndSqlGen = new System.Windows.Forms.Button(); this.lblStep1 = new System.Windows.Forms.Label(); this.lnkHelp = new System.Windows.Forms.LinkLabel(); this.gbxDataProviders.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit(); this.tabPage3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).BeginInit(); this.gbxSchemaDetails.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.SuspendLayout(); // // gbxDataProviders // resources.ApplyResources(this.gbxDataProviders, "gbxDataProviders"); this.gbxDataProviders.Controls.Add(this.rbnHiRDB); this.gbxDataProviders.Controls.Add(this.rbnODB); this.gbxDataProviders.Controls.Add(this.rbnOLE); this.gbxDataProviders.Controls.Add(this.rbnPstgrs); this.gbxDataProviders.Controls.Add(this.rbnMySQL); this.gbxDataProviders.Controls.Add(this.rbnDB2); this.gbxDataProviders.Controls.Add(this.rbnODP); this.gbxDataProviders.Controls.Add(this.rbnSQL); this.gbxDataProviders.ForeColor = System.Drawing.SystemColors.ControlText; this.gbxDataProviders.Name = "gbxDataProviders"; this.gbxDataProviders.TabStop = false; // // rbnHiRDB // resources.ApplyResources(this.rbnHiRDB, "rbnHiRDB"); this.rbnHiRDB.Name = "rbnHiRDB"; this.rbnHiRDB.TabStop = true; this.rbnHiRDB.UseVisualStyleBackColor = true; this.rbnHiRDB.CheckedChanged += new System.EventHandler(this.rbnHiRDB_CheckedChanged); // // rbnODB // resources.ApplyResources(this.rbnODB, "rbnODB"); this.rbnODB.Name = "rbnODB"; this.rbnODB.TabStop = true; this.rbnODB.UseVisualStyleBackColor = true; this.rbnODB.CheckedChanged += new System.EventHandler(this.rbnODB_CheckedChanged); // // rbnOLE // resources.ApplyResources(this.rbnOLE, "rbnOLE"); this.rbnOLE.Name = "rbnOLE"; this.rbnOLE.TabStop = true; this.rbnOLE.UseVisualStyleBackColor = true; this.rbnOLE.CheckedChanged += new System.EventHandler(this.rbnOLE_CheckedChanged); // // rbnPstgrs // resources.ApplyResources(this.rbnPstgrs, "rbnPstgrs"); this.rbnPstgrs.Name = "rbnPstgrs"; this.rbnPstgrs.TabStop = true; this.rbnPstgrs.UseVisualStyleBackColor = true; this.rbnPstgrs.CheckedChanged += new System.EventHandler(this.rbnPstgrs_CheckedChanged); // // rbnMySQL // resources.ApplyResources(this.rbnMySQL, "rbnMySQL"); this.rbnMySQL.Name = "rbnMySQL"; this.rbnMySQL.TabStop = true; this.rbnMySQL.UseVisualStyleBackColor = true; this.rbnMySQL.CheckedChanged += new System.EventHandler(this.rdbMySQL_CheckedChanged); // // rbnDB2 // resources.ApplyResources(this.rbnDB2, "rbnDB2"); this.rbnDB2.Name = "rbnDB2"; this.rbnDB2.TabStop = true; this.rbnDB2.UseVisualStyleBackColor = true; this.rbnDB2.CheckedChanged += new System.EventHandler(this.rdbDB2_CheckedChanged); // // rbnODP // resources.ApplyResources(this.rbnODP, "rbnODP"); this.rbnODP.Name = "rbnODP"; this.rbnODP.TabStop = true; this.rbnODP.UseVisualStyleBackColor = true; this.rbnODP.CheckedChanged += new System.EventHandler(this.rdbODP_CheckedChanged); // // rbnSQL // resources.ApplyResources(this.rbnSQL, "rbnSQL"); this.rbnSQL.Name = "rbnSQL"; this.rbnSQL.UseVisualStyleBackColor = true; this.rbnSQL.CheckedChanged += new System.EventHandler(this.rdbSQL_CheckedChanged); // // lblConnectionString // resources.ApplyResources(this.lblConnectionString, "lblConnectionString"); this.lblConnectionString.ForeColor = System.Drawing.SystemColors.ControlText; this.lblConnectionString.Name = "lblConnectionString"; // // txtConnString // resources.ApplyResources(this.txtConnString, "txtConnString"); this.txtConnString.Name = "txtConnString"; // // lbxTables // resources.ApplyResources(this.lbxTables, "lbxTables"); this.lbxTables.FormattingEnabled = true; this.lbxTables.Name = "lbxTables"; this.lbxTables.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; // // dataGridView1 // resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowTemplate.Height = 21; this.dataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView_DataError); // // cbxDebug // resources.ApplyResources(this.cbxDebug, "cbxDebug"); this.cbxDebug.Name = "cbxDebug"; this.cbxDebug.UseVisualStyleBackColor = true; // // tabControl1 // resources.ApplyResources(this.tabControl1, "tabControl1"); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; // // tabPage1 // resources.ApplyResources(this.tabPage1, "tabPage1"); this.tabPage1.Controls.Add(this.dataGridView1); this.tabPage1.Name = "tabPage1"; this.tabPage1.UseVisualStyleBackColor = true; // // tabPage2 // resources.ApplyResources(this.tabPage2, "tabPage2"); this.tabPage2.Controls.Add(this.dataGridView2); this.tabPage2.Name = "tabPage2"; this.tabPage2.UseVisualStyleBackColor = true; // // dataGridView2 // resources.ApplyResources(this.dataGridView2, "dataGridView2"); this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView2.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView2.Name = "dataGridView2"; this.dataGridView2.RowTemplate.Height = 21; this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView_DataError); // // tabPage3 // resources.ApplyResources(this.tabPage3, "tabPage3"); this.tabPage3.Controls.Add(this.dataGridView3); this.tabPage3.Name = "tabPage3"; this.tabPage3.UseVisualStyleBackColor = true; // // dataGridView3 // resources.ApplyResources(this.dataGridView3, "dataGridView3"); this.dataGridView3.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView3.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView3.Name = "dataGridView3"; this.dataGridView3.RowTemplate.Height = 21; this.dataGridView3.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView_DataError); // // gbxSchemaDetails // resources.ApplyResources(this.gbxSchemaDetails, "gbxSchemaDetails"); this.gbxSchemaDetails.Controls.Add(this.btnGetSchemaInfo); this.gbxSchemaDetails.Controls.Add(this.cmbSchemaInfo); this.gbxSchemaDetails.Controls.Add(this.lblSchemaInfo); this.gbxSchemaDetails.Name = "gbxSchemaDetails"; this.gbxSchemaDetails.TabStop = false; // // btnGetSchemaInfo // resources.ApplyResources(this.btnGetSchemaInfo, "btnGetSchemaInfo"); this.btnGetSchemaInfo.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(91)))), ((int)(((byte)(155)))), ((int)(((byte)(213))))); this.btnGetSchemaInfo.FlatAppearance.BorderSize = 0; this.btnGetSchemaInfo.ForeColor = System.Drawing.Color.White; this.btnGetSchemaInfo.Name = "btnGetSchemaInfo"; this.btnGetSchemaInfo.UseVisualStyleBackColor = false; this.btnGetSchemaInfo.EnabledChanged += new System.EventHandler(this.btnLoadColumn_EnabledChanged); this.btnGetSchemaInfo.Click += new System.EventHandler(this.btnGetSchemaInfo_Click); // // cmbSchemaInfo // resources.ApplyResources(this.cmbSchemaInfo, "cmbSchemaInfo"); this.cmbSchemaInfo.FormattingEnabled = true; this.cmbSchemaInfo.Name = "cmbSchemaInfo"; // // lblSchemaInfo // resources.ApplyResources(this.lblSchemaInfo, "lblSchemaInfo"); this.lblSchemaInfo.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSchemaInfo.Name = "lblSchemaInfo"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.ForeColor = System.Drawing.SystemColors.ControlText; this.label4.Name = "label4"; // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.btnSetPrimaryKey); this.groupBox1.Controls.Add(this.btnLoadColumn); this.groupBox1.Controls.Add(this.btnDelTable); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.label5); this.groupBox1.ForeColor = System.Drawing.SystemColors.ControlText; this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // btnSetPrimaryKey // resources.ApplyResources(this.btnSetPrimaryKey, "btnSetPrimaryKey"); this.btnSetPrimaryKey.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(202)))), ((int)(((byte)(207))))); this.btnSetPrimaryKey.FlatAppearance.BorderSize = 0; this.btnSetPrimaryKey.ForeColor = System.Drawing.Color.White; this.btnSetPrimaryKey.Name = "btnSetPrimaryKey"; this.btnSetPrimaryKey.UseVisualStyleBackColor = false; this.btnSetPrimaryKey.EnabledChanged += new System.EventHandler(this.btnLoadColumn_EnabledChanged); this.btnSetPrimaryKey.Click += new System.EventHandler(this.btnSetPrimaryKey_Click); // // btnLoadColumn // resources.ApplyResources(this.btnLoadColumn, "btnLoadColumn"); this.btnLoadColumn.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(91)))), ((int)(((byte)(155)))), ((int)(((byte)(213))))); this.btnLoadColumn.FlatAppearance.BorderSize = 0; this.btnLoadColumn.ForeColor = System.Drawing.Color.White; this.btnLoadColumn.Name = "btnLoadColumn"; this.btnLoadColumn.UseVisualStyleBackColor = false; this.btnLoadColumn.EnabledChanged += new System.EventHandler(this.btnLoadColumn_EnabledChanged); this.btnLoadColumn.Click += new System.EventHandler(this.btnLoadColumn_Click); // // btnDelTable // resources.ApplyResources(this.btnDelTable, "btnDelTable"); this.btnDelTable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(91)))), ((int)(((byte)(155)))), ((int)(((byte)(213))))); this.btnDelTable.FlatAppearance.BorderColor = System.Drawing.Color.White; this.btnDelTable.FlatAppearance.BorderSize = 0; this.btnDelTable.ForeColor = System.Drawing.Color.White; this.btnDelTable.Name = "btnDelTable"; this.btnDelTable.UseVisualStyleBackColor = false; this.btnDelTable.EnabledChanged += new System.EventHandler(this.btnLoadColumn_EnabledChanged); this.btnDelTable.Click += new System.EventHandler(this.btnDelTable_Click); // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // cmbEncoding // resources.ApplyResources(this.cmbEncoding, "cmbEncoding"); this.cmbEncoding.FormattingEnabled = true; this.cmbEncoding.Name = "cmbEncoding"; // // btnDaoDefinitionGen // resources.ApplyResources(this.btnDaoDefinitionGen, "btnDaoDefinitionGen"); this.btnDaoDefinitionGen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(34)))), ((int)(((byte)(42)))), ((int)(((byte)(53))))); this.btnDaoDefinitionGen.FlatAppearance.BorderSize = 0; this.btnDaoDefinitionGen.ForeColor = System.Drawing.Color.White; this.btnDaoDefinitionGen.Name = "btnDaoDefinitionGen"; this.btnDaoDefinitionGen.UseVisualStyleBackColor = false; this.btnDaoDefinitionGen.EnabledChanged += new System.EventHandler(this.btnDaoDefinitionGen_EnabledChanged); this.btnDaoDefinitionGen.Click += new System.EventHandler(this.btnDaoDefinitionGen_Click); // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // pictureBox2 // resources.ApplyResources(this.pictureBox2, "pictureBox2"); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.TabStop = false; // // btnListTable // resources.ApplyResources(this.btnListTable, "btnListTable"); this.btnListTable.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(34)))), ((int)(((byte)(42)))), ((int)(((byte)(53))))); this.btnListTable.ForeColor = System.Drawing.Color.White; this.btnListTable.Name = "btnListTable"; this.btnListTable.UseVisualStyleBackColor = false; this.btnListTable.Click += new System.EventHandler(this.btnListTable_Click); // // btnDaoAndSqlGen // resources.ApplyResources(this.btnDaoAndSqlGen, "btnDaoAndSqlGen"); this.btnDaoAndSqlGen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(34)))), ((int)(((byte)(42)))), ((int)(((byte)(53))))); this.btnDaoAndSqlGen.ForeColor = System.Drawing.Color.White; this.btnDaoAndSqlGen.Name = "btnDaoAndSqlGen"; this.btnDaoAndSqlGen.UseVisualStyleBackColor = false; this.btnDaoAndSqlGen.Click += new System.EventHandler(this.btnDaoAndSqlGen_Click); // // lblStep1 // resources.ApplyResources(this.lblStep1, "lblStep1"); this.lblStep1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(101)))), ((int)(((byte)(123)))), ((int)(((byte)(155))))); this.lblStep1.ForeColor = System.Drawing.Color.White; this.lblStep1.Name = "lblStep1"; // // lnkHelp // resources.ApplyResources(this.lnkHelp, "lnkHelp"); this.lnkHelp.ActiveLinkColor = System.Drawing.SystemColors.Highlight; this.lnkHelp.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(101)))), ((int)(((byte)(123)))), ((int)(((byte)(155))))); this.lnkHelp.ForeColor = System.Drawing.Color.White; this.lnkHelp.LinkColor = System.Drawing.Color.White; this.lnkHelp.Name = "lnkHelp"; this.lnkHelp.TabStop = true; this.lnkHelp.VisitedLinkColor = System.Drawing.SystemColors.Highlight; this.lnkHelp.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkHelp_LinkClicked); // // Form1 // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lnkHelp); this.Controls.Add(this.lblStep1); this.Controls.Add(this.btnDaoAndSqlGen); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.btnDaoDefinitionGen); this.Controls.Add(this.cmbEncoding); this.Controls.Add(this.groupBox1); this.Controls.Add(this.label4); this.Controls.Add(this.btnListTable); this.Controls.Add(this.gbxSchemaDetails); this.Controls.Add(this.gbxDataProviders); this.Controls.Add(this.tabControl1); this.Controls.Add(this.cbxDebug); this.Controls.Add(this.lbxTables); this.Controls.Add(this.txtConnString); this.Controls.Add(this.lblConnectionString); this.ForeColor = System.Drawing.SystemColors.ControlDark; this.MaximizeBox = false; this.Name = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.gbxDataProviders.ResumeLayout(false); this.gbxDataProviders.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit(); this.tabPage3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView3)).EndInit(); this.gbxSchemaDetails.ResumeLayout(false); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox gbxDataProviders; private System.Windows.Forms.RadioButton rbnDB2; private System.Windows.Forms.RadioButton rbnODP; private System.Windows.Forms.RadioButton rbnSQL; private System.Windows.Forms.Label lblConnectionString; private System.Windows.Forms.TextBox txtConnString; private System.Windows.Forms.ListBox lbxTables; private System.Windows.Forms.RadioButton rbnMySQL; private System.Windows.Forms.RadioButton rbnPstgrs; private System.Windows.Forms.RadioButton rbnODB; private System.Windows.Forms.RadioButton rbnOLE; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.CheckBox cbxDebug; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.DataGridView dataGridView2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.DataGridView dataGridView3; private System.Windows.Forms.RadioButton rbnHiRDB; private System.Windows.Forms.GroupBox gbxSchemaDetails; private System.Windows.Forms.ComboBox cmbSchemaInfo; private System.Windows.Forms.Label lblSchemaInfo; private System.Windows.Forms.Button btnGetSchemaInfo; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cmbEncoding; private System.Windows.Forms.Button btnDaoDefinitionGen; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Button btnListTable; private System.Windows.Forms.Button btnLoadColumn; private System.Windows.Forms.Button btnSetPrimaryKey; private System.Windows.Forms.Button btnDaoAndSqlGen; private System.Windows.Forms.Button btnDelTable; private System.Windows.Forms.Label lblStep1; private System.Windows.Forms.LinkLabel lnkHelp; } }
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using System; using Confluent.Kafka; using Microsoft.Extensions.Logging; namespace Silverback.Messaging.KafkaEvents { internal static class ConfluentSysLogLevelExtensions { public static LogLevel ToLogLevel(this SyslogLevel syslogLevel) => syslogLevel switch { SyslogLevel.Emergency => LogLevel.Critical, SyslogLevel.Alert => LogLevel.Critical, SyslogLevel.Critical => LogLevel.Critical, SyslogLevel.Error => LogLevel.Error, SyslogLevel.Warning => LogLevel.Warning, SyslogLevel.Notice => LogLevel.Information, SyslogLevel.Info => LogLevel.Information, SyslogLevel.Debug => LogLevel.Debug, _ => throw new ArgumentOutOfRangeException(nameof(syslogLevel), syslogLevel, null) }; } }
using Microsoft.EntityFrameworkCore; using MosqueManagement.Core.Models; using System; using System.Collections.Generic; using System.Text; namespace MosqueManagement.Infrastructure.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Member> Members { get; set; } public DbSet<Address> Addresses { get; set; } public DbSet<MemberType> MemberTypes { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { //modelBuilder.Entity<Member>(entity => //{ // entity.Property(en => en.Id).IsRequired(); // entity.Property(en => en.Address).IsRequired(); //}); modelBuilder.Entity<MemberType>(entity => { entity.Property(e => e.Description).HasMaxLength(255); }); modelBuilder.Entity<Address>(entity => { entity.Property(e => e.Address1).IsRequired(); }); } } }
using System.Collections.Generic; namespace WordStat.Core { public interface IWordBreaker { int MinWordLength { get; set; } IEnumerable<string> GetWords(string phrase); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; //WOC using Woc.Book.Setting; using Woc.Book.Setting.BusinessEntity; using Woc.Book.Base.Presenter; using Woc.Book.Base.BusinessEntity; namespace Woc.Book.Setting.Presenter { public class SettingPresenter: IAdminPresenter { IAdminPresenter iAdminPresenter; SettingController settingController; public SettingPresenter() { } public SettingPresenter(IAdminPresenter iAdmin) { iAdminPresenter = iAdmin; } public String GetSettingValue(String settingCode) { settingController = new SettingController(); return settingController.GetSettingValue(settingCode); } public List<DropDowns> GetDropdownValues(String settingCode) { settingController = new SettingController(); return settingController.GetDropdownValues(settingCode); } public String SaveData(IAdminEntity iAdminEntity) { settingController = new SettingController(); return settingController.SaveData(iAdminEntity); } public List<Settings> SearchData(IAdminEntity iAdminEntity) { settingController = new SettingController(); return settingController.SearchData(iAdminEntity); } public Settings GetUpdateData(Guid id) { settingController = new SettingController(); return settingController.GetUpdateData(id); } public string UpdateData(IAdminEntity iAdminEntity) { settingController = new SettingController(); return settingController.UpdateData(iAdminEntity); } public void DataBindings() { iAdminPresenter.DataBindings(); } public void SaveData() { iAdminPresenter.SaveData(); } public void ClearControl() { iAdminPresenter.ClearControl(); } public void SearchData() { iAdminPresenter.SearchData(); } public void GetData(Guid Id) { iAdminPresenter.GetData(Id); } public void UpdateData() { iAdminPresenter.UpdateData(); } public void DeleteData() { iAdminPresenter.DeleteData(); } } }
using A5Soft.CARMA.Domain; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace A5Soft.CARMA.Application.DataPortal { /// <summary> /// Null implementation of IRemoteClientPortal for use by DI whn no remote server is required. /// </summary> [DefaultServiceImplementation(typeof(IDataPortalProxy))] public class LocalDataPortalProxy : IDataPortalProxy { /// <inheritdoc cref="IDataPortalProxy.IsRemote" /> public bool IsRemote => false; public Task<Stream> DownloadAsync(string request, CancellationToken ct = default) { throw new NotSupportedException("Local data portal cannot be invoked."); } /// <inheritdoc cref="IDataPortalProxy.GetResponseAsync" /> public Task<string> GetResponseAsync(string request, CancellationToken ct = default) { throw new NotSupportedException("Local data portal cannot be invoked."); } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DailyTimeScheduler.Model { public class TimeBlock { /// <summary> /// PK Unique TimeBlock Number in DB /// </summary> [Key] public int No { get; set; } /// <summary> /// Intial schedule time. /// DateTime.Ticks value for 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long IntialUTCTime { get; set; } /// <summary> /// End DateTime of repeating if 0 time block not repeating. /// DateTime.Ticks value for 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long EndUTCTime { get; set; } /// <summary> /// Size of this time block; Range of this time block /// DateTime.Ticks value For 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long BlockSize { get; set; } /// <summary> /// Repeat period Of this Time block, 0 if this schedule is not repeating /// DateTime.Ticks value For 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long RepeatPeriod { get; set; } /// <summary> /// Is timeblock is on allday colum /// </summary> [Required] public bool IsAllDay { get; set; } /// <summary> /// Schedule Number foregin /// </summary> [Required] public int ScheduleNo { get; set; } [ForeignKey("ScheduleNo")] public virtual Schedule Schedule { get; set; } } }
using Assets.Scripts.Game.FishGame.Fishs; using UnityEngine; namespace Assets.Scripts.Game.FishGame.Common.core { public class RandomOddsNum : MonoBehaviour { public int MinOdds = 2; public int MaxOdds = 101; // Use this for initialization void Start () { Fish f = GetComponent<Fish>(); f.Odds = Random.Range(MinOdds, MaxOdds); } } }
using System; using System.ComponentModel; namespace SuperMap.WinRT.Core { /// <summary> /// <para>${core_CRS_Title}</para> /// <para>${core_CRS_Description}</para> /// </summary> public class CoordinateReferenceSystem : IEquatable<CoordinateReferenceSystem> { /// <overloads>${core_CRS_constructor_overloads}</overloads> /// <summary>${core_CRS_constructor_None_D}</summary> public CoordinateReferenceSystem() : this(0) { } /// <summary>${core_CRS_constructor_Int_D}</summary> /// <param name="wkid">${core_CRS_constructor_Int_param_WKID}</param> public CoordinateReferenceSystem(int wkid) : this(wkid, Unit.Undefined) { } /// <summary>${core_CRS_constructor_Int_Unit_D}</summary> /// <param name="wkid">${core_CRS_constructor_Int_param_WKID}</param> /// <param name="unit">${core_CRS_constructor_Int_Unit_param_unit}</param> public CoordinateReferenceSystem(int wkid, Unit unit) : this(wkid, unit, 6378137) { } /// <summary> /// ${core_CRS_constructor_Int_Unit_double_D} /// </summary> /// <param name="wkid">${core_CRS_constructor_Int_param_WKID}</param> /// <param name="unit">${core_CRS_constructor_Int_Unit_param_unit}</param> /// <param name="datumAxis">${core_CRS_constructor_Int_Unit_param_datumAxis}</param> public CoordinateReferenceSystem(int wkid, Unit unit, double datumAxis) { WKID = wkid; Unit = unit; DatumAxis = datumAxis; } /// <summary>${core_CRS_method_Clone_D}</summary> /// <returns>${core_CRS_method_Clone_return}</returns> /// <remarks>${core_CRS_method_Clone_remarks}</remarks> public CoordinateReferenceSystem Clone() { CoordinateReferenceSystem reference = base.MemberwiseClone() as CoordinateReferenceSystem; reference.WKID = WKID; reference.Unit = Unit; reference.DatumAxis = DatumAxis; return reference; } /// <summary>${core_CRS_method_equals_CRS_D}</summary> /// <overloads>${core_CRS_method_equals_overloads}</overloads> /// <returns>${core_CRS_method_equals_CRS_return}</returns> /// <param name="crs1">${core_CRS_method_equals_CRS_param_crs}</param> /// <param name="crs2">${core_CRS_method_equals_CRS_param_crs}</param> /// <param name="ignoreNull">${core_CRS_method_equals_CRS_param_ignoreNull}</param> public static bool Equals(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2, bool ignoreNull) { if (crs1 == null || crs2 == null) { return ignoreNull; } if (IsWebMercatorWKID(crs1.WKID) && IsWebMercatorWKID(crs2.WKID)) { return true; } return (crs1.WKID == crs2.WKID); } internal static bool IsWebMercatorWKID(int wkid) { return (wkid == 3857) || (wkid == 900913) || (wkid == 102113) || (wkid == 102100); } /// <summary>${core_CRS_method_equals_D}</summary> /// <returns>${core_CRS_method_equals_return}</returns> /// <param name="other">${core_CRS_method_equals_param_other}</param> public bool Equals(CoordinateReferenceSystem other) { return Equals(this, other, false); }//忽略单位 /// <summary>${core_CRS_attribute_WKID_D}</summary> public int WKID { get; set; } /// <summary>${core_CRS_attribute_uint_D}</summary> public Unit Unit { get; set; } public double DatumAxis { get; set; } } }
using AutoMapper; namespace app.Profiles { public class PayProfile : Profile { public PayProfile() { SourceMemberNamingConvention = new PascalCaseNamingConvention(); DestinationMemberNamingConvention = new PascalCaseNamingConvention(); CreateMap<Entities.Pay, app.Paycheck>(); CreateMap<Entities.Earnings, app.Earnings>(); CreateMap<Entities.Deductions, app.Deductions>(); CreateMap<Entities.AmountType, app.PayAmount>(); CreateMap<Entities.PaymentMode, app.PaymentMode>() .ForMember(destination => destination.Id, opt => opt.MapFrom(src => src.PaymentId)); } } }
using System.Collections.Generic; using ResourceServer.Model; using Microsoft.AspNetCore.Mvc; namespace ResourceServer.Repositories; public interface IDataEventRecordRepository { void Delete(long id); DataEventRecord Get(long id); List<DataEventRecord> GetAll(); void Post(DataEventRecord dataEventRecord); void Put(long id, [FromBody] DataEventRecord dataEventRecord); }
using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using GitMind.Utils.UI.VirtualCanvas; using UserControl = System.Windows.Controls.UserControl; namespace GitMind.RepositoryViews { /// <summary> /// Interaction logic for RepositoryView.xaml /// </summary> public partial class RepositoryView : UserControl { private RepositoryViewModel viewModel; public RepositoryView() { InitializeComponent(); } private void ZoomableCanvas_Loaded(object sender, RoutedEventArgs e) { viewModel = (RepositoryViewModel)DataContext; viewModel.Canvas = (ZoomableCanvas)sender; viewModel.ListBox = ItemsListBox; ItemsListBox.Focus(); } protected override void OnPreviewMouseUp(MouseButtonEventArgs e) { // Log.Debug($"Canvas offset {canvas.Offset}"); if (e.ChangedButton == MouseButton.Left) { Point viewPoint = e.GetPosition(ItemsListBox); Point position = new Point(viewPoint.X + viewModel.Canvas.Offset.X, viewPoint.Y + viewModel.Canvas.Offset.Y); viewModel.Clicked(position); } base.OnPreviewMouseUp(e); } private void MouseDobleClick(object sender, MouseButtonEventArgs e) { Point viewPoint = e.GetPosition(ItemsListBox); if (viewPoint.X > viewModel.GraphWidth) { viewModel.ToggleCommitDetails(); } } private void MouseEntering(object sender, MouseEventArgs e) { ListBoxItem item = sender as ListBoxItem; if (item != null) { Point viewPoint = e.GetPosition(ItemsListBox); BranchViewModel branch = item.Content as BranchViewModel; if (branch != null) { viewModel.MouseEnterBranch(branch, viewPoint); } CommitViewModel commit = item.Content as CommitViewModel; if (commit != null) { if (viewPoint.X < viewModel.GraphWidth) { branch = viewModel.Branches.FirstOrDefault(b => b.Branch == commit.Commit.Branch); if (branch != null) { viewModel.MouseEnterBranch(branch, viewPoint); } } if (viewPoint.X > viewModel.GraphWidth) { branch = viewModel.Branches.FirstOrDefault(b => b.Branch == commit.Commit.Branch); if (branch != null) { viewModel.MouseLeaveBranch(branch); } } } } } private void MouseLeaving(object sender, MouseEventArgs e) { ListBoxItem item = sender as ListBoxItem; if (item != null) { BranchViewModel branch = item.Content as BranchViewModel; if (branch != null) { viewModel.MouseLeaveBranch(branch); } CommitViewModel commit = item.Content as CommitViewModel; if (commit != null) { Point viewPoint = e.GetPosition(ItemsListBox); if (viewPoint.X < viewModel.GraphWidth) { branch = viewModel.Branches.FirstOrDefault(b => b.Branch == commit.Commit.Branch); if (branch != null) { viewModel.MouseLeaveBranch(branch); } } } } } private void EventMouseUp(object sender, MouseButtonEventArgs e) { ListBoxItem item = sender as ListBoxItem; if (item != null) { BranchViewModel branch = item.Content as BranchViewModel; if (branch != null) { } } } private void OnManipulationBoundaryFeedback( object sender, ManipulationBoundaryFeedbackEventArgs e) { // Prevent the window to slightly move when its edge is encountered using touch scrolling. e.Handled = true; } } }
//----------------------------------------------------------------------- // <copyright file="IXmlSerializationTag.cs" company="Sphere 10 Software"> // // Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com) // // Distributed under the MIT software license, see the accompanying file // LICENSE or visit http://www.opensource.org/licenses/mit-license.php. // // <author>Herman Schoenfeld</author> // <date>2018</date> // </copyright> //----------------------------------------------------------------------- // ----------------------------------------------------------------------------------- // Use it as you please, but keep this header. // Author : Marcus Deecke, 2006 // Web : www.yaowi.com // Email : code@yaowi.com // http://www.codeproject.com/KB/XML/deepserializer.aspx // ----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace Sphere10.Framework { public interface IXmlSerializationTag { string ASSEMBLY_TAG { get; } string INDEX_TAG { get; } string ITEM_TAG { get; } string ITEMS_TAG { get; } string NAME_ATT_KEY_TAG { get; } string NAME_ATT_VALUE_TAG { get; } string NAME_TAG { get; } string OBJECT_TAG { get; } string PROPERTIES_TAG { get; } string PROPERTY_TAG { get; } string TYPE_DICTIONARY_TAG { get; } string TYPE_TAG { get; } string GENERIC_TYPE_ARGUMENTS_TAG { get; } string CONSTRUCTOR_TAG { get;} string BINARY_DATA_TAG { get;} } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EmailTemplate.Wrapping { public enum WordTokenType { None, Text, Space, } public class WordToken { public string Text { get; set; } public WordTokenType Type { get; set; } } public class WordReader : IDisposable { protected internal enum WordReaderState { Start, Text, Space, Finished } public bool BreakOnHyphens { get; set; } private WordReaderState _currentState = WordReaderState.Start; private WordToken _current; private string _text; private WordTokenType _type; private readonly TextReader _reader; private bool _isEndOfFile; private char[] _chars; private int _charPos; private int _charsUsed; private int _lineStartPos; protected WordReaderState CurrentState { get { return _currentState; } } public WordToken Current { get { return _current; } } public string Text { get { return _text; } } public WordTokenType Type { get { return _type; } } public WordReader(TextReader reader) { _reader = reader; _currentState = WordReaderState.Start; _type = WordTokenType.None; _text = null; _chars = new char[1025]; } public bool Read() { if (!ReadInternal()) { SetToken(WordTokenType.None); return false; } return true; } private bool ReadInternal() { while (true) { switch (_currentState) { case WordReaderState.Start: case WordReaderState.Text: case WordReaderState.Space: return ReadNextChunk(); case WordReaderState.Finished: return false; default: break; } } } private bool ReadNextChunk() { ShiftBufferIfNeeded(); if (_isEndOfFile) return false; char currentChar = _chars[_charPos]; if (currentChar == '\0') ReadData(false); if (IsBreakChar(currentChar)) { string spaces = ReadSpaces(); this.SetToken(spaces, WordTokenType.Space); return true; } else { string text = ReadText(); this.SetToken(text, WordTokenType.Text); return true; } } private string ReadText() { int initialPosition = _charPos; int endPosition; while(true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') // need to read more data { if (ReadData(true) == 0) { break; } } bool isBreakChar = IsBreakChar(currentChar); if (BreakOnHyphens && IsHyphenChar(currentChar)) { string hyphens = ReadHyphens(); break; } if (!isBreakChar) _charPos++; else break; } //go back 1 endPosition = _charPos; return new string(_chars, initialPosition, endPosition - initialPosition); } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) return 0; // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { // copy to new array either double the size of the current or big enough to fit required content int newArrayLength = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); // increase the size of the buffer char[] dst = new char[newArrayLength]; BlockCopyChars(_chars, 0, dst, 0, _chars.Length); _chars = dst; } else { int remainingCharCount = _charsUsed - _charPos; if (remainingCharCount + charsRequired + 1 >= _chars.Length) { // the remaining count plus the required is bigger than the current buffer size char[] dst = new char[remainingCharCount + charsRequired + 1]; if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, dst, 0, remainingCharCount); _chars = dst; } else { // copy any remaining data to the beginning of the buffer if needed and reset positions if (remainingCharCount > 0) BlockCopyChars(_chars, _charPos, _chars, 0, remainingCharCount); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = remainingCharCount; } } int attemptCharReadCount = _chars.Length - _charsUsed - 1; int charsRead = _reader.Read(_chars, _charsUsed, attemptCharReadCount); _charsUsed += charsRead; if (charsRead == 0) _isEndOfFile = true; _chars[_charsUsed] = '\0'; //make sure we mark the end of our buffer return charsRead; } private string ReadSpaces() { int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') // need to read more data { if (ReadData(true) == 0) { break; } } bool isBreakChar = IsBreakChar(currentChar); if (isBreakChar) _charPos++; else break; } //go back 1 endPosition = _charPos; return new string(_chars, initialPosition, endPosition - initialPosition); } private string ReadHyphens() { int initialPosition = _charPos; int endPosition; while (true) { char currentChar = _chars[_charPos]; if (currentChar == '\0') // need to read more data { if (ReadData(true) == 0) { break; } } bool isHyphen = IsHyphenChar(currentChar); if (isHyphen) _charPos++; else break; } //go back 1 endPosition = _charPos; return new string(_chars, initialPosition, endPosition - initialPosition); } private void ShiftBufferIfNeeded() { // once in the last 10% of the buffer shift the remainling content to the start to avoid // unnessesarly increasing the buffer size when reading numbers/strings int length = _chars.Length; if (length - _charPos <= length * 0.1) { int count = _charsUsed - _charPos; if (count > 0) BlockCopyChars(_chars, _charPos, _chars, 0, count); _lineStartPos -= _charPos; _charPos = 0; _charsUsed = count; _chars[_charsUsed] = '\0'; } } private void BlockCopyChars(char[] src, int srcOffset, char[] dest, int destOffset, int count) { for (int i = 0; i < count; i++) { Buffer.BlockCopy(src, srcOffset, dest, destOffset, count); } } private bool IsBreakChar(char c) { return char.IsWhiteSpace(c); } private bool IsHyphenChar(char c) { return c == '-'; } private void SetToken(WordTokenType type) { _text = null; _type = type; _current = new WordToken() { Text = null, Type = type }; } private void SetToken(string text, WordTokenType type) { _text = text; _type = type; _current = new WordToken() { Text = text, Type = type }; } public void Dispose() { this._reader.Dispose(); } } }
using BusLog; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using StoreModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebUI.Models; namespace WebUI.Controllers { public class CustomerController : Controller { // GET: CustomerController private IBusLog _Buslog; public CustomerController(IBusLog bus) { _Buslog = bus; } public ActionResult Index() { return View(_Buslog.GetAllCustomers().Select(cust => new CustomerVM(cust)).ToList()); } public ActionResult OrderItemStore(int cust) { ViewBag.Customer = _Buslog.GetCustomer3(cust); return View(_Buslog.GetAllStorefronts().Select(store => new StorefrontVM(store)).ToList()); } //STILL NEED TO EDIT THIS PART public ActionResult OrderStoreItem(int cust, int store) { Random nums = new Random(); int IDs = nums.Next(1000, 9999); Order orde = new Order(IDs, store, 0, cust); ViewBag.Customer = _Buslog.GetCustomer3(cust); ViewBag.Storefront = _Buslog.GetStorefront3(store); _Buslog.AddOrder(new Order { IDs = orde.IDs, Storefrontsss = orde.Storefrontsss, Total = orde.Total, customernumber = orde.customernumber, } ); ViewBag.Order = _Buslog.GetOrder3(IDs); return View(_Buslog.GetAllProducts().Select(prod => new ProductVM(prod)).ToList()); } //STILL NEED TO CREATE VIEWS OF THIS public ActionResult BuyItem(int cust, int store, int prod, int orde) { //NEED TO FIX THIS TOMMORROW... DOUBLE TRACING ON INVENTORY AND ORDER... ViewBag.Customer = _Buslog.GetCustomer3(cust); ViewBag.Storefront = _Buslog.GetStorefront3(store); ViewBag.Order = _Buslog.GetOrder3(orde); ViewBag.Product = _Buslog.GetProduct3(prod); ViewBag.Inventory = _Buslog.GetInventory(store, prod); int five = orde; if(ViewBag.Inventory.InventoryQuantity != 0 ) { Random nums = new Random(); int ID = nums.Next(100, 999); LineItem lineItem = new LineItem(ID, 1, orde, prod); _Buslog.AddLineItem(lineItem); _Buslog.UpdateInventories(store,prod); _Buslog.UpdateOrders(five, ViewBag.Product.ProductPrice); return View(new LineItemVM(lineItem)); } return View(); } public ActionResult OrderStoreItem2(int cust, int store, int orde) { //THIS IS DONE AND READY TO TEST OUT ViewBag.Customer = _Buslog.GetCustomer3(cust); ViewBag.Storefront = _Buslog.GetStorefront3(store); ViewBag.Order = _Buslog.GetOrder3(orde); return View(_Buslog.GetAllProducts().Select(store => new ProductVM(store)).ToList()); } public ActionResult OrderPlaced(int cust, int store, int orde) { List<LineItem> LIList = _Buslog.GetLineItemsById(orde); //THIS NEEDS SOME FIXING ViewBag.Customer = _Buslog.GetCustomer3(cust); ViewBag.Storefront = _Buslog.GetStorefront3(store); ViewBag.Order = _Buslog.GetOrder3(orde); //foreach(var items in LIList) //{ //return View(new LineItemVM(items)); //} return View(_Buslog.GetLineItemsById(orde).Select(stores => new LineItemVM(stores)).ToList()); } //NEED TO WORK THIS OUT // GET: CustomerController/Details/5 public ActionResult Details(int id) { return View(); } // GET: CustomerController/Create public ActionResult Create() { return View(); } // POST: CustomerController/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CustomerVM customer) { try { if (ModelState.IsValid) { _Buslog.AddCustomer(new Customer { name = customer.name, hometown = customer.hometown, } ); return RedirectToAction(nameof(Index)); } return View(); } catch { return View(); } } // GET: CustomerController/Edit/5 public ActionResult Edit(int id) { return View(); } // POST: CustomerController/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: CustomerController/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: CustomerController/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, IFormCollection collection) { try { return RedirectToAction(nameof(Index)); } catch { return View(); } } } }
using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace ImmutableGeometry.Test { public static class TestHelpers { public static Point[] Points(params (int, int)[] points) => points.AsPoints().ToArray(); public static void Debug(Shape shape) { TestContext.WriteLine("==Corners=="); InternalListPoints(shape.Corners); TestContext.WriteLine("==EdgePoints=="); InternalListPoints(shape.EdgePoints); TestContext.WriteLine("==Points=="); InternalListPoints(shape.Points.Sort()); throw new InconclusiveException("Debug Data, not a test\n"); } public static void Debug(Line line) { TestContext.WriteLine($"==Start,End==\n{line.Start},{line.End}"); TestContext.WriteLine($"==Points=="); InternalListPoints(line.Points); throw new InconclusiveException("Debug Data, not a test\n"); } public static void Debug(IEnumerable<Point> points) { TestContext.WriteLine("==Points=="); InternalListPoints(points); throw new InconclusiveException("Debug Data, not a test\n"); } private static void InternalListPoints(IEnumerable<Point> points) { TestContext.Write(string.Join(", ", points.Select(p => $"({p.X},{p.Y})"))); TestContext.Write("\n"); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Adxstudio.Xrm.Web.UI.CrmEntityListView { /// <summary> /// Helpers for assisting with sorting a saved query view. /// </summary> public static class ViewSort { private static readonly Regex SortExpressionPattern = new Regex(@"(?<name>\w+)\s*(?<direction>(asc|ascending|desc|descending))?\s*(,)?", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase); /// <summary> /// Direction of the ordering /// </summary> public enum Direction { /// <summary> /// Ascending sort order; ASC /// </summary> Ascending, /// <summary> /// Decending sort order; DESC /// </summary> Descending } /// <summary> /// Parse a sort expression into a collection of column names and sort directions. /// </summary> /// <param name="sortExpression"></param> public static IEnumerable<Tuple<string, Direction>> ParseSortExpression(string sortExpression) { if (string.IsNullOrEmpty(sortExpression)) { return Enumerable.Empty<Tuple<string, Direction>>(); } return SortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match => { var sortNameCapture = match.Groups["name"].Value; var sortDirectionCapture = match.Groups["direction"].Value; var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase) ? Direction.Ascending : Direction.Descending; return new Tuple<string, Direction>(sortNameCapture, sortDirection); }).Where(sort => sort != null).ToArray(); } } }
[CompilerGeneratedAttribute] // RVA: 0x1574D0 Offset: 0x1575D1 VA: 0x1574D0 private sealed class NPCActionBehaviorController.<>c__DisplayClass19_2 // TypeDefIndex: 6151 { // Fields public Func<int, int, bool> func; // 0x10 public NPCActionBehaviorController.<>c__DisplayClass19_0 CS$<>8__locals2; // 0x18 // Methods // RVA: 0x1FB21C0 Offset: 0x1FB22C1 VA: 0x1FB21C0 public void .ctor() { } // RVA: 0x1FB4670 Offset: 0x1FB4771 VA: 0x1FB4670 internal bool <CreateFindTargetFunc>b__8(Character character) { } }
using InsuranceAdminPanel.Dal.Abstract; using InsuranceAdminPanel.Entity.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InsuranceAdminPanel.Dal.Concentre.Repository { public class GenericRepository<T> : IGenericRepository<T> where T : EntityBase { } }
namespace Saritasa.BoringWarehouse.Domain.Products.Entities { using System; using System.ComponentModel.DataAnnotations; using Users.Entities; /// <summary> /// Company that made product. /// </summary> public class Company { [Key] public int Id { get; set; } [Required] [MaxLength(255)] public string Name { get; set; } public User CreatedBy { get; set; } public DateTime CreatedAt { get; set; } = DateTime.Now; } }
namespace Spinner.Aspects.Internal { public abstract class MethodBinding : IMethodBinding { object IMethodBinding.Invoke(ref object instance, Arguments args) { Invoke(ref instance, args); return null; } public abstract void Invoke(ref object instance, Arguments args); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; namespace MMi_BIS_PA.Models { [Table("db_mmi_bis_pa.table_data")] public partial class TableData { [Required] [Key] [StringLength(45)] public string qrcode { get; set; } public sbyte? c1 { get; set; } public sbyte? c2 { get; set; } public sbyte? r { get; set; } public float? w { get; set; } public float? wd { get; set; } public float? set_point { get; set; } } }
using System; using System.Linq.Expressions; namespace FluentKusto { public class AppServiceIPSecAuditLogs : TableBase<AppServiceIPSecAuditLogs> { /// public string TenantId {get; set;} /// Time of the Http Request public DateTime TimeGenerated {get; set;} /// The result whether the access is Allowed or Denied public string Result {get; set;} /// Host header of the HTTP request public string CsHost {get; set;} /// This indicates whether the access is via Virtual Network Service Endpoint communication public string ServiceEndpoint {get; set;} /// IP address of the client public string CIp {get; set;} /// X-Forwarded-For header of the HTTP request public string XForwardedFor {get; set;} /// X-Forwarded-Host header of the HTTP request public string XForwardedHost {get; set;} /// X-Azure-FDID header (Azure Frontdoor Id) of the HTTP request public string XAzureFDID {get; set;} /// X-FD-HealthProbe (Azure Frontdoor Health Probe) of the HTTP request public string XFDHealthProbe {get; set;} /// Additional information public string Details {get; set;} /// public string SourceSystem {get; set;} /// The name of the table public string Type {get; set;} /// A unique identifier for the resource that the record is associated with public string _ResourceId {get; set;} /// A unique identifier for the subscription that the record is associated with public string _SubscriptionId {get; set;} } }
namespace clipr { /// <summary> /// Multiple arguments with the same name have been defined. /// </summary> public class DuplicateArgumentException : ArgumentIntegrityException { /// <summary> /// Multiple arguments with the same name have been defined. /// </summary> /// <param name="argumentName">Name of the duplicate argument.</param> internal DuplicateArgumentException(string argumentName) : base("Duplicate argument was defined: " + argumentName) { } } }
using System.Net; using Newtonsoft.Json; using System.Net.Http; using System.Text; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("ACR WebHook Posted"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); Uri _uri = new Uri("https://hooks.slack.com/services/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"); string _message = data?.ToString() ?? "test from azure function"; string _channel = "#imageupdates"; string _username = "webhookbot"; HttpClient _httpClient = new HttpClient(); var payload = new { text = _message, _channel, _username, }; var serializedPayload = JsonConvert.SerializeObject(payload); var response = _httpClient.PostAsync(_uri, new StringContent(serializedPayload, Encoding.UTF8, "application/json")).Result; return _message == null ? req.CreateResponse(HttpStatusCode.BadRequest, response.ToString()) : req.CreateResponse(HttpStatusCode.OK, String.Format("Message: {0}, Posted to: {1}", _message, _channel)); }
using System; namespace UtilityDisposables { /// <summary> /// A decorator class that only calls Dispose on the inner <see cref="T"/> value once all the references are gone. /// </summary> public class ReferenceCounter<T> : IDisposable where T : class, IDisposable { private readonly Func<T> _func; private T _value; private ulong _referenceCount = 0; public ReferenceCounter(Func<T> func) { _func = func; if (_func == null) throw new NullReferenceException(); } public T Value => _value; /// <summary> /// Get an object that will keep the inner <see cref="T"/> value from being Disposed /// until the return value of all calls to GetReference are Disposed. /// </summary> public ReferenceCounter<T> GetReference() { if (_value == null) _value = _func(); _referenceCount++; return this; } public void Dispose() { if (_referenceCount <= 1) { if (_value != null) _value.Dispose(); _value = null; } _referenceCount--; } } /// <summary> /// Non-generic form of <see cref="ReferenceCounter{T}"/> that deals just in <see cref="IDisposable"/>s. /// </summary> public class ReferenceCounter : ReferenceCounter<IDisposable> { public ReferenceCounter(Func<IDisposable> func) : base(func) { } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using Microsoft.Extensions.Localization; namespace Microsoft.AspNetCore.Mvc.Localization.Test { public class TestStringLocalizer : IStringLocalizer { private CultureInfo _culture { get; set; } public TestStringLocalizer() : this(null) { } public TestStringLocalizer(CultureInfo culture) { _culture = culture; } public LocalizedString this[string name] { get { var value = "Hello "; if (_culture != null) { value = "Bonjour "; } return new LocalizedString(name, value + name); } } public LocalizedString this[string name, params object[] arguments] { get { var value = "Hello "; if (_culture != null) { value = "Bonjour "; } string argument = string.Empty; foreach (var arg in arguments) { argument = argument + " " + arg; } return new LocalizedString(name, value + name + argument); } } public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures) { var allStrings = new List<LocalizedString>(); allStrings.Add(new LocalizedString("Hello", "World")); if (includeParentCultures) { allStrings.Add(new LocalizedString("Foo", "Bar")); } return allStrings; } [Obsolete("This method is obsolete. Use `CurrentCulture` and `CurrentUICulture` instead.")] public IStringLocalizer WithCulture(CultureInfo culture) { return new TestStringLocalizer(culture); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDB_Generator { public class Attribute { public object attribute_name { get; set; } public object attribute_value { get; set; } } public class Workflow { public string requester_id { get; set; } public string subject { get; set; } public string requested_url { get; set; } public string action { get; set; } public List<Attribute> attributes { get; set; } } public class Attribute2 { public object attribute_name { get; set; } public object attribute_value { get; set; } } public class Policy { public string subject { get; set; } public bool permission { get; set; } public string action { get; set; } public string resource { get; set; } public List<Attribute2> attributes { get; set; } } public class UPP { public string osp_policy_id { get; set; } public string policy_text { get; set; } public string policy_url { get; set; } public List<Workflow> workflow { get; set; } public List<Policy> policies { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class CameraRenderEvents : MonoBehaviour { // UnityEvent onPreRender; // UnityEvent onPostRender; // UnityEvent onPreCull; // UnityEvent onRenderImage; // UnityEvent onRenderObject; // UnityEvent onWillRenderObject; // void OnPreRender() { onPreRender?.Invoke (); } // void OnPostRender() { onPostRender?.Invoke (); } // void OnPreCull() { onPreCull?.Invoke (); } // void OnRenderImage() { onRenderImage?.Invoke (); } // void OnRenderObject() { onRenderObject?.Invoke (); } // void OnWillRenderObject() { onWillRenderObject?.Invoke (); } }
@model SecureXWebApp.Models.Bank @{ ViewData["Title"] = "Details"; } <li><a asp-area="" asp-controller="Customer" asp-action="Index">Customers</a></li> <li><a asp-area="" asp-controller="Employee" asp-action="Index">Employees</a></li> <h2>Details</h2> <div> <h4>Bank</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.Id) </dt> <dd> @Html.DisplayFor(model => model.Id) </dd> <dt> @Html.DisplayNameFor(model => model.Reserves) </dt> <dd> @Html.DisplayFor(model => model.Reserves) </dd> <dt> @Html.DisplayNameFor(model => model.City) </dt> <dd> @Html.DisplayFor(model => model.City) </dd> </dl> </div> <div> <a asp-action="Index">Back to bank</a> </div>
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.Tools.ServiceModel.Svcutil; using Xunit; namespace SvcutilTest { internal static class ProjectUtils { static readonly CancellationToken token = CancellationToken.None; public static MSBuildProj GetProject(string filePath, string targetFramework, bool forceNew, bool build, ILogger logger, bool globalTool = false) { MSBuildProj project = null; var projectDir = Path.GetDirectoryName(filePath); var srcProgramFile = Path.Combine(projectDir, "Program.cs"); var dstProgramFile = Path.Combine(projectDir, $"{Path.GetFileNameWithoutExtension(filePath)}.cs"); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); if (forceNew && File.Exists(filePath)) { File.Delete(filePath); if (File.Exists(dstProgramFile)) File.Delete(dstProgramFile); FileUtil.TryDeleteDirectory(Path.Combine(Path.GetDirectoryName(filePath), "obj")); } if (File.Exists(filePath)) { project = MSBuildProj.FromPathAsync(filePath, logger, token).Result; } else { project = MSBuildProj.DotNetNewAsync(filePath, logger, token).Result; File.Move(srcProgramFile, dstProgramFile); } Assert.NotNull(project); if (!string.IsNullOrEmpty(targetFramework)) { project.TargetFramework = targetFramework; } if (!globalTool) { var svcutilPkgVersion = E2ETest.GetSvcutilPkgVersionAndFeed(); var svcutilPkgRef = ProjectDependency.FromPackage("dotnet-svcutil-lib", svcutilPkgVersion); if (!project.Dependencies.Any(d => d.Equals(svcutilPkgRef))) { bool success = project.AddDependency(svcutilPkgRef); Assert.True(success, $"Could not add tool package dependency: dotnet-svcutil-lib.{svcutilPkgVersion}"); } } var ret = project.RestoreAsync(logger, token).Result; Assert.True(ret.ExitCode == 0, $"Project package restore failed:{Environment.NewLine}{ret.OutputText}{logger}"); if (build) { ret = project.BuildAsync(logger, token).Result; Assert.True(ret.ExitCode == 0, $"Project build failed:{Environment.NewLine}{ret.OutputText}{logger}"); } return project; } public static ProcessRunner.ProcessResult RunSvcutil(this MSBuildProj project, string options, bool expectSuccess, ILogger logger, bool globalTool = false) { Assert.False(string.IsNullOrEmpty(options), $"{nameof(options)} not initialized!"); Assert.True(File.Exists(project?.FullPath), $"{nameof(project)} is not initialized!"); var envVars = new Dictionary<string, string> { { AppInsightsTelemetryClient.OptOutVariable, (!AppInsightsTelemetryClient.IsUserOptedIn).ToString() } }; ProcessRunner.ProcessResult result; if (globalTool) { result = ProcessRunner.RunAsync("dotnet-svcutil", options, project.DirectoryPath, redirectOutput: true, throwOnError: false, environmentVariables: envVars, logger: logger, cancellationToken: CancellationToken.None).Result; } else { string csStr = string.Empty; string srcPath = project.FullPath.Replace("csproj", "cs"); using (var sr = new StreamReader(srcPath)) { csStr = sr.ReadToEnd(); } using (var sw = new StreamWriter(srcPath)) { if (!csStr.Contains("using Microsoft.Tools.ServiceModel.Svcutil;")) { string indent = new string(' ', 12); csStr = csStr.Replace("using System;", "using System;\r\nusing Microsoft.Tools.ServiceModel.Svcutil;\r\nusing System.Linq;\r\nusing System.Text.RegularExpressions;"); csStr = csStr.Replace("static void Main", "static int Main"); string replacement = "var re = new Regex(@\"'[^\\\"\"]*'|[^\\\"\"^\\s]+|\"\"[^\\\"\"]*\"\"\");\r\n" + indent + "string optstring = @\"" + options + "\";\r\n" + indent + "string[] opts = re.Matches(optstring).Cast<Match>().Select(m => m.Value).ToArray();\r\n" + indent + "return Tool.Main(opts);"; csStr = csStr.Replace("Console.WriteLine(\"Hello World!\");", replacement); sw.Write(csStr); sw.Flush(); } else { int start = csStr.IndexOf("string optstring"); int end = csStr.IndexOf("string[] opts"); csStr = csStr.Replace(csStr.Substring(start, end - start), "string optstring = @\"" + options + "\";\r\n"); sw.Write(csStr); sw.Flush(); } } string csprojStr = string.Empty; using (var sr2 = new StreamReader(project.FullPath)) { csprojStr = sr2.ReadToEnd(); } if (csprojStr.Contains("System.ServiceModel")) { using (var sw2 = new StreamWriter(project.FullPath)) { sw2.Write(System.Text.RegularExpressions.Regex.Replace(csprojStr, @"<ItemGroup>\s+<PackageReference Include=""System.ServiceModel[\S\s]+ItemGroup>", "")); sw2.Flush(); } } result = ProcessRunner.RunAsync("dotnet", $"run", project.DirectoryPath, redirectOutput: true, throwOnError: false, environmentVariables: envVars, logger: logger, cancellationToken: CancellationToken.None).Result; } var isSuccess = result.ExitCode == 0 || result.ExitCode == 6; var isTestSucess = !(isSuccess ^ expectSuccess); if (!isTestSucess) { var errMsg = string.Format(E2ETest.g_ToReproduceProblemMessageFormat, project.DirectoryPath, options); logger?.WriteMessageAsync(errMsg, true).Wait(); } return result; } public static string AddFakeServiceReference(this MSBuildProj project, string srcParamsFile, string referenceFolderName, bool addNamespace) { Assert.False(string.IsNullOrEmpty(srcParamsFile), $"{nameof(srcParamsFile)} not initialized!"); Assert.False(string.IsNullOrEmpty(referenceFolderName), $"{nameof(referenceFolderName)} not initialized!"); Assert.True(File.Exists(project?.FullPath), $"{nameof(project)} is not initialized!"); var outputDir = Path.Combine(project.DirectoryPath, referenceFolderName); Directory.CreateDirectory(outputDir); var dstParamsFile = Path.Combine(outputDir, Path.GetFileName(srcParamsFile)); File.Copy(srcParamsFile, dstParamsFile); if (addNamespace) { var referenceNamespace = PathHelper.GetRelativePath(referenceFolderName, project.DirectoryPath).Replace("\\", ".").Replace("/", ".").Replace(" ", "_"); var updateOptions = UpdateOptions.FromFile(dstParamsFile); updateOptions.NamespaceMappings.Add(new KeyValuePair<string, string>("*", referenceNamespace)); updateOptions.Save(dstParamsFile); } return dstParamsFile; } } }
using System.Threading; using System.Threading.Tasks; using Domain.Orders.Contracts.Events; using MediatR; namespace Domain.Customers.EventHandlers { public class OnOrderCreated : INotificationHandler<OrderCreated> { public Task Handle(OrderCreated notification, CancellationToken cancellationToken) { //Add OrderId to collection inside Customer object return Task.CompletedTask; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class color_util { public static void set_alpha(SpriteRenderer sr, float a) { Color col = sr.color; sr.color = new Color(col.r, col.g, col.b, a); } }
using System; using System.Collections.Generic; using System.Text; using ZigBeeNet.Hardware.TI.CC2531.Util; namespace ZigBeeNet.Hardware.TI.CC2531.Packet.ZDO { public class ZDO_END_DEVICE_ANNCE : ZToolPacket //// implements IREQUEST,IZDO /// </summary> { /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.Capabilities</name> /// <summary>MAC capabilities</summary> public int Capabilities { get; private set; } /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.DevAddr</name> /// <summary>Device network address.</summary> public ZToolAddress16 nwkAddr { get; private set; } /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.DeviceAddress</name> /// <summary>The 64 bit IEEE Address of the device you want to announce</summary> public ZToolAddress64 IEEEAddress { get; private set; } /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE</name> /// <summary>Constructor</summary> public ZDO_END_DEVICE_ANNCE() { } public ZDO_END_DEVICE_ANNCE(ZToolAddress16 num1, ZToolAddress64 num2, int capability_info1) { this.nwkAddr = num1; this.IEEEAddress = num2; this.Capabilities = capability_info1; byte[] framedata = new byte[11]; framedata[0] = this.nwkAddr.Lsb; framedata[1] = this.nwkAddr.Msb; byte[] bytes = this.IEEEAddress.Address; for (int i = 0; i < 8; i++) { framedata[i + 2] = bytes[7 - i]; } BuildPacket(new DoubleByte((ushort)ZToolCMD.ZDO_END_DEVICE_ANNCE), framedata); } /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO</name> /// <summary>Capability Information bitfield</summary> public class CAPABILITY_INFO { /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.ALTER_PAN_COORD</name> /// <summary>Capability Information bitfield</summary> public readonly int ALTER_PAN_COORD = 1; /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.DEVICE_TYPE</name> /// <summary>Capability Information bitfield</summary> public readonly int DEVICE_TYPE = 2; /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.NONE</name> /// <summary>Capability Information bitfield</summary> public readonly int NONE = 0; /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.POWER_SOURCE</name> /// <summary>Capability Information bitfield</summary> public readonly int POWER_SOURCE = 4; /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.RECEIVER_ON_WHEN_IDLE</name> /// <summary>Capability Information bitfield</summary> public readonly int RECEIVER_ON_WHEN_IDLE = 8; /// <name>TI.ZPI1.ZDO_END_DEVICE_ANNCE.CAPABILITY_INFO.SECURITY_CAPABILITY</name> /// <summary>Capability Information bitfield</summary> public readonly int SECURITY_CAPABILITY = 0x40; } } }
using BenTurkia.NumbersConverter.Business.Contracts; using BenTurkia.NumbersConverter.Business.Implementations; using SimpleInjector; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BenTurkia.NumbersConverter.Business { /// <summary> /// Business Factory Class /// </summary> public class BusinessFactory { private Container container; private static BusinessFactory instance; private static readonly object syncRoot = new Object(); private BusinessFactory() { RegisterBusinessImplementations(); } private void RegisterBusinessImplementations() { container = new Container(); #region Roman Numbers container.Register<IRomanBO, RomanBO>(Lifestyle.Singleton); #endregion container.Verify(); } public static BusinessFactory Instance { get { lock (syncRoot) { if (instance == null) { instance = new BusinessFactory(); } } return instance; } } public T GetService<T>() { return (T)container.GetInstance(typeof(T)); } public static T Service<T>() { return Instance.GetService<T>(); } } }