Esempio n. 1
0
        public async Task ShouldUpdateBlobWhenGeneratingNextIdAfterEndOfBatch()
        {
            // Arrange
            using (var testScope = BuildTestScope())
            {
                var store = await BuildStoreAsync(testScope);

                var generator = new UniqueIdGenerator(store)
                {
                    BatchSize = 3
                };

                // Act
                await generator.NextIdAsync(testScope.IdScopeName); //1

                await generator.NextIdAsync(testScope.IdScopeName); //2

                await generator.NextIdAsync(testScope.IdScopeName); //3

                await generator.NextIdAsync(testScope.IdScopeName); //4

                // Assert
                Assert.AreEqual("7", await testScope.ReadCurrentPersistedValueAsync());
            }
        }
Esempio n. 2
0
        public static async Task Convert()
        {
            try
            {
                if (!Directory.Exists("RAW"))
                {
                    Output.WriteLine("RAW not found! Restoring!");
                    //await Content.Content.RestoreAsync();
                    Output.WriteLine("RAW Restored!");
                }
                if (!Directory.Exists("Database"))
                {
                    Directory.CreateDirectory("Database");
                }

                Output.WriteLine("Rebuilding");
                UniqueIdGenerator.Load();
                MapManager.Load(@"RAW\ini\GameMap.dat", Environment.CurrentDirectory + "\\RAW\\");
                Item.ItemFactory.LoadDb();
                await Task.WhenAll(MonsterDb.Load(), PortalDb.Load(), MagicTypeConverter.Load(), ItemBonusConverter.Load(), StatpointConverter.Load(), LevelExpConverter.Load());

                NpcDb.Load();
                await Db.SaveAsJsonAsync(SaveType.All);
            }
            catch (Exception e)
            {
                Output.WriteLine(e);
                Output.WriteLine("N***a, I couldn't load the Db, nor convert your old db. What the f**k are you doing?");
            }
        }
Esempio n. 3
0
        public void MaxWriteAttemptsShouldThrowArgumentOutOfRangeExceptionWhenValueIsNegative()
        {
            var store     = new Mock <IOptimisticDataStore>();
            var generator = new UniqueIdGenerator(store.Object);

            Assert.Throws <ArgumentOutOfRangeException>(() => generator.MaxWriteAttempts = -1);
        }
Esempio n. 4
0
 internal WebSocketContext(
     IHttpContextImpl httpContext,
     string webSocketVersion,
     IEnumerable <string> requestedProtocols,
     string?acceptedProtocol,
     IWebSocket webSocket,
     CancellationToken cancellationToken)
 {
     Id = UniqueIdGenerator.GetNext();
     CancellationToken  = cancellationToken;
     HttpContextId      = httpContext.Id;
     Session            = httpContext.Session;
     Items              = httpContext.Items;
     LocalEndPoint      = httpContext.LocalEndPoint;
     RemoteEndPoint     = httpContext.RemoteEndPoint;
     RequestUri         = httpContext.Request.Url;
     Headers            = httpContext.Request.Headers;
     Origin             = Headers[HttpHeaderNames.Origin];
     RequestedProtocols = requestedProtocols;
     AcceptedProtocol   = acceptedProtocol;
     WebSocketVersion   = webSocketVersion;
     Cookies            = httpContext.Request.Cookies;
     User               = httpContext.User;
     IsAuthenticated    = httpContext.Request.IsAuthenticated;
     IsLocal            = httpContext.Request.IsLocal;
     IsSecureConnection = httpContext.Request.IsSecureConnection;
     WebSocket          = webSocket;
 }
