NewGuid() публичный статический Метод

Creates a new sequential guid.
public static NewGuid ( ) : System.Guid
Результат System.Guid
Пример #1
0
 public CreateGameCommand(string name, int launchYear, string platform)
 {
     Id         = SequentialGuid.NewGuid();
     Name       = name;
     LaunchYear = launchYear;
     Platform   = platform;
 }
Пример #2
0
        public void 寫入記憶體_Guid_調用ICompare_由小到大排序_得到連續順序()
        {
            var testTables = new List <TestTable>();

            //arrange

            for (var i = 1; i < 10000; i++)
            {
                var key   = SequentialGuid.NewGuid();
                var name  = i.ToString("000");
                var table = new TestTable {
                    Id = i, Name = name, Key = key
                };
                testTables.Add(table);
            }

            //act
            var tables = testTables.OrderBy(p => p.Key, new SequentialGuidComparer())
                         .ToList();

            var targetArray = tables.Select(p => p.Id).ToArray();

            var actual = this.IsSequential(targetArray);

            //assert
            Assert.IsTrue(actual);
        }
Пример #3
0
        public async Task ShouldReturnAllGames()
        {
            GenerateMock();

            var entities = new List <Game>
            {
                Game.Create(SequentialGuid.NewGuid(), "Bridge Constructor: The Walking Dead", 2020, "PC"),
                Game.Create(SequentialGuid.NewGuid(), "Bugsnax", 2020, "X-Box"),
            };

            var expected = entities.Select(e => _mapper.Map <GameListViewModel>(e)).ToList();

            var gameMock = entities.AsQueryable().BuildMock();


            _gameQueryMock.Setup(x => x.GetAllAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .Returns(gameMock.Object);

            _gameQueryMock.Setup(x => x.CountAsync(It.IsAny <string>(), default))
            .ReturnsAsync(1);

            var command = GetCommandHandler();

            var result = await command.Handle(new GetGamesCommand { Search = "search", Sort = "sort", Order = "order", Page = 0, Size = 5 }, default);

            result.Should().NotBeNull()
            .And.BeAssignableTo <ResponseViewModel <GameListViewModel> >();

            result.Records.Should().Be(1);
            result.Data.Should().HaveCount(2)
            .And.BeEquivalentTo(expected);
        }
Пример #4
0
        public async Task ShouldReturnOnlyGameWithNameContainsName()
        {
            GenerateMock();

            List <Game> list = new List <Game>
            {
                Game.Create(SequentialGuid.NewGuid(), "Call of Duty: Black Ops Cold War", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Immortals Fenyx Rising", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Ratchet & Clank: Rift Apart", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Bridge Constructor: The Walking Dead", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Bugsnax", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Watch Dogs: Legion", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Assassin's Creed Valhalla", 2020, "PS 5")
            };

            var mockGame = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Game>()).Returns(mockGame.Object);

            var repository = GetRepository();

            var query = repository.GetAllAsync("Call", "name", "desc", 0, 10);

            var result = await query.ToListAsync();

            result.Should().HaveCount(1)
            .And.BeEquivalentTo(list.Where(x => x.Name.Contains("Call")));
        }
Пример #5
0
        public void 寫入記憶體_SequentialGuid_由大到小排序_得到連續順序()
        {
            var testTables = new List <TestTableViewModel>();

            //arrange

            for (var i = 1; i < 10000; i++)
            {
                var key   = SequentialGuid.NewGuid();
                var name  = i.ToString("000");
                var table = new TestTableViewModel {
                    Id = i, Name = name, Key = key
                };
                testTables.Add(table);
            }

            //act
            var tables = testTables.OrderByDescending(p => p.Key)
                         .ToList();

            var targetArray = tables.Select(p => p.Id).ToArray();

            var actual = this.IsReverseSequential(targetArray);

            //assert
            Assert.IsTrue(actual);
        }
