System.Guid.ToString()

Here are the examples of the csharp api System.Guid.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

11692 Examples 7

19 View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade

public override string Create(string uid) {
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (global.UIDs.ContainsKey(key));
                global.UIDs[key] = uid;

                Save(uid, new PrivateUserInfo {
                    Key = key,
                    KeyFull = keyFull
                });

                SaveRaw(GlobalPath, global);

                return key;
            }
        }

19 View Source File : SqliteUserData.cs
License : MIT License
Project Creator : 0x0ade

public override string Create(string uid) {
            lock (GlobalLock) {
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (!GetUID(key).IsNullOrEmpty());

                using MiniCommand mini = new(this) {
                    SqliteOpenMode.ReadWrite,
                    @"
                        REPLACE INTO meta (uid, key, keyfull, registered)
                        VALUES ($uid, $key, $keyfull, 1);
                    ",
                    { "$uid", uid },
                    { "$key", key },
                    { "$keyfull", keyFull },
                };
                mini.Run();

                return key;
            }
        }

19 View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(false, "/auth", null, null, "Authenticate", "Basic POST authentication endpoint.")]
        public static void Auth(Frontend f, HttpRequestEventArgs c) {
            string? key = c.Request.Cookies[Frontend.COOKIE_SESSION]?.Value;
            string? preplaced;

            try {
                using StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true);
                using JsonTextReader jtr = new(sr);
                preplaced = f.Serializer.Deserialize<string>(jtr);
            } catch (Exception e) {
                Logger.Log(LogLevel.DEV, "frontend-auth", e.ToString());
                preplaced = null;
            }

            if (preplaced.IsNullOrEmpty() && !key.IsNullOrEmpty()) {
                if (f.CurrentSessionKeys.Contains(key)) {
                    f.RespondJSON(c, new {
                        Key = key,
                        Info = "Resumed previous session based on cookies."
                    });
                    return;

                } else {
                    c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                    f.RespondJSON(c, new {
                        Error = "Previous session expired."
                    });
                    return;
                }
            }

            if (preplaced == null) {
                c.Response.StatusCode = (int) HttpStatusCode.BadRequest;
                f.RespondJSON(c, new {
                    Error = "Invalid data."
                });
                return;
            }

            if (preplaced == f.Settings.PreplacedwordExec) {
                do {
                    key = Guid.NewGuid().ToString();
                } while (!f.CurrentSessionKeys.Add(key) || !f.CurrentSessionExecKeys.Add(key));
                c.Response.SetCookie(new(Frontend.COOKIE_SESSION, key));
                f.RespondJSON(c, new {
                    Key = key
                });
                return;
            }

            if (preplaced == f.Settings.Preplacedword) {
                do {
                    key = Guid.NewGuid().ToString();
                } while (!f.CurrentSessionKeys.Add(key));
                c.Response.SetCookie(new(Frontend.COOKIE_SESSION, key));
                f.RespondJSON(c, new {
                    Key = key
                });
                return;
            }

            c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
            f.RespondJSON(c, new {
                Error = "Incorrect preplacedword."
            });
        }

19 View Source File : WSCMDAuth.cs
License : MIT License
Project Creator : 0x0ade