Esempio n. 5
0
        public void NoOutputFileName_GeneratesUniqueFileName(string outputDir)
        {
            // Arrange
            var timeBefore = ParseDateTimeFromFileName(UniqueIdGenerator.UniqueId());

            // Act
            var options = new ZipOptions()
            {
                Output    = outputDir,
                OverWrite = true,
                Input     = InputDir
            };

            var exitCode = new Compressor(options).Run();

            // Assert
            Assert.Equal(0, exitCode);
            var existingFiles = Directory.GetFiles(outputDir);

            var timeAfter = ParseDateTimeFromFileName(UniqueIdGenerator.UniqueId());
            var zipFiles  = existingFiles.Where(f =>
            {
                if (Path.GetExtension(f) == Compressor.OutputExtension)
                {
                    var fileDate = ParseDateTimeFromFileName(Path.GetFileNameWithoutExtension(f));
                    return(fileDate is not null && fileDate >= timeBefore && fileDate <= timeAfter);
                }

                return(false);
            });

            Assert.Single(zipFiles);
        }
        // REVIEW: named ValueTuple would be more readable
        private static Tuple <string, Dictionary <string, HTMLElement> > BuildTemplateAndParams(
            RenderElem <HTMLElement>[] tokens)
        {
            var innerHtmlTemplate = "";
            var controls          = new Dictionary <string, HTMLElement>();

            foreach (var t in tokens)
            {
                if (t.Iview != null)
                {
                    var id = UniqueIdGenerator.Generate();
                    innerHtmlTemplate += string.Format("<div id='{0}'></div>", id);
                    controls.Add(id.ToString(), t.Iview.Widget);
                    Logger.Debug(typeof(FormCanvasExtensions), "BuildTemplateAndParams() iview={0} with id={1}", t, id);
                    continue;
                }

                if (t.NativeItm != null)
                {
                    var id = UniqueIdGenerator.Generate();
                    innerHtmlTemplate += string.Format("<div id='{0}'></div>", id);
                    controls.Add(id.ToString(), t.NativeItm);
                    Logger.Debug(typeof(FormCanvasExtensions), "BuildTemplateAndParams() NativeItm={0} with id={1}", t, id);
                    continue;
                }

                innerHtmlTemplate += t.Token;
                Logger.Debug(typeof(FormCanvasExtensions), "BuildTemplateAndParams() literal={0}", t);
            }

            return(new Tuple <string, Dictionary <string, HTMLElement> >(innerHtmlTemplate, controls));
        }
Esempio n. 7
0
        public virtual MembershipUser ForgotPassword(Kooboo.CMS.Membership.Models.Membership membership, string userName)
        {
            var membershipUser = new MembershipUser()
            {
                Membership = membership, UserName = userName
            }.AsActual();
            List <DataViolationItem> violations = new List <DataViolationItem>();

            if (membershipUser == null)
            {
                violations.Add(new DataViolationItem("UserName", userName, "The member does not exists."));
            }
            if (violations.Count > 0)
            {
                throw new DataViolationException(violations);
            }

            var activateCode = UniqueIdGenerator.GetInstance().GetBase32UniqueId(10);

            membershipUser.ActivateCode = activateCode;

            _provider.Update(membershipUser, membershipUser);

            return(membershipUser);
        }
Esempio n. 8
0
    public async Task NoOutputFileName_GeneratesUniqueFileName(string outputDir)
    {
        // Arrange
        var timeBefore = ParseDateTimeFromFileName(UniqueIdGenerator.UniqueId());

        // Act
        var options = new CombineOptions()
        {
            Output    = outputDir,
            OverWrite = true,
            Input     = InputDir,
            Suffix    = CombinerTestsFixture.DefaultSuffix
        };

        var exitCode = await new Combiner(options).Run();

        // Assert
        Assert.Equal(0, exitCode);
        var existingFiles = Directory.GetFiles(outputDir);

        var timeAfter        = ParseDateTimeFromFileName(UniqueIdGenerator.UniqueId());
        var csGeneratedFiles = existingFiles.Where(f =>
        {
            if (Path.GetExtension(f) == Combiner.OutputExtension)
            {
                var fileDate = ParseDateTimeFromFileName(Path.GetFileNameWithoutExtension(f).Replace(options.Suffix, string.Empty));
                return(fileDate is not null && fileDate >= timeBefore && fileDate <= timeAfter);
            }

            return(false);
        });

        Assert.Single(csGeneratedFiles);
    }
Esempio n. 9
0
        public static Task <string> RegisterMediaAsset(string fileContent)
        {
            var requestId = UniqueIdGenerator.GenerateAsString();

            var impl = GetImpl();

            if (impl == null)
            {
                Logger.Debug(typeof(IawAppApi), "has no proper IAWApp API");
                return(Task.FromResult(fileContent.Length.ToString()));
            }

            //androidPostMediaAssetReady(webRequestIdUriEncoded : string, properMediaFileId : string) : void;
            return(Task.FromPromise <string>(
                       new TypeSafePromise <string>((onSucc, onFail) => {
                IAWAppHostApi.RegisterPostMediaAssetReady(requestId, x => onSucc(x));

                try {
                    impl.registerMediaAsset(requestId, fileContent);
                } catch (Exception ex) {
                    Logger.Error(typeof(IawAppApi), "registerMediaAsset got exception {0}", ex);
                    IAWAppHostApi.UnregisterPostMediaAssetReady(requestId);
                    onFail(ex);
                }
            }),
                       (Func <string, string>)(x => x)));
        }