Пример #6
0
        public async Task ExecuteInTransactionAsync(DbContext dbContext, Func <CancellationToken, Task> operation, CancellationToken token = default)
        {
            _contexts.ValidateContext(dbContext);

            /* Connection Resilience Strategy: "Manually track the transaction"                                 *
            * reference: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency          */

            var connection = dbContext.Database.GetDbConnection();

            using (_db = CreateTransactionContext(connection))
            {
                var strategy = _db.Database.CreateExecutionStrategy();

                var transaction = new TransactionEntry(SequentialGuid.NewGuid());
                _db.Transactions.Add(transaction);

                await operation(token);

                await strategy.ExecuteInTransactionAsync(
                    operation : async() =>
                    await _contexts.SaveChangesAsync(token),
                    verifySucceeded : async() =>
                    await _db.Transactions.AsNoTracking()
                    .AnyAsync(t => t.Id == transaction.Id, cancellationToken: token));

                _contexts.AcceptAllChanges();

                _db.Transactions.Remove(transaction);
                await _db.SaveChangesAsync(token);
            }

            _db = null;
        }
Пример #7
0
        /// <summary>
        /// Creates a document object from the specified document contract.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="contract"></param>
        /// <returns></returns>
        public static TestDocument Create(DocumentLibraryContext context, DocumentContract contract)
        {
            TestDocument document = new TestDocument()
            {
                TestDocumentId = SequentialGuid.NewGuid(),
                Application    = contract.Application,
                AppVersion     = contract.AppVersion,
                Author         = contract.Author,
                AuthorType     = contract.AuthorType,
                ColorMode      = contract.ColorMode,
                DefectId       = contract.DefectId,
                FileName       = contract.FileName,
                FileSize       = contract.FileSize,
                FileType       = contract.FileType,
                Notes          = contract.Notes,
                Orientation    = contract.Orientation,
                Pages          = contract.Pages,
                SubmitDate     = contract.SubmitDate,
                Submitter      = contract.Submitter,
                Tag            = contract.Tag,
                Vertical       = contract.Vertical,
            };

            TestDocumentExtension extension = context.TestDocumentExtensions.FirstOrDefault(x => x.Extension.Equals(contract.Extension));

            document.TestDocumentExtension = extension;

            return(document);
        }
Пример #8
0
        public static User CreateUser(ITupapiContext context, Provider provider, StandartAuthRequest request)
        {
            User   newUser      = null;
            string providerName = null;
            string providerId   = null;
            string accesstoken  = null;

            if (provider == Provider.Standart)
            {
                var salt = AuthHelper.GenerateSalt();
                newUser = new User
                {
                    Id    = SequentialGuid.NewGuid(),
                    Name  = request.Name,
                    Email = request.Email,
                    Salt  = salt,
                    SaltedAndHashedPassword = AuthHelper.Hash(request.Password, salt)
                };
                providerName = Const.Standart;
                providerId   = newUser.Id;
            }

            context.Users.Add(newUser);
            context.SaveChanges();
            CreateAccount(context, provider, providerName, newUser.Id, providerId);
            return(newUser);
        }
Пример #9
0
        /// <summary>
        /// Exexutes the Print Job
        /// </summary>
        /// <returns></returns>
        private PluginExecutionResult ExecutePrintJob()
        {
            PluginExecutionResult printResult = new PluginExecutionResult(PluginResult.Passed);

            try
            {
                PrintQueue     defaultPrintQueue;
                PrintQueueInfo printQueueInfo = ExecutionData.PrintQueues.GetRandom();
                UpdateStatus("Print Activity: Retrieving print queue for " + printQueueInfo.QueueName);
                defaultPrintQueue = PrintQueueController.Connect(printQueueInfo);
                PrintingEngine engine = new PrintingEngine();

                // Select a documents to print
                DocumentCollectionIterator documentIterator = new DocumentCollectionIterator(CollectionSelectorMode.ShuffledRoundRobin);
                Document document = documentIterator.GetNext(ExecutionData.Documents);

                // Download the document and log the starting information for the print job
                Guid     jobId     = SequentialGuid.NewGuid();
                FileInfo localFile = ExecutionServices.FileRepository.GetFile(document);

                UpdateStatus($"Print Activity: Printing {localFile.Name} to {defaultPrintQueue.FullName}");
                var result = engine.Print(localFile, defaultPrintQueue);
                UpdateStatus($"Print Activity: Finished printing {localFile.Name}");

                return(printResult);
            }
            catch (Exception genericException)
            {
                printResult = new PluginExecutionResult(PluginResult.Failed, genericException.ToString());
                ExecutionServices.SystemTrace.LogError(genericException.ToString());
                return(printResult);
            }
        }