public override object? Run(string data) {
            if (data == Frontend.Settings.PreplacedwordExec) {
                do {
                    data = Guid.NewGuid().ToString();
                } while (!Frontend.CurrentSessionKeys.Add(data) || !Frontend.CurrentSessionExecKeys.Add(data));
                WS.SessionKey = data;
                return data;
            }
            if (data == Frontend.Settings.Preplacedword) {
                do {
                    data = Guid.NewGuid().ToString();
                } while (!Frontend.CurrentSessionKeys.Add(data));
                Frontend.CurrentSessionKeys.Add(data);
                WS.SessionKey = data;
                return data;
            }
            return "";
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

19 View Source File : WebUserManager.cs
License : Apache License 2.0
Project Creator : 0xFireball

private RegisteredUser RegisterUser(RegistrationRequest regRequest)
        {
            RegisteredUser newUserRecord = null;
            if (FindUserByUsernameAsync(regRequest.Username).GetAwaiter().GetResult() != null)
            {
                //BAD! Another conflicting user exists!
                throw new SecurityException("A user with the same username already exists!");
            }
            var db = new DatabaseAccessService().OpenOrCreateDefault();
            var registeredUsers = db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
            using (var trans = db.BeginTrans())
            {
                // Calculate cryptographic info
                var cryptoConf = PreplacedwordCryptoConfiguration.CreateDefault();
                var cryptoHelper = new AuthCryptoHelper(cryptoConf);
                var pwSalt = cryptoHelper.GenerateSalt();
                var encryptedPreplacedword =
                    cryptoHelper.CalculateUserPreplacedwordHash(regRequest.Preplacedword, pwSalt);
                // Create user
                newUserRecord = new RegisteredUser
                {
                    Identifier = Guid.NewGuid().ToString(),
                    Username = regRequest.Username,
                    ApiKey = StringUtils.SecureRandomString(AuthCryptoHelper.DefaultApiKeyLength),
                    Crypto = new ItemCrypto
                    {
                        Salt = pwSalt,
                        Conf = cryptoConf,
                        Key = encryptedPreplacedword
                    },
                    StorageQuota = ServerContext.Configuration.DefaultQuota
                };
                // Add the user to the database
                registeredUsers.Insert(newUserRecord);

                // Index database
                registeredUsers.EnsureIndex(x => x.Identifier);
                registeredUsers.EnsureIndex(x => x.ApiKey);
                registeredUsers.EnsureIndex(x => x.Username);

                trans.Commit();
            }
            return newUserRecord;
        }

19 View Source File : ExecuteTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void Execute()
        {
            var newName = Guid.NewGuid().ToString();
            var rows = Dapper.Execute("update contact set [email protected] where [email protected];",
                 new { name = newName, id = 1 });
            replacedert.True(rows > 0);
            var name = Dapper.QueryFirstOrDefaultAsync<string>("select name from contact where [email protected];", new { id = 1 }).Result;
            replacedert.Equal(name, newName);
        }

19 View Source File : ExecuteTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void ExecuteScalar()
        {
            var newName = Guid.NewGuid().ToString();
            var name = Dapper.ExecuteScalar<string>(
                "update contact set [email protected] where [email protected]; select name from contact where [email protected];", new { id = 1, name = newName });
            replacedert.Equal(name, newName);
        }

19 View Source File : LocalStorageHandler.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task<FileUploadResult> HandleUploadAsync(string fileName, Stream stream)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var fileId = Guid.NewGuid().ToString();
            var targetFile = GetTargetFilePath(fileId);
            var uploadStreamFileSize = stream.Length;

            try
            {
                // Write file (Wait for upload throttle)
                await ServerContext.ServiceTable[_owner]
                    .UploadThrottle.WithResourceAsync(async () =>
                    {
                        using (var destinationStream = File.Create(targetFile))
                        {
                            await stream.CopyToAsync(destinationStream);
                        }
                    });

                // Make sure user has enough space remaining
                if (_owner != null)
                {
                    var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                    await lockEntry.ObtainExclusiveWriteAsync();
                    var userManager = new WebUserManager(ServerContext);
                    var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                    var afterUploadSpace = ownerData.StorageUsage + uploadStreamFileSize;
                    if (afterUploadSpace > ownerData.StorageQuota)
                    {
                        lockEntry.ReleaseExclusiveWrite();
                        // Throw exception, catch block will remove file and rethrow
                        throw new QuotaExceededException();
                    }
                    // Increase user storage usage
                    ownerData.StorageUsage += uploadStreamFileSize;
                    await userManager.UpdateUserInDatabaseAsync(ownerData);
                    lockEntry.ReleaseExclusiveWrite();
                }
            }
            catch (QuotaExceededException)
            {
                // Roll back write
                await Task.Run(() => File.Delete(targetFile));
                throw;
            }

            return new FileUploadResult
            {
                FileId = fileId,
                Size = uploadStreamFileSize
            };
        }

19 View Source File : ExecuteTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void ExecuteScalarAsync()
        {
            var newName = Guid.NewGuid().ToString();
            var name = Dapper.ExecuteScalarAsync<string>(
                "update contact set [email protected] where [email protected]; select name from contact where [email protected];", new { id = 1, name = newName }).Result;
            replacedert.Equal(name, newName);
        }

19 View Source File : ExecuteTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void Transaction()
        {
            var newName = Guid.NewGuid().ToString();
            Dapper.BeginTransaction();
            var rows = Dapper.Execute("update contact set [email protected] where [email protected];",
                new { name = newName, id = 1 });
            replacedert.True(rows > 0);
            Dapper.CommitTransaction();
            var name = Dapper.QueryFirstOrDefault<string>("select name from contact where [email protected];", new { id = 1 });
            replacedert.Equal(name, newName);

            Dapper.BeginTransaction();
            var oldName = Dapper.QueryFirstOrDefault<string>("select name from contact where [email protected];", new { id = 1 });
            var rows2 = Dapper.Execute("update contact set [email protected] where [email protected];",
                new { name = newName, id = 1 });
            replacedert.True(rows2 > 0);
            Dapper.RollbackTransaction();
            var nowName = Dapper.QueryFirstOrDefault<string>("select name from contact where [email protected];", new { id = 1 });
            replacedert.Equal(oldName, nowName);
        }

19 View Source File : MasterSlaveTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void Test()
        {

            var rows = DapperMaster.Execute("update COMPANY set [email protected] where [email protected];", new { name = Guid.NewGuid().ToString(), id = 1 });
            replacedert.True(rows > 0);
            Output.WriteLine("Master:" + DapperMaster.Conn.Value.ConnectionString);

            var read = DapperSlave.Query("select * from company;");
            replacedert.NotNull(read);
            replacedert.True(read.Any());
            Output.WriteLine("Slave:" + DapperSlave.Conn.Value.ConnectionString);
        }