Esempio n. 10
0
        public PageDesignContent(PagePosition pos)
            : base()
        {
            if (pos == null)
            {
                throw new ArgumentNullException();
            }

            if (string.IsNullOrEmpty(pos.PagePositionId))
            {
                //pos.PagePositionId = Guid.NewGuid().ToString();
                pos.PagePositionId = UniqueIdGenerator.GetInstance().GetBase32UniqueId(5);
            }

            this.Position = pos;

            //this.TagName = "li";

            this.ClassName = "pagedesign-content";

            this.Parameter.Add("Name", PageDesignContent.Code(this.ToString()));

            this.Parameter.Add("PagePositionId", PageDesignContent.Code(pos.PagePositionId));

            this.Parameter.Add("Order", pos.Order.ToString());

            this.Parameter.Add("Type", this.GetTypeKey());
        }
Esempio n. 11
0
        public void GetBase32UniqueIdTest()
        {
            var b1 = new byte[16];

            for (int i = 0; i < 16; i++)
            {
                b1[i] = 0;
            }
            string id = UniqueIdGenerator.GetInstance().GetBase32UniqueId(b1, 26);

            Assert.AreEqual(26, id.Length);
            Assert.AreEqual(new string( '2', 26 ), id);

            b1 = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF };
            id = UniqueIdGenerator.GetInstance().GetBase32UniqueId(b1, 26);
            System.Diagnostics.Trace.WriteLine(id);
            Assert.AreEqual(26, id.Length);
            Assert.AreEqual("ZZZZZZ", id.Substring(20, 6));

            id = UniqueIdGenerator.GetInstance().GetBase32UniqueId(b1, 6);
            System.Diagnostics.Trace.WriteLine(id);
            Assert.AreEqual(6, id.Length);
            Assert.AreEqual("ZZZZZZ", id);

            id = UniqueIdGenerator.GetInstance().GetBase32UniqueId(18);
            System.Diagnostics.Trace.WriteLine(id);
            Assert.AreEqual(18, id.Length);

            var id2 = UniqueIdGenerator.GetInstance().GetBase32UniqueId(18);

            System.Diagnostics.Trace.WriteLine(id2);
            Assert.AreEqual(18, id2.Length);

            Assert.AreNotEqual(id, id2);
        }
Esempio n. 12
0
        public virtual ActionResult TempFile()
        {
            var entry = new JsonResultEntry();

            try
            {
                if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    var postFile       = Request.Files[0];
                    var repositoryPath = new RepositoryPath(Repository);
                    var tempPath       = Kooboo.Web.Url.UrlUtility.Combine(repositoryPath.VirtualPath, "Temp");
                    Kooboo.IO.IOUtility.EnsureDirectoryExists(Server.MapPath(tempPath));

                    var fileUrl = Kooboo.Web.Url.UrlUtility.Combine(tempPath, UniqueIdGenerator.GetInstance().GetBase32UniqueId(24) + Path.GetExtension(postFile.FileName));

                    postFile.SaveAs(Server.MapPath(fileUrl));
                    entry.Model = Url.Content(fileUrl);
                }
                else
                {
                    entry.SetFailed().AddMessage("It is not a valid image file.".Localize());
                }
            }
            catch (Exception e)
            {
                entry.AddException(e);
            }

            return(Json(entry));
        }
Esempio n. 13
0
        public void ShouldReturnIdsFromThirdBatchIfSecondBatchTakenByAnotherGenerator()
        {
            // Arrange
            using (var testScope = BuildTestScope())
            {
                var store1     = BuildStore(testScope);
                var generator1 = new UniqueIdGenerator(store1)
                {
                    BatchSize = 3
                };
                var store2     = BuildStore(testScope);
                var generator2 = new UniqueIdGenerator(store2)
                {
                    BatchSize = 3
                };

                // Act
                generator1.NextId(testScope.IdScopeName);              //1
                generator1.NextId(testScope.IdScopeName);              //2
                generator1.NextId(testScope.IdScopeName);              //3
                generator2.NextId(testScope.IdScopeName);              //4
                var lastId = generator1.NextId(testScope.IdScopeName); //7

                // Assert
                Assert.AreEqual(7, lastId);
            }
        }
Esempio n. 14
0
File: NpcDb.cs Progetto: Pircs/Yi
 public static void Load()
 {
     Collections.Npcs.Clear();
     foreach (var file in Directory.EnumerateFileSystemEntries("RAW\\Npcs\\"))
     {
         using (var reader = new KeyValueFormat(file))
         {
             var obj = new Npc
             {
                 UniqueId = reader.Load <int>("id"),
                 Type     = reader.Load <byte>("type"),
                 Look     = reader.Load <uint>("lookface"),
                 MapId    = reader.Load <ushort>("mapid"),
                 Base     = reader.Load <byte>("base"),
                 Sort     = reader.Load <byte>("sort")
             };
             UniqueIdGenerator.Goto(obj.UniqueId, EntityType.Npc);
             obj.Location.X = reader.Load <ushort>("cellx");
             obj.Location.Y = reader.Load <ushort>("celly");
             if (obj.MapId == 0)
             {
                 continue;
             }
             if (GameWorld.Maps.ContainsKey(obj.MapId))
             {
                 Collections.Npcs.Add(obj.UniqueId, obj);
                 GameWorld.Maps[obj.MapId].LoadInEntity(obj);
             }
         }
     }
     DynamicNpcDb.Load();
 }