Пример #10
0
        /// <summary>
        /// Loads the specified VirtualResourceDetail into the specified EnterpriseScenario.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="scenario">The <see cref="EnterpriseScenario"/></param>
        /// <param name="detail">The metadata detail</param>
        public void LoadDetail <T>(EnterpriseScenario scenario, T detail) where T : ResourceDetailBase
        {
            VirtualResourceId    = SequentialGuid.NewGuid();
            EnterpriseScenario   = scenario;
            EnterpriseScenarioId = scenario.EnterpriseScenarioId;
            ResourceType         = detail.ResourceType.ToString();
            Name          = detail.Name;
            Description   = detail.Description;
            InstanceCount = detail.InstanceCount;
            Platform      = detail.Platform;
            Enabled       = detail.Enabled;

            foreach (var metadataDetail in detail.MetadataDetails)
            {
                VirtualResourceMetadata metadata = new VirtualResourceMetadata(ResourceType, metadataDetail.MetadataType)
                {
                    VirtualResource           = this,
                    VirtualResourceId         = VirtualResourceId,
                    ExecutionPlan             = GetExecutionPlan(metadataDetail),
                    VirtualResourceMetadataId = metadataDetail.Id,
                    Name            = metadataDetail.Name,
                    Metadata        = metadataDetail.Data,
                    MetadataVersion = metadataDetail.MetadataVersion,
                    Enabled         = metadataDetail.Enabled
                };

                VirtualResourceMetadataSet.Add(metadata);
            }

            LoadChildDetail(detail);
        }
Пример #11
0
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            string str2;

            base.BarItemClick(e);
            if (((str2 = e.BarItemKey.ToUpperInvariant()) != null) && (str2 == "TBBUMPSETTING"))
            {
                string id = base.View.BusinessInfo.GetForm().Id;
                if (!CommonHelper.CheckPermission(base.Context, id, "545c77b3761524"))
                {
                    base.View.ShowMessage(ResManager.LoadKDString("您没有撞单设置的权限!", "006008030001275", SubSystemType.CRM, new object[0]), MessageBoxType.Notice);
                }
                else
                {
                    BillShowParameter param = new BillShowParameter
                    {
                        FormId       = "CRM_BumpAnalysisSetting",
                        OpenStyle    = { ShowType = ShowType.Modal },
                        PageId       = SequentialGuid.NewGuid().ToString(),
                        CustomParams = { {
                                             "FormID",
                                             id
                                         } },
                        CustomComplexParams = { {
                                                    "EnableExpdate",
                                                    false
                                                } }
                    };
                    List <string> list = new string[] { "FBillHead", "FCRM_Clue_Cust", "FCRM_Clue_Contact" }.ToList <string>();
                    param.CustomComplexParams.Add("FormTables", list);
                    base.View.ShowForm(param);
                }
            }
        }
Пример #12
0
        PluginExecutionData IPluginFrameworkSimulator.CreateExecutionData(PluginConfigurationData configurationData)
        {
            if (configurationData == null)
            {
                throw new ArgumentNullException(nameof(configurationData));
            }

            PluginExecutionContext executionContext = new PluginExecutionContext
            {
                ActivityExecutionId = SequentialGuid.NewGuid(),
                SessionId           = SessionId,
                UserName            = UserName,
                UserPassword        = UserPassword
            };

            // Retrieve all selected assets, then add any badge boxes associated with those assets
            var selectedAssets = PluginConfigurationTransformer.GetExecutionAssets(configurationData, _assetInventory);
            var badgeBoxes     = _assetInventory.GetBadgeBoxes(selectedAssets);
            AssetInfoCollection executionAssets = new AssetInfoCollection(selectedAssets.Union(badgeBoxes).ToList());

            return(new PluginExecutionData
                   (
                       configurationData.GetMetadata(),
                       configurationData.MetadataVersion,
                       executionAssets,
                       PluginConfigurationTransformer.GetExecutionDocuments(configurationData, _documentLibrary),
                       PluginConfigurationTransformer.GetExecutionServers(configurationData, _assetInventory),
                       PluginConfigurationTransformer.GetExecutionPrintQueues(configurationData, _assetInventory),
                       (this as IPluginFrameworkSimulator).Environment,
                       executionContext,
                       new PluginRetrySettingDictionary(RetrySettings)
                   ));
        }