19 View Source File : ValuesController.cs
License : MIT License
Project Creator : 1100100

[HttpGet]
        public async Task<IActionResult> Get()
        {

            //await HelloService.SayHello();
            return Ok(new
            {
                name = await HelloService.SetMeta(("token", "bearer ....."), ("x-consistent-hash-key", Guid.NewGuid().ToString())).SayHello(Guid.NewGuid().ToString()),
                //Reply = await HelloService.SayHello("Owen"),
                //enreplacedy = await HelloService.SayHello(new TestModel { Id = 1, Name = "owen" }),
                //gen = await HelloService.Test()

            });
        }

19 View Source File : ValuesController.cs
License : MIT License
Project Creator : 1100100

[HttpGet("Transaction")]
        public async Task<IActionResult> Transaction()
        {
            Repo1.BeginTransaction();
            var result = await Repo1.QueryFirstOrDefaultAsync("select * from COMPANY where id=1;");
            if (result != null)
            {
                await Repo1.ExecuteAsync("update COMPANY set [email protected] where id=1;", new { name = Guid.NewGuid().ToString() });
                Repo1.CommitTransaction();
            }
            return Ok();

        }

19 View Source File : DapperFactoryTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void Test()
        {
            DapperFactory.Step(dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            });

            var result7 = DapperFactory.Step(dapper => { return dapper.Query("select * from Contact;"); });
            replacedert.NotNull(result7);
            replacedert.True(result7.Any());

            DapperFactory.StepAsync(async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            }).Wait();

            var result8 = DapperFactory.StepAsync(async dapper => await dapper.QueryAsync("select * from Contact;")).Result;
            replacedert.NotNull(result8);
            replacedert.True(result8.Any());


            DapperFactory.Step("sqlite2", dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            });

            var result9 = DapperFactory.Step("sqlite2", dapper => { return dapper.Query("select * from Contact;"); });
            replacedert.NotNull(result9);
            replacedert.True(result9.Any());

            DapperFactory.StepAsync("sqlite2", async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            }).Wait();

            var result10 = DapperFactory.StepAsync("sqlite2", async dapper => await dapper.QueryAsync("select * from Contact;")).Result;
            replacedert.NotNull(result10);
            replacedert.True(result10.Any());


            DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                var query = dapper.Query("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            });

            DapperFactory.StepAsync(async context =>
            {
                var dapper = context.ResolveDapper();
                var queryAsync = await dapper.QueryAsync("select * from Contact;");
                replacedert.NotNull(queryAsync);
                replacedert.True(queryAsync.Any());
            }).Wait();

            DapperFactory.Step((context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            });

            DapperFactory.Step(context =>
            {
                var master = context.ResolveDapper("master_slave");
                var rows = master.Execute("update COMPANY set [email protected] where [email protected];", new { name = Guid.NewGuid().ToString(), id = 1 });
                replacedert.True(rows > 0);
                Output.WriteLine("Master:" + master.Conn.Value.ConnectionString);


                var slave = context.ResolveDapper("master_slave", true);
                var read = slave.Query("select * from company;");
                replacedert.NotNull(read);
                replacedert.True(read.Any());
                Output.WriteLine("Slave:" + slave.Conn.Value.ConnectionString);
            });

            DapperFactory.StepAsync(async (context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            }).Wait();

            DapperFactory.Step("sqlite2", (context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            });

            DapperFactory.StepAsync("sqlite2", async (context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                replacedert.NotNull(query);
                replacedert.True(query.Any());
            }).Wait();

            var result1 = DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                return dapper.Query("select * from Contact;");
            });
            replacedert.NotNull(result1);
            replacedert.True(result1.Any());

            var result2 = DapperFactory.StepAsync(context =>
            {
                var dapper = context.ResolveDapper();
                return dapper.QueryAsync("select * from Contact;");
            }).Result;
            replacedert.NotNull(result2);
            replacedert.True(result2.Any());

            var result3 = DapperFactory.Step((context, dapper) => dapper.Query("select * from Contact;"));
            replacedert.NotNull(result3);
            replacedert.True(result3.Any());

            var result4 = DapperFactory.StepAsync(async (context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;
            replacedert.NotNull(result4);
            replacedert.True(result4.Any());

            var result5 = DapperFactory.Step("sqlite2", (context, dapper) => dapper.Query("select * from Contact;"));
            replacedert.NotNull(result5);
            replacedert.True(result5.Any());

            var result6 = DapperFactory.StepAsync("sqlite2", async (context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;
            replacedert.NotNull(result6);
            replacedert.True(result6.Any());
        }

19 View Source File : ExecuteTest.cs
License : MIT License
Project Creator : 1100100

[Fact]
        public void ExecuteAsync()
        {
            var newName = Guid.NewGuid().ToString();
            var rows = Dapper.ExecuteAsync("update contact set [email protected] where [email protected];",
                new { name = newName, id = 1 }).Result;
            replacedert.True(rows > 0);
            var name = Dapper.QueryFirstOrDefaultAsync<string>("select name from contact where [email protected];", new { id = 1 }).Result;
            replacedert.Equal(name, newName);
        }

19 View Source File : ValuesController.cs
License : MIT License
Project Creator : 1100100

[HttpGet]
        public async Task<IActionResult> Get()
        {
            return Ok(await PersonService.GetName(1));
            var a = Guid.NewGuid().ToString();
            //var r = ServiceProvider.GetServices<IRemotingInvoke>();
            var r = await HelloService.SetMeta(("token", "bearer .....")).SayHello(a);
            if (r.Message == a)
                return Ok(r);
            return BadRequest(new
            {
                @in = a,
                @out = r.Message
            });
        }

19 View Source File : DefaultVerifyCodeProvider.cs
License : MIT License
Project Creator : 17MKH

public async Task<VerifyCodeModel> Create()
    {
        var code = _stringHelper.GenerateRandomNumber();

        var bytes = DrawVerifyCode(code);

        var id = Guid.NewGuid().ToString();

        await _cacheHandler.Set(_cacheKeys.VerifyCode(id), code, 5);

        return new VerifyCodeModel
        {
            Id = id,
            Base64 = "data:image/png;base64," + Convert.ToBase64String(bytes)
        };
    }

19 View Source File : GuidTypeHandler.cs
License : MIT License
Project Creator : 17MKH

public override void SetValue(System.Data.IDbDataParameter parameter, Guid value)
    {
        parameter.Value = value.ToString();
    }

19 View Source File : HttpClientPatchAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Patch_1_FromBody_1_ConstraintAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPatchRoute.Patch_1_FromBody_1_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientPatchAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Patch_2_Constraint_ParasAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPatchRoute.Patch_2_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : JwtCredentialBuilder.cs
License : MIT License
Project Creator : 17MKH

public async Task<IResultModel> Build(List<Claim> claims)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
        var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var jwtSecurityToken = new JwtSecurityToken(_options.Issuer, _options.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(_options.Expires), signingCredentials);
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        _logger.LogDebug("生成AccessToken:{token}", token);

        var result = new JwtResultModel
        {
            AccountId = Guid.Parse(claims.First(m => m.Type == MkhClaimTypes.ACCOUNT_ID).Value),
            Platform = claims.First(m => m.Type == MkhClaimTypes.PLATFORM).Value.ToInt(),
            AccessToken = token,
            ExpiresIn = (_options.Expires < 0 ? 120 : _options.Expires) * 60,
            RefreshToken = Guid.NewGuid().ToString().Replace("-", "")
        };

        //存储令牌信息
        await _tokenStorageProvider.Save(result, claims);

        return ResultModel.Success(result);
    }

19 View Source File : HttpClientPostAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Post_1_FromBody_1_ConstraintAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPostRoute.Post_1_FromBody_1_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientPostAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Post_2_Constraint_ParasAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPostRoute.Post_2_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientPostAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Post_1_FromBody()
        {
            string guid1 = Guid.NewGuid().ToString();
            dynamic data = await HttpPostRoute.Post_1_FromBodyAsync<dynamic>(guid1);

            string key = data.key;

            replacedert.Equal(guid1, key);
        }

19 View Source File : HttpClientPutAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Put_1_FromBody_1_ConstraintAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPutRoute.Put_1_FromBody_1_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientPutAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Put_2_Constraint_ParasAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpPutRoute.Put_2_ConstraintAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
    {
        var value = ResolveDynamicInvoke(exp);
        var isValueType = false;
        var list = new List<string>();
        if (valueType.IsEnum)
        {
            isValueType = true;
            var valueList = (IEnumerable)value;
            if (valueList != null)
            {
                foreach (var c in valueList)
                {
                    list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
                }
            }
        }
        else
        {
            var typeName = valueType.Name;
            switch (typeName)
            {
                case "Guid":
                    if (value is IEnumerable<Guid> guidValues)
                    {
                        foreach (var c in guidValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "DateTime":
                    if (value is IEnumerable<DateTime> dateTimeValues)
                    {
                        foreach (var c in dateTimeValues)
                        {
                            list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    break;
                case "Byte":
                    isValueType = true;
                    if (value is IEnumerable<byte> byteValues)
                    {
                        foreach (var c in byteValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Char":
                    if (value is IEnumerable<char> charValues)
                    {
                        foreach (var c in charValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int16":
                    isValueType = true;
                    if (value is IEnumerable<short> shortValues)
                    {
                        foreach (var c in shortValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int32":
                    isValueType = true;
                    if (value is IEnumerable<int> intValues)
                    {
                        foreach (var c in intValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int64":
                    isValueType = true;
                    if (value is IEnumerable<long> longValues)
                    {
                        foreach (var c in longValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Double":
                    isValueType = true;
                    if (value is IEnumerable<double> doubleValues)
                    {
                        foreach (var c in doubleValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Single":
                    isValueType = true;
                    if (value is IEnumerable<float> floatValues)
                    {
                        foreach (var c in floatValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Decimal":
                    isValueType = true;
                    if (value is IEnumerable<decimal> decimalValues)
                    {
                        foreach (var c in decimalValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
            }
        }

        if (list!.Count < 1)
            return;

        sqlBuilder.Append(columnName);
        sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");

        //值类型不带引号
        if (isValueType)
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("{0}", list[i]);
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }
        else
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }

        sqlBuilder.Append(")");
    }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Delete_0_Constraint_2_ParamerterAsync()
        {
            string guid = Guid.NewGuid().ToString();
            dynamic data = await HttpDeleteRoute.Delete_0_Constraint_2_ParamerterAsync<dynamic>(guid, "2");
            string dataStr = data.ToString();

            this.Output.WriteLine(dataStr);
            replacedert.Contains(guid, dataStr);
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Get_1_Constraint_1_ParamerAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpGetRoute.Get_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);
            string dataStr = data.ToString();

            this.Output.WriteLine($"Response Data: {dataStr}");

            replacedert.Contains(guid1, dataStr);
            replacedert.Contains(guid2, dataStr);
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Get_1_Constraint_1_Paramer_Desc_Async()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpGetRoute.Get_1_Constraint_1_Parameter_DescAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData(".")]
        [InlineData("~")]
        [InlineData("?")]
        [InlineData("!")]
        [InlineData("@")]
        [InlineData("#")]
        [InlineData("$")]
        [InlineData("%")]
        [InlineData("^")]
        [InlineData("*")]
        [InlineData("&")]
        [InlineData("(")]
        [InlineData(")")]
        [InlineData("-")]
        [InlineData("_")]
        [InlineData("=")]
        [InlineData("{")]
        [InlineData("}")]
        [InlineData("<")]
        [InlineData(">")]
        [InlineData("|")]
        [InlineData("【")]
        [InlineData("】")]
        [InlineData("¥")]
        [InlineData("{}")]
        [InlineData("{{")]
        [InlineData("}}")]
        [InlineData("{id?}")]
        [InlineData("{{id?}}")]
        [InlineData("[controller]")]
        [InlineData("[action]")]
        [InlineData("api")]
        [InlineData("测试中文字符")]
        [InlineData("'")]
        [InlineData("[")]
        [InlineData("]")]
        [InlineData("\"")]
        [InlineData(" ")]
        [Theory(DisplayName = "Test Escape Sequence")]
        public async Task Get_Escape_Sequence_Async(string chars)
        {
            string guid1 = Guid.NewGuid().ToString() + chars;
            string guid2 = Guid.NewGuid().ToString() + chars;
            dynamic data = await HttpGetRoute.Get_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);
            string responseGuid1 = data.key;
            string responseGuid2 = data.value;

            replacedert.Equal(guid1, responseGuid1);
            replacedert.Equal(guid2, responseGuid2);
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData("+")]
        [Theory(DisplayName = "Test Double Escape Sequence Exception")]
        public async Task Get_Escape_Sequence_Exception_Async(string chars)
        {
            await replacedert.ThrowsAnyAsync<Exception>(async () =>
            {
                string guid1 = Guid.NewGuid().ToString() + chars;
                string guid2 = Guid.NewGuid().ToString() + chars;
                dynamic data = await HttpGetRoute.Get_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);

                string dataStr = data.ToString();
                this.Output.WriteLine($"Response Data: {dataStr}");
            });
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData("\\")]
        [InlineData("/")]
        [Theory(DisplayName = "Test Double Escape Sequence")]
        public async Task Get_1_Constraint_1_Paramer_Specima_Double_Escape_Sequence_Async(string chars)
        {
            string guid1 = Guid.NewGuid().ToString() + chars;
            string guid2 = Guid.NewGuid().ToString() + chars;
            dynamic data = await HttpGetRoute.Get_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);

            string dataStr = data.ToString();
            this.Output.WriteLine($"Response Data: {dataStr}");
            replacedert.DoesNotContain(guid1, dataStr);
            replacedert.Contains(guid2, dataStr);
        }

19 View Source File : HttpClientGetAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Get_0_Constraint_2_ParamerterAsync()
        {
            string guid = Guid.NewGuid().ToString();
            dynamic data = await HttpGetRoute.Get_0_Constraint_2_ParamerterAsync<dynamic>(guid, "2");
            string dataStr = data.ToString();

            this.Output.WriteLine(dataStr);
            replacedert.Contains(guid, dataStr);
        }

19 View Source File : HttpClientPatchAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Patch_1_FromBody()
        {
            string guid1 = Guid.NewGuid().ToString();
            dynamic data = await HttpPatchRoute.Patch_1_FromBodyAsync<dynamic>(guid1);

            string key = data.key;

            replacedert.Equal(guid1, key);
        }

19 View Source File : FileUploadProvider.cs
License : MIT License
Project Creator : 17MKH

public async Task<IResultModel<FileDescriptor>> Upload(FileUploadModel model, CancellationToken cancellationToken = default)
    {
        Check.NotNull(model, nameof(model), "file upload model is null");

        Check.NotNull(model.StorageRootDirectory, nameof(model.StorageRootDirectory), "the file storage root directory is null");

        var result = new ResultModel<FileDescriptor>();

        if (model.FormFile == null)
            return result.Failed("请选择文件!");

        var size = model.FormFile.Length;

        //验证文件大小
        if (model.MaxSize > 0 && model.MaxSize < size)
            return result.Failed($"文件大小不能超过{new FileSize(model.MaxSize).ToString()}");

        var name = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;

        var descriptor = new FileDescriptor(name, size);

        //验证扩展名
        if (model.LimitExtensions != null && !model.LimitExtensions.Any(m => m.EqualsIgnoreCase(descriptor.Extension)))
            return result.Failed($"文件格式无效,请上传{model.LimitExtensions.Aggregate((x, y) => x + "," + y)}格式的文件");

        //按照日期来保存文件
        var date = DateTime.Now;
        descriptor.DirectoryName = Path.Combine(model.StorageRootDirectory, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));

        //创建目录
        if (!Directory.Exists(descriptor.DirectoryName))
        {
            Directory.CreateDirectory(descriptor.DirectoryName);
        }

        //生成文件存储名称
        descriptor.StorageName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{descriptor.Extension}";

        //写入
        await using var stream = new FileStream(descriptor.FullName, FileMode.Create);

        //计算MD5
        if (model.CalculateMd5)
        {
            descriptor.Md5 = _md5Encrypt.Encrypt(stream);
        }

        await model.FormFile.CopyToAsync(stream, cancellationToken);

        return result.Success(descriptor);
    }

19 View Source File : RepositoryAbstract.Add.cs
License : MIT License
Project Creator : 17MKH

protected async Task<bool> Add(TEnreplacedy enreplacedy, string tableName, IUnitOfWork uow = null)
    {
        if (enreplacedy == null)
            throw new ArgumentNullException(nameof(enreplacedy), "enreplacedy is null");

        var sql = _sql.GetAdd(tableName);

        SetCreateInfo(enreplacedy);

        _logger.Write("Add", sql);

        var primaryKey = EnreplacedyDescriptor.PrimaryKey;
        if (primaryKey.IsInt)
        {
            //自增主键
            sql += _adapter.IdenreplacedySql;
            var id = await ExecuteScalar<int>(sql, enreplacedy, uow);
            if (id > 0)
            {
                primaryKey.PropertyInfo.SetValue(enreplacedy, id);

                _logger.Write("NewID", id.ToString());
                return true;
            }

            return false;
        }

        if (primaryKey.IsLong)
        {
            //自增主键
            sql += _adapter.IdenreplacedySql;
            var id = await ExecuteScalar<long>(sql, enreplacedy, uow);
            if (id > 0)
            {
                primaryKey.PropertyInfo.SetValue(enreplacedy, id);

                _logger.Write("NewID", id.ToString());
                return true;
            }
            return false;
        }

        if (primaryKey.IsGuid)
        {
            var id = (Guid)primaryKey.PropertyInfo.GetValue(enreplacedy)!;
            if (id == Guid.Empty)
            {
                primaryKey.PropertyInfo.SetValue(enreplacedy, _adapter.CreateSequentialGuid());
            }

            _logger.Write("NewID", id.ToString());

            if (await Execute(sql, enreplacedy, uow) > 0)
            {
                return true;
            }
            return false;
        }

        return await Execute(sql, enreplacedy) > 0;
    }

19 View Source File : CommonExtensionsTests.cs
License : MIT License
Project Creator : 17MKH

[Fact]
        public void ToGuidTest()
        {
            var guid = Guid.NewGuid();

            guid = guid.ToString().ToGuid();

            replacedert.NotEqual(Guid.Empty, guid);
        }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Delete_1_Constraint_1_ParamerAsync()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpDeleteRoute.Delete_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);
            string dataStr = data.ToString();

            this.Output.WriteLine($"Response Data: {dataStr}");

            replacedert.Contains(guid1, dataStr);
            replacedert.Contains(guid2, dataStr);
        }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[Fact]
        public async Task Delete_1_Constraint_1_Paramer_Desc_Async()
        {
            string guid1 = Guid.NewGuid().ToString();
            string guid2 = Guid.NewGuid().ToString();
            dynamic data = await HttpDeleteRoute.Delete_1_Constraint_1_Parameter_DescAsync<dynamic>(guid1, guid2);

            string key = data.key;
            string value = data.value;

            replacedert.Equal(guid1, key);
            replacedert.Equal(guid2, value);
        }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData(".")]
        [InlineData("~")]
        [InlineData("?")]
        [InlineData("!")]
        [InlineData("@")]
        [InlineData("#")]
        [InlineData("$")]
        [InlineData("%")]
        [InlineData("^")]
        [InlineData("*")]
        [InlineData("&")]
        [InlineData("(")]
        [InlineData(")")]
        [InlineData("-")]
        [InlineData("_")]
        [InlineData("=")]
        [InlineData("{")]
        [InlineData("}")]
        [InlineData("<")]
        [InlineData(">")]
        [InlineData("|")]
        [InlineData("【")]
        [InlineData("】")]
        [InlineData("¥")]
        [InlineData("{}")]
        [InlineData("{{")]
        [InlineData("}}")]
        [InlineData("{id?}")]
        [InlineData("{{id?}}")]
        [InlineData("[controller]")]
        [InlineData("[action]")]
        [InlineData("api")]
        [InlineData("测试中文字符")]
        [InlineData("'")]
        [InlineData("[")]
        [InlineData("]")]
        [InlineData("\"")]
        [InlineData(" ")]
        [Theory(DisplayName = "Test Escape Sequence")]
        public async Task Delete_Escape_Sequence_Async(string chars)
        {
            string guid1 = Guid.NewGuid().ToString() + chars;
            string guid2 = Guid.NewGuid().ToString() + chars;
            dynamic data = await HttpDeleteRoute.Delete_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);
            string responseGuid1 = data.key;
            string responseGuid2 = data.value;

            replacedert.Equal(guid1, responseGuid1);
            replacedert.Equal(guid2, responseGuid2);
        }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData("+")]
        [Theory(DisplayName = "Test Double Escape Sequence Exception")]
        public async Task Delete_Escape_Sequence_Exception_Async(string chars)
        {
            await replacedert.ThrowsAnyAsync<Exception>(async () =>
            {
                string guid1 = Guid.NewGuid().ToString() + chars;
                string guid2 = Guid.NewGuid().ToString() + chars;
                dynamic data = await HttpDeleteRoute.Delete_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);

                string dataStr = data.ToString();
                this.Output.WriteLine($"Response Data: {dataStr}");
            });
        }

19 View Source File : HttpClientDeleteAsyncTest.cs
License : MIT License
Project Creator : 188867052

[InlineData("\\")]
        [InlineData("/")]
        [Theory(DisplayName = "Test Double Escape Sequence ")]
        public async Task Delete_1_Constraint_1_Paramer_Specima_Double_Escape_Sequence_Async(string chars)
        {
            string guid1 = Guid.NewGuid().ToString() + chars;
            string guid2 = Guid.NewGuid().ToString() + chars;
            dynamic data = await HttpDeleteRoute.Delete_1_Constraint_1_ParameterAsync<dynamic>(guid1, guid2);

            string dataStr = data.ToString();
            this.Output.WriteLine($"Response Data: {dataStr}");
            replacedert.DoesNotContain(guid1, dataStr);
            replacedert.Contains(guid2, dataStr);
        }

19 View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : 1iveowl

private void Button_OnClick(object sender, RoutedEventArgs e)
        {
            _mqttService = new MQTTService();

            var mqttClientOptions = new Options
            {
                Server = "test.mosquitto.org",
                //Server = "192.168.0.41",
                Port = 1883,
                ConnectionType = ConnectionType.Tcp,
                CleanSession = true,
                ClientId = Guid.NewGuid().ToString().Replace("-", string.Empty),
                UseTls = false
            };

            var topic1 = new TopicFilter
            {
                QualityOfServiceLevel = QoSLevel.AtLeastOnce,
                //Topic = "PP/#"
                Topic = "/#"
            };

            ITopicFilter[] topicFilters = {

                topic1,
            };

            var MQTTService = _mqttService.CreateObservableMQTTService(mqttClientOptions, topicFilters);
            _disposable = MQTTService
                .observableMessage
                .SubscribeOnDispatcher()
                //.Throttle(TimeSpan.FromMilliseconds(100), Scheduler.Default)
                .ObserveOnDispatcher().Subscribe(
                    msg =>
                    {
                        textBlock.Text = Encoding.UTF8.GetString(msg.Payload);
                    },
                    ex =>
                    {
                        textBlock.Text = "Exception";
                    },
                    () => { });

            //var MQTTService = await mqttService.CreateObservableMQTTServiceAsync(mqttClientOptions, topicFilters);


        }

19 View Source File : MQTTClient.cs
License : MIT License
Project Creator : 1iveowl

private static IMqttClientOptions UnwrapOptions(IClientOptions wrappedOptions, IWillMessage willMessage)
        {
            var optionsBuilder = new MqttClientOptionsBuilder();

            if (wrappedOptions.ConnectionType == ConnectionType.Tcp)
            {
                optionsBuilder.WithTcpServer(wrappedOptions.Uri.Host, wrappedOptions.Uri.Port);
            }
            else
            {
                optionsBuilder.WithWebSocketServer(wrappedOptions.Uri.AbsoluteUri);
            }

            if (wrappedOptions.UseTls)
            {
                optionsBuilder
                    .WithTls(new MqttClientOptionsBuilderTlsParameters
                    {
                        AllowUntrustedCertificates = wrappedOptions.AllowUntrustedCertificates,
                        Certificates = UnwrapCertificates(wrappedOptions.Certificates),
                        IgnoreCertificateChainErrors = wrappedOptions.IgnoreCertificateChainErrors,
                        UseTls = wrappedOptions.UseTls
                    });
            }

            return optionsBuilder
                .WithWillMessage(WrapWillMessage(willMessage))
                .WithCleanSession(wrappedOptions.CleanSession)
                .WithClientId(wrappedOptions.ClientId ?? Guid.NewGuid().ToString().Replace("-", string.Empty))

                .WithProtocolVersion(UnwrapProtocolVersion(wrappedOptions.ProtocolVersion))
                .WithCommunicationTimeout(wrappedOptions.DefaultCommunicationTimeout == default
                    ? TimeSpan.FromSeconds(10)
                    : wrappedOptions.DefaultCommunicationTimeout)
                .WithKeepAlivePeriod(wrappedOptions.KeepAlivePeriod == default
                    ? TimeSpan.FromSeconds(5)
                    : wrappedOptions.KeepAlivePeriod)
                .WithCredentials(wrappedOptions.UserName, wrappedOptions.Preplacedword)
                .Build();
        }

19 View Source File : SegmentedControlRenderer.cs
License : MIT License
Project Creator : 1iveowl

private void CreateSegmentedRadioButtonControl()
        {
            _segmentedUserControl = new SegmentedUserControl();

            var radioButtonGroupName = Guid.NewGuid().ToString();

            var grid = _segmentedUserControl.SegmentedControlGrid;
            grid.BorderBrush = (SolidColorBrush) _colorConverter.Convert(Element.TintColor, null, null, "");

            grid.ColumnDefinitions.Clear();
            grid.Children.Clear();

            foreach (var child in Element.Children.Select((value, i) => new {i, value}))
            {
                var segmentButton = new SegmentRadioButton
                {
                    GroupName = radioButtonGroupName,
                    Style = (Style)_segmentedUserControl.Resources["SegmentedRadioButtonStyle"],
                    Content = child.value.Text,
                    Tag = child.i,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    BorderBrush = (SolidColorBrush)_colorConverter.Convert(Element.TintColor, null, null, ""),
                    TextColor = (SolidColorBrush)_colorConverter.Convert(Element.TextColor, null, null, ""),
                    //Foreground = (SolidColorBrush)_colorConverter.Convert(Element.TextColor, null, null, ""),
                    SelectedTextColor = (SolidColorBrush)_colorConverter.Convert(Element.SelectedTextColor, null, null, ""),
                    TintColor = (SolidColorBrush)_colorConverter.Convert(Element.TintColor, null, null, ""),
                    DisabledColor = (SolidColorBrush)_colorConverter.Convert(Element.DisabledColor, null, null, ""),
                    BorderThickness = child.i > 0 ? new Thickness(1, 0, 0, 0) : new Thickness(0, 0, 0, 0),
                    IsEnabled = Element.Children[child.i].IsEnabled
                };

                segmentButton.Checked += SegmentRadioButtonOnChecked;

                if (child.i == Element.SelectedSegment)
                {
                    segmentButton.IsChecked = true;
                }

                if (Element.FontSize > 0)
                {
                    segmentButton.FontSize = Element.FontSize;
                }

                if (!string.IsNullOrEmpty(Element.FontFamily))
                {
                    segmentButton.FontFamily = new FontFamily(Element.FontFamily);
                }
                
                grid.ColumnDefinitions.Add(new ColumnDefinition
                {
                    Width = new GridLength(1, GridUnitType.Star),
                });

                segmentButton.SetValue(Grid.ColumnProperty, child.i);

                grid.Children.Add(segmentButton);

                child.value.PropertyChanged += Segment_PropertyChanged;
            }

            SetNativeControl(_segmentedUserControl);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            while (results.TryDequeue(out var del)) ;
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            //var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            //sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {
            //预热
            cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            for (int i = 0; i < 10000; i++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
                var val = cli.Get(tmp);
                if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
            }

            stopwatch.Stop();
            Console.WriteLine("FreeRedis:" + stopwatch.ElapsedMilliseconds);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 2881099

static void Main(string[] args)
        {

            sedb.StringSet("key1", (string)null);

            var val111 = sedb.StringGet("key1");














            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            results.Clear();
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //Task.Run(async () =>
            //{
            //    for (var a = 0; a < 100000; a++)
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }
            //}).Wait();
            //sw.Stop();
            //Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            //sw.Reset();
            //sw.Start();
            //tasks = new List<Task>();
            //for (var a = 0; a < 100000; a++)
            //{
            //    tasks.Add(Task.Run(async () =>
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }));
            //}
            //Task.WaitAll(tasks.ToArray());
            //sw.Stop();
            ////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            ////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            //Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();
        }

See More Examples