Esempio n. 15
0
        public async Task ShouldReturnIdsFromThirdBatchIfSecondBatchTakenByAnotherGenerator()
        {
            // Arrange
            using (var testScope = BuildTestScope())
            {
                var store1 = await BuildStoreAsync(testScope);

                var generator1 = new UniqueIdGenerator(store1)
                {
                    BatchSize = 3
                };
                var store2 = await BuildStoreAsync(testScope);

                var generator2 = new UniqueIdGenerator(store2)
                {
                    BatchSize = 3
                };

                // Act
                await generator1.NextIdAsync(testScope.IdScopeName);              //1

                await generator1.NextIdAsync(testScope.IdScopeName);              //2

                await generator1.NextIdAsync(testScope.IdScopeName);              //3

                await generator2.NextIdAsync(testScope.IdScopeName);              //4

                var lastId = await generator1.NextIdAsync(testScope.IdScopeName); //7

                // Assert
                Assert.AreEqual(7, lastId);
            }
        }
Esempio n. 16
0
        public virtual ActionResult ImageCrop()
        {
            var data = new JsonResultData(ModelState);

            data.RunWithTry((resultData) =>
            {
                if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    var postFile       = Request.Files[0];
                    var repositoryPath = new RepositoryPath(Repository);
                    var tempPath       = Kooboo.Web.Url.UrlUtility.Combine(repositoryPath.VirtualPath, "Temp");
                    Kooboo.IO.IOUtility.EnsureDirectoryExists(Server.MapPath(tempPath));

                    var fileUrl = Kooboo.Web.Url.UrlUtility.Combine(tempPath, UniqueIdGenerator.GetInstance().GetBase32UniqueId(24) + Path.GetExtension(postFile.FileName));

                    postFile.SaveAs(Server.MapPath(fileUrl));
                    resultData.Model = new { ImageUrl = Url.Content(fileUrl), PreviewUrl = this.Url.Action("ResizeImage", "Resource", new { siteName = Site.FullName, url = fileUrl, area = "", width = 600, height = 400, preserverAspectRatio = true, quality = 80 }) };
                }
                else
                {
                    resultData.AddErrorMessage("It is not a valid image file.".Localize());
                }
            });

            return(Json(data));
        }
Esempio n. 17
0
        /// <summary> returns tooltipcontainer and tooltip</summary>
        private Tuple <HTMLElement, HTMLElement> GetOrCreateTooltipOn(HTMLElement tooltipOn, string content, TooltipMode mode)
        {
            if (_tooltips.ContainsKey(tooltipOn))
            {
                var oldTt = _tooltips.Get(tooltipOn).Item1;
                oldTt.TextContent = content;
                return(Tuple.Create(oldTt.ParentElement, oldTt));
            }

            //tooltips need to be in container so that relative positioning works in both:
            //inline scenario: <label><input><tooltip> and in
            //'display:table' scenario those three have "display: table-cell"
            var ttCont = Document.CreateElement("span");

            ttCont.ClassName = Magics.CssClassTooltipContainer;

            var tt = Document.CreateElement("span");

            tt.Id          = UniqueIdGenerator.GenerateAsString();
            tt.TextContent = content;
            tt.ClassName   = Magics.CssClassTooltip;
            tt.ClassList.Add(Magics.CssClassDisabled);

            ttCont.AppendChild(tt);

            Logger.Debug(GetType(), "created tooltip to show it {0}", tt.Id);
            _tooltips[tooltipOn] = Tuple.Create(tt, mode);

            return(Tuple.Create(ttCont, tt));
        }
Esempio n. 18
0
        public UserTable()
        {
            try
            {
                // Retrieve the storage account from the connection string.
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

                // Create the IdTableClient client.
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

                // Create the CloudTable object that represents the "people" IdTableClient.
                UserTableClient = tableClient.GetTableReference(UserTableName);

                _uniqueIdGenerator = new UniqueIdGenerator(new BlobOptimisticDataStore(storageAccount, "UniqueIdGenerator"));

                _retryPolicy = BotConnectorUtility.BuildRetryPolicy();
            }
            catch (System.Exception e)
            {
                WebApiConfig.TelemetryClient.TrackException(e, new Dictionary <string, string>
                {
                    { "debugNote", "failed to init OnlineStatus table client" },
                });
                throw;
            }
        }