Пример #13
0
        public void Init()
        {
            using (var unitWork = UnitOfWork.Start())
            {
                User user = new User("h.c");
                user.FirstName = "Hugo";
                user.LastName  = "Cheng";
                user.Email     = "*****@*****.**";

                Group group = new Group("c#");
                group.Name = "C# Team";

                var userRepository  = new EFRepository <User>();
                var groupRepository = new EFRepository <Group>();

                //Type=hierarchy,似乎就是表示從屬的關係,Role則是表示已為從屬,且在此組織中扮演何角色
                Membership membership = new Membership(SequentialGuid.NewGuid());
                membership.Type  = "hierarchy";
                membership.Role  = "Member";
                membership.User  = userRepository.Single(s => s.FirstName == "Hugo");
                membership.Group = groupRepository.Single(s => s.GroupName == "C# Team");

                var membershipRepository = new EFRepository <Membership>();
                membershipRepository.Add(membership);
                unitWork.Flush();
            }
        }
Пример #14
0
        public static bool ConnectToDispatcher()
        {
            var result = false;

            if (GlobalSettings.IsDistributedSystem)
            {
                FrameworkServer dispatcher = null;
                using (MainFormConnectDialog connectDialog = new MainFormConnectDialog())
                {
                    connectDialog.ShowDialog();
                    if (connectDialog.DialogResult == DialogResult.OK)
                    {
                        try
                        {
                            dispatcher = connectDialog.SelectedDispatcher;

                            //Subscribe to dispatcher updates
                            SessionClient.Instance.Initialize(dispatcher.IPAddress);
                            SessionClient.Instance.Refresh();

                            Dispatcher = dispatcher;
                            GlobalSettings.SetDispatcher(dispatcher.IPAddress);
                            DispatcherChanged?.Invoke(dispatcher, new EventArgs());
                            result = true;
                        }
                        catch (EndpointNotFoundException ex)
                        {
                            Connected = result;
                            throw new EnvironmentConnectionException(
                                      "Could not connect to '{0}' at {1}.".FormatWith(dispatcher.HostName, dispatcher.IPAddress), ex);
                        }
                    }
                }
            }
            else
            {
                // If we are in a standalone mode then there will not be a remote dispatcher running
                // and in this case just collect information on the local machine and use that for
                // the Dispatcher information.
                Dispatcher = new FrameworkServer()
                {
                    FrameworkServerId = SequentialGuid.NewGuid()
                };
                Dispatcher.HostName = Environment.MachineName;

                // This is needed to run on a 192 or 10 net.
                Dispatcher.IPAddress = "localhost";

                SessionClient.Instance.Initialize(Dispatcher.IPAddress);
                SessionClient.Instance.Refresh();

                GlobalSettings.SetDispatcher(Dispatcher.IPAddress);
                DispatcherChanged(Dispatcher, new EventArgs());

                result = true;
            }
            Connected = result;
            return(result
                   );
        }
        public async Task ShouldReturnAllFriends()
        {
            GenerateMock();

            var entities = new List <Friend>
            {
                Friend.Create(SequentialGuid.NewGuid(), "Bruce", "Wayne", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Banner", "Banner", "*****@*****.**")
            };

            var expected = entities.Select(e => _mapper.Map <FriendListViewModel>(e)).ToList();

            var friendMock = entities.AsQueryable().BuildMock();


            _friendQueryMock.Setup(x => x.GetAllAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>()))
            .Returns(friendMock.Object);

            _friendQueryMock.Setup(x => x.CountAsync(It.IsAny <string>(), default))
            .ReturnsAsync(1);

            var command = GetCommandHandler();

            var result = await command.Handle(new GetFriendsCommand { Search = "search", Sort = "sort", Order = "order", Page = 0, Size = 5 }, default);

            result.Should().NotBeNull()
            .And.BeAssignableTo <ResponseViewModel <FriendListViewModel> >();

            result.Records.Should().Be(1);
            result.Data.Should().HaveCount(2)
            .And.BeEquivalentTo(expected);
        }
