System.Guid.NewGuid()

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

20511 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 : 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 : 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 : 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 : TempTableData.cs
License : MIT License
Project Creator : 0x1000000

private static string GenerateName() => $"t{Guid.NewGuid().ToString("N")}";

19 View Source File : Alias.cs
License : MIT License
Project Creator : 0x1000000

public IExprAlias? BuildAliasExpression()
        {
            if (this._proxy != null)
            {
                return this._proxy;
            }

            if (!this._notAuto)
            {
                return new ExprAliasGuid(Guid.NewGuid());
            }

            if (this._name == null || string.IsNullOrWhiteSpace(this._name))
            {
                return null;
            }

            return new ExprAlias(this._name);
        }

19 View Source File : SqQueryBuilder.cs
License : MIT License
Project Creator : 0x1000000

public static IUpdateDataBuilderMapDataInitial<TTable, replacedem> UpdateData<TTable, replacedem>(TTable table, IEnumerable<replacedem> data)
            where TTable : ExprTable
            => new UpdateDataBuilder<TTable,replacedem>(table, data, new ExprAliasGuid(Guid.NewGuid()));

19 View Source File : SqQueryBuilder.cs
License : MIT License
Project Creator : 0x1000000

public static IMergeDataBuilderMapDataInitial<TTable, replacedem> MergeDataInto<TTable, replacedem>(TTable table, IEnumerable<replacedem> data)
            where TTable : ExprTable
            => new MergeDataBuilder<TTable, replacedem>(table, data, new ExprAliasGuid(Guid.NewGuid()));

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 : 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 : 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 : 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 : 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 : IClient.Default.cs
License : MIT License
Project Creator : 1100100

public async Task<IServiceResult> SendAsync(IInvokeMessage message)
        {
            var transportMessage = new TransportMessage<IInvokeMessage>
            {
                Id = Guid.NewGuid().ToString("N"),
                Body = message
            };
            if (Logger.IsEnabled(LogLevel.Trace))
                Logger.LogTrace($"Sending message to node {Node}:\nMessage id:{transportMessage.Id}\nArgs:{Codec.ToJson(message.Args)}\n\n");
            var tcs = new TaskCompletionSource<IServiceResult>(TaskCreationOptions.RunContinuationsAsynchronously);
            using (var ct = new CancellationTokenSource(UraganoOptions.Remoting_Invoke_CancellationTokenSource_Timeout.Value))
            {
                ct.Token.Register(() =>
                {
                    tcs.TrySetResult(new ServiceResult("Remoting invoke timeout!", RemotingStatus.Timeout));
                    Logger.LogWarning("Remoting invoke timeout,You can set the wait time with the Remoting_Invoke_CancellationTokenSource_Timeout option.\nSend to node:{1}\nMessage id:{0}\n\n", transportMessage.Id, Node);
                }, false);

                if (!_resultCallbackTask.TryAdd(transportMessage.Id, tcs)) throw new Exception("Failed to send.");
                try
                {
                    await Channel.WriteAndFlushAsync(transportMessage);
                    if (Logger.IsEnabled(LogLevel.Trace))
                        Logger.LogTrace($"Send completed, waiting for node {Node} to return results:\nMessage id:{transportMessage.Id}\n\n");
                    var result = await tcs.Task;
                    if (Logger.IsEnabled(LogLevel.Trace))
                        Logger.LogTrace($"The client received the return result of node {Node}:\nMessage id:{transportMessage.Id}\nBody:{Codec.ToJson(result)}\n\n");
                    return result;
                }
                finally
                {
                    _resultCallbackTask.TryRemove(transportMessage.Id, out var t);
                    t?.TrySetCanceled();
                }
            }
        }

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 : 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 : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<object, Dictionary<string, object>> CreateTypeDeserializerHandler(Type type)
        {
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var methodName = $"{type.Name}Deserializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, typeof(Dictionary<string, object>), new Type[] { typeof(object) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder enreplacedyLocal1 = generator.DeclareLocal(typeof(Dictionary<string, object>));
            LocalBuilder enreplacedyLocal2 = generator.DeclareLocal(type);
            generator.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            generator.Emit(OpCodes.Stloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclreplaced, type);
            generator.Emit(OpCodes.Stloc, enreplacedyLocal2);
            foreach (var item in properties)
            {
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
                generator.Emit(OpCodes.Ldstr, item.Name);
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal2);
                generator.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, item.PropertyType);
                }
                var addMethod = typeof(Dictionary<string, object>).GetMethod(nameof(Dictionary<string, object>.Add), new Type[] { typeof(string), typeof(object) });
                generator.Emit(OpCodes.Callvirt, addMethod);
            }
            generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<object, Dictionary<string, object>>)) as Func<object, Dictionary<string, object>>;
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<IDataRecord, T> CreateTypeSerializerHandler<T>(MemberMapper mapper, IDataRecord record)
        {
            var type = typeof(T);
            var methodName = $"Serializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, type, new Type[] { typeof(IDataRecord) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder local = generator.DeclareLocal(type);
            var dataInfos = new DataReaderCellInfo[record.FieldCount];
            for (int i = 0; i < record.FieldCount; i++)
            {
                var dataname = record.GetName(i);
                var datatype = record.GetFieldType(i);
                var typename = record.GetDataTypeName(i);
                dataInfos[i] = new DataReaderCellInfo(i, typename, datatype, dataname);
            }
            if (dataInfos.Length == 1 && (type.IsValueType || type == typeof(string) || type == typeof(object)))
            {
                var dataInfo = dataInfos.First();
                var convertMethod = mapper.FindConvertMethod(type, dataInfo.DataType);
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, 0);
                if (convertMethod.IsVirtual)
                    generator.Emit(OpCodes.Callvirt, convertMethod);
                else
                    generator.Emit(OpCodes.Call, convertMethod);
                if (type == typeof(object) && convertMethod.ReturnType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, convertMethod.ReturnType);
                }
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            var constructor = mapper.FindConstructor(type);
            if (constructor.GetParameters().Length > 0)
            {
                var parameters = constructor.GetParameters();
                var locals = new LocalBuilder[parameters.Length];
                for (int i = 0; i < locals.Length; i++)
                {
                    locals[i] = generator.DeclareLocal(parameters[i].ParameterType);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    var item = mapper.FindConstructorParameter(dataInfos, parameters[i]);
                    if (item == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(parameters[i].ParameterType, item.DataType);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, item.Ordinal);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Stloc, locals[i]);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    generator.Emit(OpCodes.Ldloc, locals[i]);
                }
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            else
            {
                var properties = type.GetProperties();
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                foreach (var item in dataInfos)
                {
                    var property = mapper.FindMember(properties, item) as PropertyInfo;
                    if (property == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(property.PropertyType, item.DataType);
                    if (convertMethod == null)
                    {
                        continue;
                    }
                    int i = record.GetOrdinal(item.DataName);
                    generator.Emit(OpCodes.Ldloc, local);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, i);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Callvirt, property.GetSetMethod());
                }
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : 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 : InterfaceImplementation.cs
License : MIT License
Project Creator : 1996v