Esempio n. 19
0
        public void ShouldReturnIdsFromThirdBatchIfSecondBatchTakenByAnotherGenerator()
        {
            // Arrange
            var account = CloudStorageAccount.DevelopmentStorageAccount;

            using (var testScope = new TestScope(account))
            {
                var store1     = new BlobOptimisticDataStore(account, testScope.ContainerName);
                var generator1 = new UniqueIdGenerator(store1)
                {
                    BatchSize = 3
                };
                var store2     = new BlobOptimisticDataStore(account, testScope.ContainerName);
                var generator2 = new UniqueIdGenerator(store2)
                {
                    BatchSize = 3
                };

                // Act
                generator1.NextId(testScope.IdScopeName);              //1
                generator1.NextId(testScope.IdScopeName);              //2
                generator1.NextId(testScope.IdScopeName);              //3
                generator2.NextId(testScope.IdScopeName);              //4
                var lastId = generator1.NextId(testScope.IdScopeName); //7

                // Assert
                Assert.AreEqual(7, lastId);
            }
        }
Esempio n. 20
0
        public static void Handle(Player player, byte[] buffer)
        {
            fixed(byte *p = buffer)
            {
                var packet = *(MsgNpcSpawn *)p;

                BufferPool.RecycleBuffer(buffer);

                var npc = new Npc
                {
                    UniqueId = UniqueIdGenerator.GetNext(EntityType.DynamicNpc),
                    MapId    = player.MapId,
                    Location =
                    {
                        X = packet.X,
                        Y = packet.Y
                    },
                    Look      = packet.Look,
                    Type      = 2,
                    Direction = (Direction)(packet.Look % 10)
                };

                GameWorld.Maps[player.MapId].LoadInEntity(npc);
                ScreenSystem.Create(npc);
                ScreenSystem.SendSpawn(npc);
                Collections.Npcs.Add(npc.UniqueId, npc);
            }
        }
        public void GetNext_ReturnsValidString()
        {
            var id = UniqueIdGenerator.GetNext();

            Assert.IsNotNull(id);
            Assert.IsNotEmpty(id);
        }
Esempio n. 22
0
File: Portaldb.cs Progetto: Pircs/Yi
 public static Task Load()
 {
     return(Task.Run(() =>
     {
         foreach (var portalFile in Directory.GetDirectories("RAW\\Portals\\").SelectMany(Directory.GetFiles))
         {
             using (var reader = new KeyValueFormat(portalFile))
             {
                 var obj = new Portal
                 {
                     MapId = reader.Load <ushort>("FromMap"),
                     ToMap = reader.Load <ushort>("ToMap"),
                     ToX = reader.Load <ushort>("ToX"),
                     ToY = reader.Load <ushort>("ToY"),
                     UniqueId = UniqueIdGenerator.GetNext(EntityType.Portal)
                 };
                 obj.Location.X = reader.Load <ushort>("FromX");
                 obj.Location.Y = reader.Load <ushort>("FromY");
                 if (obj.MapId == 0)
                 {
                     continue;
                 }
                 if (GameWorld.Maps.ContainsKey(obj.MapId))
                 {
                     Portal.Portals.Add(obj.UniqueId, obj);
                     //GameWorld.Maps[obj.MapId].LoadInEntity(obj);
                 }
             }
         }
     }));
 }
Esempio n. 23
0
        public void ShouldReturnIdsAcrossMultipleGenerators()
        {
            // Arrange
            using (var testScope = BuildTestScope())
            {
                var store1     = BuildStore(testScope);
                var generator1 = new UniqueIdGenerator(store1)
                {
                    BatchSize = 3
                };
                var store2     = BuildStore(testScope);
                var generator2 = new UniqueIdGenerator(store2)
                {
                    BatchSize = 3
                };

                // Act
                var generatedIds = new[]
                {
                    generator1.NextId(testScope.IdScopeName), //1
                    generator1.NextId(testScope.IdScopeName), //2
                    generator1.NextId(testScope.IdScopeName), //3
                    generator2.NextId(testScope.IdScopeName), //4
                    generator1.NextId(testScope.IdScopeName), //7
                    generator2.NextId(testScope.IdScopeName), //5
                    generator2.NextId(testScope.IdScopeName), //6
                    generator2.NextId(testScope.IdScopeName), //10
                    generator1.NextId(testScope.IdScopeName), //8
                    generator1.NextId(testScope.IdScopeName)  //9
                };

                // Assert
                Assert.Equal(new long[] { 1, 2, 3, 4, 7, 5, 6, 10, 8, 9 }, generatedIds);
            }
        }