Пример #16
0
        private static async Task Sample2(IEventStore store)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options, TransactionScopeAsyncFlowOption.Enabled))
            {
                var repo      = new Repository <ShoppingCart>(store);
                var streamId  = SequentialGuid.NewGuid();
                var aggregate = new ShoppingCart(streamId, SequentialGuid.NewGuid());
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 1", quantity: 3);
                var item2Id = SequentialGuid.NewGuid();
                aggregate.AddItem(item2Id, name: "Product 2", quantity: 1);
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 3", quantity: 5);
                aggregate.RemoveItem(item2Id);
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 4", quantity: 1);

                var snap = aggregate.GetSnapshot();

                await repo.SaveChangesAsync(aggregate);

                await store.Advanced.UpdateSnapshotAsync(aggregate.Id, snap.Version, snap.State);

                aggregate = await repo.LoadAsync(streamId);

                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 5", quantity: 5);
                await repo.SaveChangesAsync(aggregate);

                aggregate = await repo.LoadAsync(streamId);

                Console.WriteLine($@"Aggregate expected version 7 = {aggregate.CommittedVersion}");

                scope.Complete();
            }
        }
Пример #17
0
        public FooItem(string name) : this()
        {
            Ensure.NotEmpty(name, nameof(name));

            Id   = SequentialGuid.NewGuid();
            Name = name;
        }
Пример #18
0
        private static async Task Sample1(IEventStore store)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options, TransactionScopeAsyncFlowOption.Enabled))
            {
                var streamId  = SequentialGuid.NewGuid();
                var aggregate = new ShoppingCart(streamId, Guid.Empty);
                aggregate.AddItem(SequentialGuid.NewGuid(), name: "Product 1", quantity: 3);

                var commitId = SequentialGuid.NewGuid();
                var stream   = new EventStream(commitId, aggregate.TakeUncommittedEvents());

                // Adding metadata item (key, value)
                stream.Metadata = new Dictionary <string, object>
                {
                    { "RequestIP", "0.0.0.0" },
                    { "User", "John Doe" }
                };

                await store.SaveChangesAsync(streamId, ExpectedVersion.NoStream, stream);

                await store.LoadAsync(streamId, 1, false);

                scope.Complete();
            }
        }
        /// <summary>
        /// Creates a new folder under the specified parent id.
        /// </summary>
        /// <param name="parentId">The parent id.</param>
        /// <returns>The ID of the created folder.</returns>
        public Guid CreateFolder(Guid?parentId)
        {
            // Create a default folder, which is valid if the parent is null
            var folder = new ConfigurationTreeFolder(SequentialGuid.NewGuid(), "New Folder", "ScenarioFolder", parentId);

            // Determine the real folder type and parent
            if (parentId != null)
            {
                EnterpriseTestMapNode node = _databaseMap[(Guid)parentId];
                switch (node.NodeType)
                {
                case ConfigurationObjectType.EnterpriseScenario:
                case ConfigurationObjectType.ResourceFolder:
                    folder.FolderType = "ResourceFolder";
                    break;

                case ConfigurationObjectType.VirtualResource:
                case ConfigurationObjectType.MetadataFolder:
                    folder.FolderType = "MetadataFolder";
                    break;
                }
            }

            using (EnterpriseTestContext context = new EnterpriseTestContext())
            {
                context.ConfigurationTreeFolders.AddObject(folder);
                HandleObjectChange(context, folder);
                context.SaveChanges();
            }

            return(folder.ConfigurationTreeFolderId);
        }
Пример #20
0
        public void Should_NotHave_Empty_Id_When_Instantiated_With_Id()
        {
            var id = SequentialGuid.NewGuid();
            Device <System.Guid> a = new Device <System.Guid>(null, id);

            a.Id.Should().NotBeEmpty();
        }
Пример #21
0
        public async Task ShouldReturnTheLastGamesSkipFiveOrderedByName()
        {
            GenerateMock();

            List <Game> list = new List <Game>
            {
                Game.Create(SequentialGuid.NewGuid(), "Call of Duty: Black Ops Cold War", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Immortals Fenyx Rising", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Ratchet & Clank: Rift Apart", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Bridge Constructor: The Walking Dead", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Bugsnax", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Watch Dogs: Legion", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Assassin's Creed Valhalla", 2020, "PS 5")
            };

            var mockGame = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Game>()).Returns(mockGame.Object);

            var repository = GetRepository();

            var query = repository.GetAllAsync(string.Empty, "name", "asc", 1, 5);

            var result = await query.ToListAsync();

            result.Should().HaveCount(2)
            .And.BeEquivalentTo(list.OrderBy(x => x.Name).Skip(5).Take(5).ToList())
            .And.BeInAscendingOrder(x => x.Name);
        }