public static Type CreateType(Type interfaceType)
        {
            try
            {
                TypeBuilder typeBuilder = Impreplacedembly.DefineInterfaceImpType(interfaceType);

                List<MemberInfo> allMembers = interfaceType.GetAllInterfaceMembers();

                List<MethodInfo> propertyInfos = new List<MethodInfo>();

                foreach (PropertyInfo prop in allMembers.OfType<PropertyInfo>())
                {
                    Type propType = prop.PropertyType;

                    PropertyBuilder propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes);

                    MethodInfo iGetter = prop.GetMethod;
                    MethodInfo iSetter = prop.SetMethod;
                    if (iGetter != null)
                    {
                        propertyInfos.Add(iGetter);
                    }

                    if (iSetter != null)
                    {
                        propertyInfos.Add(iSetter);
                    }

                    if (prop.Name == "Item")
                    {
                        if (iGetter != null)
                        {
                            MethodAttributes accessor = iGetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, iGetter.ReturnType, iGetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetGetMethod(methBuilder);
                        }
                        if (iSetter != null)
                        {
                            MethodAttributes accessor = iSetter.Attributes;
                            accessor &= ~MethodAttributes.Abstract;
                            MethodBuilder methBuilder = typeBuilder.DefineMethod(iSetter.Name, accessor, iSetter.ReturnType, iSetter.GetParameters().Select(e => e.ParameterType).ToArray());
                            ILGenerator il = methBuilder.GetILGenerator();
                            il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                            il.Emit(OpCodes.Throw);
                            propBuilder.SetSetMethod(methBuilder);
                        }
                        continue;
                    }


                    Func<FieldInfo> getBackingField;
                    {
                        FieldInfo backingField = null;
                        getBackingField =
                            () =>
                            {
                                if (backingField == null)
                                {
                                    backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), propType, FieldAttributes.Private);
                                }

                                return backingField;
                            };
                    }

                    if (iGetter != null)
                    {
                        MethodAttributes accessor = iGetter.Attributes;
                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(iGetter.Name, accessor, propType, Type.EmptyTypes);
                        ILGenerator il = methBuilder.GetILGenerator();
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldfld, getBackingField());
                        il.Emit(OpCodes.Ret);
                        propBuilder.SetGetMethod(methBuilder);
                    }

                    if (iGetter != null || iSetter != null)
                    {
                        MethodAttributes accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private;
                        string name = iSetter != null ? iSetter.Name : "set_" + prop.Name;

                        accessor &= ~MethodAttributes.Abstract;

                        MethodBuilder methBuilder = typeBuilder.DefineMethod(name, accessor, typeof(void), new[] { propType });
                        ILGenerator il = methBuilder.GetILGenerator();

                        if (iGetter != null)
                        {
                            il.Emit(OpCodes.Ldarg_0);
                            il.Emit(OpCodes.Ldarg_1);
                            il.Emit(OpCodes.Stfld, getBackingField());
                            il.Emit(OpCodes.Ret);
                        }
                        else
                        {
                            il.Emit(OpCodes.Ret);
                        }

                        propBuilder.SetSetMethod(methBuilder);
                    }
                }

                foreach (MethodInfo method in allMembers.OfType<MethodInfo>().Except(propertyInfos))
                {
                    MethodBuilder methBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, method.ReturnType, method.GetParameters().Select(e => e.ParameterType).ToArray());
                    if (method.IsGenericMethod)
                    {
                        methBuilder.DefineGenericParameters(method.GetGenericArguments().Select(e => e.Name).ToArray());
                    }
                    ILGenerator il = methBuilder.GetILGenerator();
                    il.Emit(OpCodes.Newobj, typeof(NotImplementedException).GetConstructors()[0]);
                    il.Emit(OpCodes.Throw);

                    typeBuilder.DefineMethodOverride(methBuilder, method);
                }

                return typeBuilder.CreateTypeInfo();
            }
            catch
            {
                throw BssomSerializationTypeFormatterException.UnsupportedType(interfaceType);
            }
        }

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 : 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}");
            });
        }

See More Examples