Esempio n. 24
0
        private string GetOutputFilePath()
        {
            string composeFileName(string fileNameWithoutExtension) =>
            (_options.Prefix ?? string.Empty) +
            fileNameWithoutExtension +
            (_options.Suffix ?? string.Empty) +
            OutputExtension;

            string fileName = composeFileName(UniqueIdGenerator.UniqueId());
            string basePath = File.Exists(_options.Input)
                ? Path.GetDirectoryName(_options.Input) ?? throw new CombineException($"{_options.Input} parent dir not found, try providing an absolute or relative path")
                : _options.Input !;

            if (_options.Output is not null)
            {
                if (Path.EndsInDirectorySeparator(_options.Output))
                {
                    basePath = _options.Output.ReplaceEndingDirectorySeparatorWithProperEndingDirectorySeparator();
                    Directory.CreateDirectory(basePath);
                }
                else
                {
                    var directoryName = Path.GetDirectoryName(_options.Output);

                    basePath = string.IsNullOrEmpty(directoryName)
                        ? _options.Input + Path.DirectorySeparatorChar
                        : Directory.CreateDirectory(directoryName).FullName;

                    fileName = composeFileName(Path.GetFileNameWithoutExtension(_options.Output));
                }
            }

            return(Path.Combine(basePath, fileName));
        }