Пример #22
0
 public CreateFriendCommand(string name, string nickname, string email)
 {
     Id       = SequentialGuid.NewGuid();
     Name     = name;
     Nickname = nickname;
     Email    = email;
 }
Пример #23
0
        public async Task ShouldReturnTheGameRequestedWithLoanedInformation()
        {
            GenerateMock();

            var game = Game.Create(SequentialGuid.NewGuid(), "Watch Dogs: Legion", 2020, "PS 5");

            List <Game> list = new List <Game>
            {
                Game.Create(SequentialGuid.NewGuid(), "Call of Duty: Black Ops Cold War", 2020, "PS 5"),
                Game.Create(SequentialGuid.NewGuid(), "Immortals Fenyx Rising", 2020, "PS 5")
            };

            list.Add(game);

            var mockGame = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Game>()).Returns(mockGame.Object);

            var query = GetRepository();

            var model = await query.GetLoanedInfo(game.Id, default);

            model.Should().NotBeNull();
            model.Id.Should().Be(game.Id);
            model.Name.Should().Be(game.Name);
            model.Platform.Should().Be(game.Platform);
        }
        public async Task ShouldReturnTheLastFriendsSkipFiveOrderedByName()
        {
            GenerateMock();

            List <Friend> list = new List <Friend>
            {
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Wayne", "Batman", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Banner", "Hulk", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Tony Stark", "Iron Man", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Natasha Romanoff", "Black Widow", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Clint Barton", "Hawkeye", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "James Rhodes", "War Machine", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Scott Lang", "Ant Man", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Carol Danvers", "Captain Marvel", "*****@*****.**")
            };

            var mockFriend = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Friend>()).Returns(mockFriend.Object);

            var repository = GetRepository();

            var query = repository.GetAllAsync(string.Empty, "name", "asc", 1, 5);

            var result = await query.ToListAsync();

            result.Should().HaveCount(3)
            .And.BeEquivalentTo(list.OrderBy(x => x.Name).Skip(5).Take(5).ToList())
            .And.BeInAscendingOrder(x => x.Name);
        }
Пример #25
0
        public void 寫入記憶體_時間相同_Guid_調用ICompare_由大到小排序_得到連續順序()
        {
            var testTables = new List <TestTable>();

            //arrange
            SequentialGuid.TimeNow = new DateTime(2010, 1, 1, 0, 0, 0, 0);
            for (var i = 1; i < 10000; i++)
            {
                var key   = SequentialGuid.NewGuid();
                var name  = i.ToString("000");
                var table = new TestTable {
                    Id = i, Name = name, Key = key
                };
                testTables.Add(table);
            }

            //act
            var tables = testTables.OrderByDescending(p => p.Key, new SequentialGuidComparer())
                         .ToList();

            var targetArray = tables.Select(p => p.Id).ToArray();

            var actual = this.IsReverseSequential(targetArray);

            //assert
            Assert.IsTrue(actual);
        }
        public async Task ShouldReturnOnlyFriendWithNameContainsName()
        {
            GenerateMock();

            List <Friend> list = new List <Friend>
            {
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Wayne", "Batman", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Banner", "Hulk", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Tony Stark", "Iron Man", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Natasha Romanoff", "Black Widow", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Clint Barton", "Hawkeye", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "James Rhodes", "War Machine", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Scott Lang", "Ant Man", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Carol Danvers", "Captain Marvel", "*****@*****.**")
            };

            var mockFriend = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Friend>()).Returns(mockFriend.Object);

            var repository = GetRepository();

            var query = repository.GetAllAsync("Bruce", "name", "desc", 0, 10);

            var result = await query.ToListAsync();

            result.Should().HaveCount(2)
            .And.BeEquivalentTo(list.Where(x => x.Name.Contains("Bruce")));
        }