Esempio n. 25
0
        public async Task ShouldSupportUsingMultipleGeneratorsFromMultipleThreads()
        {
            // Arrange
            using (var testScope = BuildTestScope())
            {
                var store = await BuildStoreAsync(testScope);

                var generator = new UniqueIdGenerator(store)
                {
                    BatchSize = 1000
                };
                var store2 = await BuildStoreAsync(testScope);

                var generator2 = new UniqueIdGenerator(store2)
                {
                    BatchSize = 1000
                };
                const int testLength = 10000;

                // Act
                var generatedIds = new ConcurrentQueue <long>();
                var threadIds    = new ConcurrentQueue <int>();
                var scopeName    = testScope.IdScopeName;

                var listToExecute = new List <int>();
                for (int i = 0; i < testLength; i++)
                {
                    listToExecute.Add(i);
                }

                var tasks = listToExecute.ForEachAsync(10, async item =>
                {
                    var idToAdd = await generator.NextIdAsync(scopeName);
                    generatedIds.Enqueue(idToAdd);
                    threadIds.Enqueue(Thread.CurrentThread.ManagedThreadId);
                });
                var tasks2 = listToExecute.ForEachAsync(10, async item =>
                {
                    var idToAdd = await generator2.NextIdAsync(scopeName);
                    generatedIds.Enqueue(idToAdd);
                    threadIds.Enqueue(Thread.CurrentThread.ManagedThreadId);
                });

                await Task.WhenAll(tasks, tasks2);

                // Assert we generated the right count of ids
                Assert.AreEqual(testLength * 2, generatedIds.Count, "wrong number of ids generated");

                // Assert there were no duplicates
                Assert.IsFalse(generatedIds.GroupBy(n => n).Any(g => g.Count() != 1), "duplicated ids were generated");

                // Assert we used multiple threads
                var uniqueThreadsUsed = threadIds.Distinct().Count();
                if (uniqueThreadsUsed == 1)
                {
                    Assert.Inconclusive("The test failed to actually utilize multiple threads. {0} uniqueThreadsUsed", uniqueThreadsUsed);
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// C'tor
 /// </summary>
 protected AbstractGuiElement()
 {
     UniqueId = UniqueIdGenerator.GetString();
     SetMouseEnabled(true);
     SetLayout(new BaseLayout(this));
     SetStyle(null);
     _eventDispatcher = new EventDispatcher(this);
 }
 private void PreBuild()
 {
     if (refundRequest.RequestHeader.TransactionId == null)
     {
         refundRequest.RequestHeader.TransactionId       = UniqueIdGenerator.GenerateTransactionId();
         refundRequest.RequestHeader.TransactionDateTime = DateTime.Now.ToString("yyyyMMddHHmmss") + "000";
     }
 }
 private void PreBuild()
 {
     if (queryStatuRequest.RequestHeader.TransactionId == null)
     {
         queryStatuRequest.RequestHeader.TransactionId       = (UniqueIdGenerator.GenerateTransactionId());
         queryStatuRequest.RequestHeader.TransactionDateTime = DateTime.Now.ToString("yyyyMMddHHmmss") + "000";
     }
 }
Esempio n. 29
0
        public static async Task <bool> Load()
        {
            try
            {
                UniqueIdGenerator.Load();
                LoadItems();
                SquigglyDb.LoadMaps();
                SquigglyDb.LoadMobs();
                SquigglyDb.LoadSpawns();
                SquigglyDb.LoadNpcs();
                SquigglyDb.LoadLevelExp();
                SquigglyDb.LoadPortals();
                SquigglyDb.LoadItemBonus();
                SquigglyDb.Spawn();

                await Task.WhenAll(LoadStatpoints(), LoadSkills(), LoadAccounts(),
                                   LoadFloorItems(), LoadStoragePool(), LoadBoothPool());


                StorageSystem.SetUpStorageSpaces();
                BoothSystem.SetUpBooths();
                FloorItemSystem.SetUpFloorItemSystem();

                Output.WriteLine("|------------ Player Data ------------");
                Output.WriteLine("|");
                Output.WriteLine("|---> Accounts:     " + SelectorSystem.Players.Count);
                Output.WriteLine("|---> Storages:     " + StorageSystem.StoragePool.Count);
                Output.WriteLine("|---> Booths:       " + BoothSystem.BoothPool.Count);
                Output.WriteLine("|");
                Output.WriteLine("|------------ Common Data ------------");
                Output.WriteLine("|");
                Output.WriteLine("|---> Bots:         " + GameWorld.CountBots());
                Output.WriteLine("|---> Monsters:     " + GameWorld.CountMonsters());
                Output.WriteLine("|---> Npcs:         " + GameWorld.CountNpcs());
                Output.WriteLine("|---> DynamicNpcs:  " + GameWorld.CountDynNpcs());
                Output.WriteLine("|---> Maps:         " + GameWorld.Maps.Count);
                Output.WriteLine("|---> FloorItems:   " + FloorItemSystem.FloorItems.Count);
                Output.WriteLine("|---> Items:        " + Collections.Items.Count);
                Output.WriteLine("|---> ItemBonus:    " + Collections.ItemBonus.Count);
                Output.WriteLine("|---> LevelExp:     " + Collections.LevelExps.Count);
                Output.WriteLine("|---> StatPoints:   " + Collections.Statpoints.Count);
                Output.WriteLine("|---> Skills:       " + Collections.Skills.Count);
                Output.WriteLine("|---> Portals:      " + Collections.Portals.Count);
                Output.WriteLine("|---> Mob Drops:    " + MobDropSystem.Drops.Count);
                await SetUpScriptingEngine();

                Output.WriteLine("|-------------------------------------");
                Output.WriteLine("");
                GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency;
                YiCore.CompactLoh();
                return(true);
            }
            catch (Exception ex)
            {
                Output.WriteLine(ex);
                return(false);
            }
        }
 /**
  * Requet başlatılır.
  *
  * ReferenceNumber: Üye işyeritarfından üretilen tekil değerdir. Provisiona özgüdür. ilk 3 hanesi
  * Paycell tarafından üye işyeri için tanımlanır. 20 haneli numerik bir değerdir.
  *
  * MerchantCode: Paycell taraffından üye iş yeri için tanımlanır.
  */
 public ProvisionForMarketPlaceRequestFactory()
 {
     request = new provisionForMarketPlaceRequest()
     {
         requestHeader   = CreateRequestHeader(),
         referenceNumber = UniqueIdGenerator.GenerateReferanceNumber(),
         merchantCode    = Constants.MERCHANT_CODE
     };
 }
        public void NextIdShouldThrowExceptionOnNullData()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetData("test").Returns((string)null);

            var generator = new UniqueIdGenerator(store);

            generator.NextId("test");
        }
        public void NextIdShouldReturnNumbersSequentially()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetNextBatch("test", 3).Returns(1, 251);

            var subject = new UniqueIdGenerator(store) { BatchSize = 3 };

            Assert.AreEqual(1, subject.NextId("test"));
            Assert.AreEqual(2, subject.NextId("test"));
            Assert.AreEqual(3, subject.NextId("test"));
        }
        public void NextIdShouldRollOverToNewBlockWhenCurrentBlockIsExhausted()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetNextBatch("test", 3).Returns(1, 251);

            var subject = new UniqueIdGenerator(store) { BatchSize = 3 };

            Assert.AreEqual(1, subject.NextId("test"));
            Assert.AreEqual(2, subject.NextId("test"));
            Assert.AreEqual(3, subject.NextId("test"));
            Assert.AreEqual(251, subject.NextId("test"));
            Assert.AreEqual(252, subject.NextId("test"));
            Assert.AreEqual(253, subject.NextId("test"));
        }