Пример #27
0
        /// <summary>
        /// Handles the specified ex.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="additionalInfo">The additional information.</param>
        /// <param name="ignoreTracking">if set to <c>true</c> [ignore tracking].</param>
        public void Handle(Exception ex, NameValueCollection additionalInfo = null, bool ignoreTracking = false)
        {
            if (!TimeEventTracker.CanEvent(ex.Message, _eventTracking, out int occurrences) || ignoreTracking)
            {
                return;
            }

            additionalInfo = additionalInfo ?? new NameValueCollection();
            additionalInfo["TrackingId"] = SequentialGuid.NewGuid().ToString();
            additionalInfo["Time (UTC)"] = DateTime.UtcNow.ToString();

            if (occurrences != 0)
            {
                additionalInfo["Occurrences"] = occurrences.ToString("N0");
            }

            foreach (var handler in _exceptionHandlers)
            {
                try
                {
                    handler.Handle(ex, additionalInfo);
                }
                catch (Exception ex2)
                {
                    // one of the handlers screwed up.

                    var error            = $"Exception Handler: '{handler.Name}' threw an unhandled exception.";
                    var handlerException = new AggregateException(new Exception(error, ex2), ex);

                    var errorMessage = ExceptionFormatter.ConstructMessage(handlerException, additionalInfo);
                    _logger.LogError(errorMessage);
                }
            }
        }
        public async Task ShouldReturnTheFriendRequested()
        {
            GenerateMock();

            var           friend = Friend.Create(SequentialGuid.NewGuid(), "Scott Lang", "", "");
            List <Friend> list   = new List <Friend>
            {
                Friend.Create(SequentialGuid.NewGuid(), "Bruce", "Wayne", "*****@*****.**"),
                Friend.Create(SequentialGuid.NewGuid(), "Bruce Banner", "Banner", "*****@*****.**")
            };

            list.Add(friend);

            var mockFriend = list.AsQueryable().BuildMockDbSet();

            _contextMock.Setup(x => x.Set <Friend>()).Returns(mockFriend.Object);

            var query = GetRepository();

            var model = await query.GetAsync(friend.Id, default);

            model.Should().NotBeNull();
            model.Id.Should().Be(friend.Id);
            model.Name.Should().Be(friend.Name);
        }
Пример #29
0
        /// <summary>
        /// 上传至文件服务器
        /// </summary>
        private async Task <SimplyResult <Guid> > UploadFileServerAsync(byte[] fileBytes, string fileExt = null)
        {
            var fileId = SequentialGuid.NewGuid();

            var file = new
            {
                FileId   = fileId,
                FileName = string.IsNullOrEmpty(fileExt) ? fileId.ToString() : $"{fileId}.{fileExt}",
                Data     = fileBytes
            };

            try
            {
                var httpClient = m_HttpClientFactory.CreateClient("FileClient");
                var response   = await httpClient.PostAsJsonAsync("file/upload", file);

                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <WebApiResponse>(responseBody);
                if (!result.Success)
                {
                    throw new Exception(result.Error.Description);
                }

                return(SimplyResult.Ok(fileId));
            }
            catch (Exception ex)
            {
                m_Logger.LogError(ex, "上传文件失败");
                return(SimplyResult.Fail(nameof(Errors.RequestFileAPIFail), Errors.RequestFileAPIFail, Guid.Empty));
            }
        }
Пример #30
0
        private void UpdateDefinition(int rowIndex, PluginResult activityUpdateType)
        {
            ComboBox actionCombo      = (ComboBox)main_TableLayoutPanel.GetControlFromPosition(ACTION_COLUMN, rowIndex);
            TextBox  retryTextBox     = (TextBox)main_TableLayoutPanel.GetControlFromPosition(RETRY_LIMIT_COLUMN, rowIndex);
            var      delayTimeSpan    = (HP.ScalableTest.Framework.UI.TimeSpanControl)main_TableLayoutPanel.GetControlFromPosition(RETRY_DELAY_COLUMN, rowIndex);
            ComboBox retryActionCombo = (ComboBox)main_TableLayoutPanel.GetControlFromPosition(RETRY_ACTION_COLUMN, rowIndex);

            // Add it to all of the configurations
            foreach (var c in _configurations)
            {
                VirtualResourceMetadataRetrySetting retrySetting = new VirtualResourceMetadataRetrySetting();
                retrySetting.SettingId = SequentialGuid.NewGuid();
                retrySetting.State     = activityUpdateType.ToString();
                retrySetting.Action    = actionCombo.Text;
                int limitValue = 0;
                if (!int.TryParse(retryTextBox.Text, out limitValue))
                {
                    limitValue = 0;
                }
                retrySetting.RetryLimit          = limitValue;
                retrySetting.RetryDelay          = Convert.ToInt32(delayTimeSpan.Value.TotalSeconds);
                retrySetting.LimitExceededAction = retryActionCombo.Text;

                c.Metadata.VirtualResourceMetadataRetrySettings.Add(retrySetting);
            }
        }