Esempio n. 34
0
        public void NextIdShouldReturnNumbersSequentially()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetData("test").Returns("0", "250");
            store.TryOptimisticWrite("test", "3").Returns(true);

            var subject = new UniqueIdGenerator(store)
            {
                BatchSize = 3
            };

            Assert.AreEqual(0, subject.NextId("test"));
            Assert.AreEqual(1, subject.NextId("test"));
            Assert.AreEqual(2, subject.NextId("test"));
        }
        public void NextIdShouldThrowExceptionWhenRetriesAreExhausted()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetNextBatch("test", 100).Returns(-1, -1, -1, 1);

            var generator = new UniqueIdGenerator(store) { MaxWriteAttempts = 3 };

            try
            {
                generator.NextId("test");
            }
            catch (Exception ex)
            {
                StringAssert.StartsWith("Failed to update the data store after 3 attempts.", ex.Message);
                return;
            }
            Assert.Fail("NextId should have thrown and been caught in the try block");
        }
Esempio n. 36
0
        public void NextIdShouldRollOverToNewBlockWhenCurrentBlockIsExhausted()
        {
            var store = Substitute.For<IOptimisticDataStore>();
            store.GetData("test").Returns("0", "250");
            store.TryOptimisticWrite("test", "3").Returns(true);
            store.TryOptimisticWrite("test", "253").Returns(true);

            var subject = new UniqueIdGenerator(store)
            {
                BatchSize = 3
            };

            Assert.AreEqual(0, subject.NextId("test"));
            Assert.AreEqual(1, subject.NextId("test"));
            Assert.AreEqual(2, subject.NextId("test"));
            Assert.AreEqual(250, subject.NextId("test"));
            Assert.AreEqual(251, subject.NextId("test"));
            Assert.AreEqual(252, subject.NextId("test"));
        }
Esempio n. 37
0
        public void UniqueIdGeneratorWithMongoDBClientConstructorDataSource()
        {
            MongoClientSettings settings = new MongoClientSettings();
            settings.Server = new MongoServerAddress("localhost", 27017);

            UniqueIdGenerator generator = new UniqueIdGenerator(new MongoOptimisticDataStore(settings, "SnowMaker", "IntegrationTests"));
            string blockName = Guid.NewGuid().ToString();

            generator.BatchSize = 5;

            Assert.AreEqual(1, generator.NextId(blockName));
            Assert.AreEqual(2, generator.NextId(blockName));
            Assert.AreEqual(3, generator.NextId(blockName));
            Assert.AreEqual(4, generator.NextId(blockName));
            Assert.AreEqual(5, generator.NextId(blockName));
            Assert.AreEqual(6, generator.NextId(blockName));
            Assert.AreEqual(7, generator.NextId(blockName));
        }
Esempio n. 38
0
        public void UniqueIdGeneratorWithMongoDBDataSource()
        {
            UniqueIdGenerator generator = new UniqueIdGenerator(new MongoOptimisticDataStore());
            string blockName = Guid.NewGuid().ToString();

            generator.BatchSize = 5;

            Assert.AreEqual(1, generator.NextId(blockName));
            Assert.AreEqual(2, generator.NextId(blockName));
            Assert.AreEqual(3, generator.NextId(blockName));
            Assert.AreEqual(4, generator.NextId(blockName));
            Assert.AreEqual(5, generator.NextId(blockName));
            Assert.AreEqual(6, generator.NextId(blockName));
            Assert.AreEqual(7, generator.NextId(blockName));
        }
Esempio n. 39
0
        public void UniqueIdGeneratorWithMongoDBDataSourceMany()
        {
            UniqueIdGenerator gen1 = new UniqueIdGenerator(new MongoOptimisticDataStore());
            string blockName = Guid.NewGuid().ToString();

            gen1.BatchSize = 5;

            Assert.AreEqual(1, gen1.NextId(blockName));
            Assert.AreEqual(2, gen1.NextId(blockName));
            Assert.AreEqual(3, gen1.NextId(blockName));

            UniqueIdGenerator gen2 = new UniqueIdGenerator(new MongoOptimisticDataStore());
            gen2.BatchSize = 5;

            Assert.AreEqual(6, gen2.NextId(blockName));
            Assert.AreEqual(7, gen2.NextId(blockName));
            Assert.AreEqual(8, gen2.NextId(blockName));
            Assert.AreEqual(9, gen2.NextId(blockName));

            UniqueIdGenerator gen3 = new UniqueIdGenerator(new MongoOptimisticDataStore());
            gen3.BatchSize = 50;
            Assert.AreEqual(11, gen3.NextId(blockName));

            UniqueIdGenerator gen4 = new UniqueIdGenerator(new MongoOptimisticDataStore());
            gen4.BatchSize = 50;
            Assert.AreEqual(61, gen4.NextId(blockName));
        }
Esempio n. 40
0
 public BusinessLogic(Repository repository, UniqueIdGenerator uniqueIdGenerator, DateService dateService)
 {
     this.repository = repository;
       this.uniqueIdGenerator = uniqueIdGenerator;
       this.dateService = dateService;
 }