System.Random.Next(int)

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

4062 Examples 7

19 View Source File : Edi.cs
License : MIT License
Project Creator : 0ffffffffh

private static void GenSessionId()
        {
            StringBuilder sb = new StringBuilder();
            string hx = "abcdefgh0123456789";
            Random rnd = new Random();

            for (int i=0;i<16;i++)
            {
                sb.Append(hx[rnd.Next(hx.Length)]);
            }

            sessionId = sb.ToString();
            sb.Clear();
            sb = null;
        }

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

static void Main(string[] args)
        {
            //if (args.Length == 1)
            //{
            //    string taskname = args[0];
            //    DeleteTask(taskname);
            //    return;
            //}

            if (args.Length != 2)
            {
                Banner();
                Console.WriteLine("\nUsage: SchTask.exe <File Path> <Minutes>");
                Console.WriteLine(@"   Eg: SchTask.exe C:\Windows\System32\cmd.exe 10");
                //Console.WriteLine("\nUsage: SchTask.exe <TaskName>");
                //Console.WriteLine("[!] Add the scheduled task first and then delete it");
            }
            else
            {
                Banner();
                string inputfile = args[0];
                string min = args[1];

                //选择主机随机进程名
                Process[] progresses = Process.GetProcesses();
                Random random = new Random();
                string randomname = (progresses[random.Next(progresses.Length)].ProcessName);
                if (File.Exists(inputfile))
                {
                    Copy(inputfile, randomname, min);
                    return;
                }
                Console.WriteLine("\n[x] Local file not found !");
            }
        }

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

public async Task<ServiceNodeInfo> GetNextNode(string serviceName, string serviceRoute, IReadOnlyList<object> serviceArgs, IReadOnlyDictionary<string, string> serviceMeta)
        {
            var nodes = await ServiceDiscovery.GetServiceNodes(serviceName);
            if (!nodes.Any())
                throw new NotFoundNodeException(serviceName);
            if (nodes.Count == 1)
                return nodes.First();
            var node= nodes[new Random().Next(0, nodes.Count)];
            if (Logger.IsEnabled(LogLevel.Trace))
                Logger.LogTrace($"Load to node {node.ServiceId}.");
            return node;
        }

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

public async Task<ServiceNodeInfo> GetNextNode(string serviceName, string serviceRoute, IReadOnlyList<object> serviceArgs, IReadOnlyDictionary<string, string> serviceMeta)
        {
            var nodes = await ServiceDiscovery.GetServiceNodes(serviceName);
            if (!nodes.Any())
                throw new NotFoundNodeException(serviceName);
            if (nodes.Count == 1)
                return nodes.First();
            lock (LockObject)
            {
                var total = nodes.Sum(p => p.Weight);
                var offset = new Random().Next(0, total+1);
                var currentSum = 0;
                foreach (var node in nodes.OrderByDescending(p => p.Weight))
                {
                    currentSum += node.Weight;
                    if (offset <= currentSum)
                    {
                        if (Logger.IsEnabled(LogLevel.Trace))
                            Logger.LogTrace($"Load to node {node.ServiceId}.");
                        return node;
                    }
                }
                var result= nodes[new Random().Next(0, nodes.Count)];
                if (Logger.IsEnabled(LogLevel.Trace))
                    Logger.LogTrace($"Load to node {result.ServiceId}.");
                return result;
            }
        }

19 View Source File : BloonTaskRunner.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

internal static bool Emit(ref Spawner __instance) {
            if (!__instance.isSandbox) {
                var i = 0;
                if (__instance.CurrentRound < 50)
                    i = rand.Next(100);
                else if (__instance.CurrentRound < 100)
                    i = rand.Next(50);
                else if (__instance.CurrentRound < 200)
                    i = rand.Next(20);
                else
                    i = rand.Next(10);


                if (i == 4) {
                    var coconut = BloonCreator.bloons.Find(a => a.icon.guidRef.Equals("CoconutIcon")).Clone().Cast<BloonModel>();
                    if (__instance.currentRound.ValueInt > 20) coconut.maxHealth = __instance.currentRound.ValueInt;
                    __instance.Emit(coconut, __instance.currentRound.ValueInt, 0);
                }
            }

            return true;
        }

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

private byte[] DrawVerifyCode(string code)
    {
        using var img = new Image<Rgba32>(4 + 16 * code.Length, 40);
        var font = new Font(SystemFonts.Families.First(), 16, FontStyle.Regular);
        var codeStr = code;
        img.Mutate(x =>
        {
            x.BackgroundColor(Color.WhiteSmoke);

            var r = new Random();

            //画噪线 
            for (var i = 0; i < 4; i++)
            {
                int x1 = r.Next(img.Width);
                int y1 = r.Next(img.Height);
                int x2 = r.Next(img.Width);
                int y2 = r.Next(img.Height);
                x.DrawLines(new Pen(_colors.RandomGet(), 1L), new PointF(x1, y1), new PointF(x2, y2));
            }

            //画验证码字符串 
            for (int i = 0; i < codeStr.Length; i++)
            {
                x.DrawText(codeStr[i].ToString(), font, _colors.RandomGet(), new PointF((float)i * 16 + 4, 8));
            }
        });

        using var stream = new MemoryStream();
        img.SaveAsPng(stream);
        return stream.GetBuffer();
    }

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

public static T RandomGet<T>(this T[] arr)
    {
        if (arr == null || !arr.Any())
            return default(T);

        var r = new Random();

        return arr[r.Next(arr.Length)];
    }

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

public string GenerateRandom(int length = 32)
    {
        var newRandom = new StringBuilder();
        var rd = new Random();
        for (int i = 0; i < length; i++)
        {
            newRandom.Append(_constant[rd.Next(_constant.Length)]);
        }
        return newRandom.ToString();
    }

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

public string GenerateRandomNumber(int length = 6)
    {
        var newRandom = new StringBuilder();
        var rd = new Random();
        for (int i = 0; i < length; i++)
        {
            newRandom.Append(_constant[rd.Next(10)]);
        }
        return newRandom.ToString();
    }

19 View Source File : DefaultCaptchaCodeGenerator.cs
License : MIT License
Project Creator : 1992w

public string Generate(int length)
        {
            Random rand = new Random();
            int maxRand = Letters.Length - 1;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                int index = rand.Next(maxRand);
                sb.Append(Letters[index]);
            }

            return sb.ToString();
        }

19 View Source File : DefaultCaptchaImageGenerator.cs
License : MIT License
Project Creator : 1992w

private Color GetRandomLightColor()
        {
            int low = 180, high = 255;

            int nRend = rand.Next(high) % (high - low) + low;
            int nGreen = rand.Next(high) % (high - low) + low;
            int nBlue = rand.Next(high) % (high - low) + low;

            return Color.FromArgb(nRend, nGreen, nBlue);
        }

19 View Source File : DefaultCaptchaImageGenerator.cs
License : MIT License
Project Creator : 1992w

private Color GetRandomDeepColor()
        {
            int redlow = 160, greenLow = 100, blueLow = 160;
            return Color.FromArgb(rand.Next(redlow), rand.Next(greenLow), rand.Next(blueLow));
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static string Random(int length)
        {
            var cArray = new char[length];
            for (var i = 0; i < length; i++)
            {
                cArray[i] = name[random.Next(name.Length)];
            }

            return new string(cArray);
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD

private instanceData MakeInstance(string aInstanceName, string aStyleName, int aRotation, int aEntID, int aX, int aY, int aZ)
        {
            try
            {
                int seed = aEntID + aX + aY + aZ + aRotation;
                Random random = new Random(seed);

                List<string> filepaths = this.Config.GetStyle(aStyleName).GetInstancePaths(aInstanceName);

                string filepath = filepaths[random.Next(filepaths.Count)];

                instanceData instance = new instanceData { filename = "Nails/" + filepath, rotation = aRotation };
                instance.xpos = aX;
                instance.ypos = aY;
                instance.zpos = aZ;
                instance.ent_id = aEntID;
                return instance;
            } catch(Exception e)
            {
                log.Error("VMFAdapter caught exception while generating instance data: ", e);
            }
            return null;
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : 1y0n

public static bool Gen_C(string shellcode, string path, string execute, string inject, string arch, string detect)
        {
            string finalcode;
            shellcode = Shellcode_Handle(shellcode);
            shellcode = XOR_C("c", shellcode);

            Random r = new Random();
            int n = r.Next(0, Global.Company_name.Length - 1);
            string comname = Global.Company_name[n];

            string c_compile_info = C_Template.compile_info.Replace("{{companyname}}", comname);

            //图标设置
            if (Global.ICONPATH != "")
            {
                c_compile_info += @"IDI_ICON1 ICON ""{{path}}""";
                c_compile_info = c_compile_info.Replace("{{path}}", Global.ICONPATH.Replace("\\", "\\\\"));
            }
            System.IO.File.WriteAllText("C:\\Windows\\Temp\\Yanri_res.rc", c_compile_info);
            string res_cmd = "windres C:\\Windows\\Temp\\Yanri_res.rc C:\\Windows\\Temp\\Yanri_res.o";
            if (arch.StartsWith("32"))
            {
                res_cmd += " --target=pe-i386";
            }
            Common.Execute_Cmd(res_cmd);
            bool icon_set = System.IO.File.Exists("C:\\Windows\\Temp\\Yanri_res.o");
            //System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.rc");

            //根据执行方式选择代码模板
            if (execute == "执行4-Dynamic")
            {
                finalcode = C_Template.Dynamic.Replace("{{shellcode}}", shellcode);
            }
            else
            {
                finalcode = C_Template.Base_Code.Replace("{{shellcode}}", shellcode);
                switch (execute)
                {
                    case "执行1-VirtualAlloc":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.VirtualALloc);
                        break;
                    case "执行2-GetProcAddress":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.GetProcessAddress);
                        break;
                    case "注入现有进程":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateRemoteThread);
                        finalcode = finalcode.Replace("{{pid}}", inject);
                        break;
                    case "注入新进程":
                        finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateNew);
                        finalcode = finalcode.Replace("{{processname}}", inject);
                        break;
                    default:
                        return false;
                }
            }
            //虚拟机及沙箱检测
            switch (detect)
            {
                case "沙箱:延时约180秒":
                    finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Super_Delay);
                    break;
                case "虚拟机:简单反虚拟机":
                    finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Vm_Detect);
                    break;
            }

            //保存代码到临时文件
            string temp_path = @"C:\Windows\Temp\YANRI_TEMP_" + Common.GetRandomString(6, true, true, true, false, "") + ".c";
            System.IO.File.WriteAllText(temp_path, finalcode);

            //编译
            if (C_Compiler(arch, temp_path, path, icon_set))
            {
                //System.IO.File.Delete(temp_path);
                System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
                return true;
            } else
            {
                System.IO.File.Delete(temp_path);
                System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
                return false;
            }
        }

19 View Source File : Math.cs
License : MIT License
Project Creator : 1CM69

public static int RandomInteger(int N)
    {
      lock (Math.RndObject)
        return Math.RndObject.Next(N);
    }

19 View Source File : Puzzle.cs
License : MIT License
Project Creator : 3583Bytes

private static Engine PuzzleKnightBishopCandidate()
        {
            Engine engine = new Engine("");

            Random random = new Random(DateTime.Now.Second);

            byte whiteKingIndex;
            byte blackKingIndex;
            byte whiteKnightIndex;
            byte whiteBishopIndex;

            do
            {
                whiteKingIndex = (byte)random.Next(63);
                blackKingIndex = (byte)random.Next(63);
                whiteKnightIndex = (byte)random.Next(63);
                whiteBishopIndex = (byte)random.Next(63);
            }
            while (
                whiteKingIndex == blackKingIndex ||
                whiteKingIndex == whiteBishopIndex ||
                whiteKingIndex == whiteKnightIndex ||
                whiteKnightIndex == whiteBishopIndex ||
                blackKingIndex == whiteBishopIndex ||
                blackKingIndex == whiteKingIndex
            );

            Piece whiteKing = new Piece(ChessPieceType.King, ChessPieceColor.White);
            Piece whiteBishop = new Piece(ChessPieceType.Bishop, ChessPieceColor.White);
            Piece whiteKnight = new Piece(ChessPieceType.Knight, ChessPieceColor.White);
            Piece blackKing = new Piece(ChessPieceType.King, ChessPieceColor.Black);

            engine.SetChessPiece(whiteKing, whiteKingIndex);
            engine.SetChessPiece(blackKing, blackKingIndex);
            engine.SetChessPiece(whiteKnight, whiteKnightIndex);
            engine.SetChessPiece(whiteBishop, whiteBishopIndex);
            
            engine.GenerateValidMoves();
            engine.EvaluateBoardScore();

            return engine;
        }

19 View Source File : Puzzle.cs
License : MIT License
Project Creator : 3583Bytes

private static Engine PuzzleRookCandidate()
        {
            Engine engine = new Engine("");

            Random random = new Random(DateTime.Now.Second);

            byte whiteKingIndex;
            byte blackKingIndex;
            byte whiteRookIndex;
            
            do
            {
                whiteKingIndex = (byte)random.Next(63);
                blackKingIndex = (byte)random.Next(63);
                whiteRookIndex = (byte)random.Next(63);
            }
            while (
                whiteKingIndex == blackKingIndex ||
                whiteKingIndex == whiteRookIndex ||
                blackKingIndex == whiteKingIndex
            );

            Piece whiteKing = new Piece(ChessPieceType.King, ChessPieceColor.White);
            Piece whiteRook = new Piece(ChessPieceType.Rook, ChessPieceColor.White);
            Piece blackKing = new Piece(ChessPieceType.King, ChessPieceColor.Black);

            engine.SetChessPiece(whiteKing, whiteKingIndex);
            engine.SetChessPiece(blackKing, blackKingIndex);
            engine.SetChessPiece(whiteRook, whiteRookIndex);

            engine.GenerateValidMoves();
            engine.EvaluateBoardScore();

            return engine;
        }

19 View Source File : Puzzle.cs
License : MIT License
Project Creator : 3583Bytes

private static Engine PuzzleKingPawnCandidate()
        {
            Engine engine = new Engine("");

            Random random = new Random(DateTime.Now.Second);

            byte whiteKingIndex;
            byte blackKingIndex;
            byte whitePawnIndex;

            do
            {
                whiteKingIndex = (byte)random.Next(63);
                blackKingIndex = (byte)random.Next(63);
                whitePawnIndex = (byte)random.Next(63);
            }
            while (
                whiteKingIndex == blackKingIndex ||
                whiteKingIndex == whitePawnIndex ||
                blackKingIndex == whiteKingIndex ||
                whitePawnIndex <= 8 ||whitePawnIndex >= 56 ||
                whitePawnIndex < blackKingIndex
            );

            Piece whiteKing = new Piece(ChessPieceType.King, ChessPieceColor.White);
            Piece whitePawn = new Piece(ChessPieceType.Pawn, ChessPieceColor.White);
            Piece blackKing = new Piece(ChessPieceType.King, ChessPieceColor.Black);

            engine.SetChessPiece(whiteKing, whiteKingIndex);
            engine.SetChessPiece(blackKing, blackKingIndex);
            engine.SetChessPiece(whitePawn, whitePawnIndex);

            engine.GenerateValidMoves();
            engine.EvaluateBoardScore();

            return engine;
        }

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

private static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

19 View Source File : StringExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public static string GenerateRandom(this String obj, int Length)
        {
            StringBuilder newRandom = new StringBuilder(constant.Length);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(constant.Length)]);
            }
            return newRandom.ToString();
        }

19 View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task Muse(PlayerEnreplacedy player)
        {
            if (player.Mp >= player.MaxMp)
            {
                await StopAction(player);
                await _mudProvider.ShowMessage(player.Id, $"{player.Status}结束,你站了起来。。。");
            }
            else
            {
                Random random = new Random();
                int addMp = random.Next((player.MaxMp / 40) + 1, (player.MaxMp / 20) + 1);
                if (player.Mp + addMp > player.MaxMp)
                {
                    addMp = player.MaxMp - player.Mp;
                }
                player.Mp += addMp;
                await _playerDomainService.Update(player);

                await _mudProvider.ShowMessage(player.Id, $"你正在{player.Status}。。。");
                await _mudProvider.ShowMessage(player.Id, $"你感觉精神好多了,内力恢复 +{addMp}。。。");
                await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            }
          
        }

19 View Source File : UserCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private string GenerateRandom(int Length)
        {
            char[] constant =
            {
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
            };

            StringBuilder newRandom = new StringBuilder(constant.Length);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(constant.Length)]);
            }
            return newRandom.ToString().ToUpper();
        }

19 View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task Heal(PlayerEnreplacedy player)
        {
            if (player.Hp >= player.MaxHp)
            {
                await _mudProvider.ShowMessage(player.Id, $"{player.Status}结束,你站了起来。。。");

                await StopAction(player);
            }
            else
            {
                Random random = new Random();
                int addHp = random.Next((player.MaxHp / 40) + 1, (player.MaxHp / 20) + 1);
                if (player.Hp + addHp > player.MaxHp)
                {
                    addHp = player.MaxHp - player.Hp;
                }
                player.Hp += addHp;

                await _mudProvider.ShowMessage(player.Id, $"你正在{player.Status}。。。");
                await _mudProvider.ShowMessage(player.Id, $"你感觉身体好多了,气血恢复 +{addHp}。。。");
                await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            }
         
        }

19 View Source File : CaptchaUtil.cs
License : Apache License 2.0
Project Creator : 91270

public static CaptchaResult GenerateCaptchaImage(string captchaCode, int width = 0, int height = 30)
        {
            //验证码颜色集合
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };

            //定义图像的大小,生成图像的实例
            var image = new Bitmap(width == 0 ? captchaCode.Length * 25 : width, height);

            var g = Graphics.FromImage(image);

            //背景设为白色
            g.Clear(Color.White);

            var random = new Random();

            for (var i = 0; i < 100; i++)
            {
                var x = random.Next(image.Width);
                var y = random.Next(image.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //验证码绘制在g中  
            for (var i = 0; i < captchaCode.Length; i++)
            {
                //随机颜色索引值 
                var cindex = random.Next(c.Length);

                //随机字体索引值 
                var findex = random.Next(fonts.Length);

                //字体 
                var f = new Font(fonts[findex], 15, FontStyle.Bold);

                //颜色  
                Brush b = new SolidBrush(c[cindex]);

                var ii = 4;
                if ((i + 1) % 2 == 0)
                    ii = 2;

                //绘制一个验证字符  
                g.DrawString(captchaCode.Substring(i, 1), f, b, 17 + (i * 17), ii);
            }

            var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            g.Dispose();
            image.Dispose();

            return new CaptchaResult { CaptchaGUID = Guid.NewGuid().ToString().ToUpper(),  CaptchaCode = captchaCode, CaptchaMemoryStream = ms, Timestamp = DateTime.Now };
        }

19 View Source File : RecurringQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Dictionary<string,T>> Subscribe<T>()
        {
            var list = new Dictionary<string, T>();
            var channel = typeof(T).Name.ToLower();
            var key = $"{queueName}_{channel}";
            var dic = await _redisDb.HashGetAll<QueueData<T>>(key);
            if (dic == null || dic.Count == 0)
            {
                return default;
            }

            bool hasChange = false;
            Random rnd = new Random();
            foreach (var item in dic)
            {
                var uniqueId = item.Key;
                var itemValue = item.Value;
                if (itemValue.DelayTime.Subtract(DateTime.Now).TotalMilliseconds > 0)
                {
                    //没到时间
                    continue;
                }


                var delay = itemValue.DelayMax > itemValue.DelayMin ? rnd.Next(itemValue.DelayMin, itemValue.DelayMax) : itemValue.DelayMin;
                if (delay < 2000)
                {
                    delay = 2000;
                } 
                //下次消费时间
                itemValue.DelayTime = DateTime.Now.AddMilliseconds(delay);

                if (!list.ContainsKey(uniqueId))
                {
                    list.Add(uniqueId, itemValue.Data);
                }
                await _redisDb.HashSet(key, uniqueId, itemValue);
                hasChange = true;
            }

            if (hasChange)
            {
                await RemoveCache(channel);
            }

            return list;
        }

19 View Source File : CaptchaUtil.cs
License : Apache License 2.0
Project Creator : 91270

public static string GetRandomEnDigitalText(int codeLength = 4)
        {
            var Letters = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";

            var array = Letters.Split(new[] { ',' });

            var random = new Random();

            var temp = -1;

            var captcheCode = string.Empty;

            for (int i = 0; i < codeLength; i++)
            {
                if (temp != -1)
                    random = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

                var index = random.Next(array.Length);

                if (temp != -1 && temp == index)
                    return GetRandomEnDigitalText(codeLength);

                temp = index;

                captcheCode += array[index];
            }
            return captcheCode;
        }

19 View Source File : CaptchaUtil.cs
License : Apache License 2.0
Project Creator : 91270

public static CaptchaResult GenerateCaptchaImage(string captchaCode, int width = 0, int height = 30)
        {
            //验证码颜色集合
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };

            //定义图像的大小,生成图像的实例
            var image = new Bitmap(width == 0 ? captchaCode.Length * 25 : width, height);

            var g = Graphics.FromImage(image);

            //背景设为白色
            g.Clear(Color.White);

            var random = new Random();

            for (var i = 0; i < 100; i++)
            {
                var x = random.Next(image.Width);
                var y = random.Next(image.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //验证码绘制在g中  
            for (var i = 0; i < captchaCode.Length; i++)
            {
                //随机颜色索引值 
                var cindex = random.Next(c.Length);

                //随机字体索引值 
                var findex = random.Next(fonts.Length);

                //字体 
                var f = new Font(fonts[findex], 15, FontStyle.Bold);

                //颜色  
                Brush b = new SolidBrush(c[cindex]);

                var ii = 4;
                if ((i + 1) % 2 == 0)
                    ii = 2;

                //绘制一个验证字符  
                g.DrawString(captchaCode.Substring(i, 1), f, b, 17 + (i * 17), ii);
            }

            var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            g.Dispose();
            image.Dispose();

            return new CaptchaResult { CaptchaGUID = Guid.NewGuid().ToString().ToUpper(),  CaptchaCode = captchaCode, CaptchaMemoryStream = ms, Timestamp = DateTime.Now };
        }

19 View Source File : SkillCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(LearnSkillCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var objectSkillId = command.MySkillId;
            var type = command.Type;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                return Unit.Value;
            }

            int skillId = 0;
            int objectSkillLevel = 0;

            if (type == 1)
            {
                var objectSkill = await _playerSkillDomainService.Get(objectSkillId);
                if (objectSkill == null)
                {
                    return Unit.Value;
                }
                skillId = objectSkill.SkillId;
                objectSkillLevel = objectSkill.Level;
            }
            else
            {
                var objectSkill = await _npcSkillDomainService.Get(objectSkillId);
                if (objectSkill == null)
                {
                    return Unit.Value;
                }
                skillId = objectSkill.SkillId;
                objectSkillLevel = objectSkill.Level;
            }


            var skill = await _skillDomainService.Get(skillId);
            if (skill == null)
            {
                return Unit.Value;
            }

            if (player.Pot <= 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"潜能不够,无法修练!");
                return Unit.Value;
            }

            var needPot = 0;
            var exp = 0;

            var mySkill = await _playerSkillDomainService.Get(x => x.PlayerId == playerId && x.SkillId == skillId);
            if (mySkill == null)
            {
                needPot = 100;
                exp = 1;
                if (player.Pot <= needPot)
                {
                    await _mudProvider.ShowMessage(player.Id, $"潜能不够,无法修练!");
                    return Unit.Value;
                }

                mySkill = new PlayerSkillEnreplacedy
                {
                    Exp = 1,
                    Level = 1,
                    SkillId = skillId,
                    PlayerId = playerId,
                    SkillName = skill.Name
                };
                await _playerSkillDomainService.Add(mySkill);

                player.Pot -= needPot;
                await _playerDomainService.Update(player);

                await _mudProvider.ShowMessage(player.Id, $"你消耗潜能{needPot},学会了[{skill.Name}]!");
                return Unit.Value;
            }


            if (player.Level * 10 < mySkill.Level)
            {
                await _mudProvider.ShowMessage(player.Id, $"武功最高等级不能超过自身等级的10倍!");
                return Unit.Value;
            }

            if (mySkill.Level >= objectSkillLevel && !skill.IsBase)
            {
                await _mudProvider.ShowMessage(player.Id, $"你已经无法从对方身上学到什么了!");
                return Unit.Value;
            }

            var @int = player.Int * 3 + player.IntAdd;
            var nextLevelExp = (mySkill.Level + 1) * (mySkill.Level + 1) * 50;
            var levelUpExp = nextLevelExp - mySkill.Level * mySkill.Level * 50;

            Random random = new Random();
            exp = random.Next(1, levelUpExp / 10);
            needPot = exp * 100 / @int;

            var effect = exp * 1000 / levelUpExp;

            string effectWords;
            if (effect > 80)
            {
                effectWords = "恍然大悟";
            }
            else if (effect > 50)
            {
                effectWords = "有所顿悟";
            }
            else if (effect > 20)
            {
                effectWords = "略有所获";
            }
            else if (effect > 10)
            {
                effectWords = "略有所获";
            }
            else
            {
                effectWords = "似乎没有什么进展";
            }

            player.Pot -= needPot;
            await _playerDomainService.Update(player);
            mySkill.SkillName = skill.Name;
            mySkill.Exp += exp;
            await _mudProvider.ShowMessage(player.Id, $"你消耗潜能{needPot},{effectWords},[{skill.Name}]经验增加{exp}!");

            if (mySkill.Exp > nextLevelExp)
            {
                mySkill.Level++;
                await _mudProvider.ShowMessage(player.Id, $"[{skill.Name}]等级上升为 Lv.{mySkill.Level}!");
            }



            await _playerSkillDomainService.Update(mySkill);



            await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            return Unit.Value;
        }

19 View Source File : SkillCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(LearnWareCommand command, CancellationToken cancellationToken)
        {
            var myWareId = command.MyWareId;
            var playerId = command.PlayerId;

            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
                return Unit.Value;
            }

            var playerWare = await _playerWareDomainService.Get(myWareId);
            if (playerWare == null || playerWare.PlayerId != playerId)
            {
                await _bus.RaiseEvent(new DomainNotification($"你什么也没学会!"));
                return Unit.Value;
            }

            var ware = await _wareDomainService.Get(playerWare.WareId);
            if (ware == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"你什么也没学会!"));
                await _playerWareDomainService.Delete(playerWare);
                return Unit.Value;
            }

            if (ware.Category != WareCategoryEnum.秘籍)
            {
                await _bus.RaiseEvent(new DomainNotification($"你什么也没学会!"));
                return Unit.Value;
            }

            var skill = await _skillDomainService.Get(x => x.Name == ware.Name);
            if (skill == null)
            {
                await _bus.RaiseEvent(new DomainNotification($"你什么也没学会!"));
                return Unit.Value;
            }

            if (player.Pot <= 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"潜能不够,无法修练!");
                return Unit.Value;
            }

            var needPot = 0;
            var exp = 0;

            var mySkill = await _playerSkillDomainService.Get(x => x.PlayerId == playerId && x.SkillId == skill.Id);
            if (mySkill == null)
            {
                needPot = 100;
                exp = 1;
                if (player.Pot <= needPot)
                {
                    await _mudProvider.ShowMessage(player.Id, $"潜能不够,无法修练!");
                    return Unit.Value;
                }

                mySkill = new PlayerSkillEnreplacedy
                {
                    Exp = 1,
                    Level = 1,
                    SkillId = skill.Id,
                    PlayerId = playerId,
                    SkillName = skill.Name
                };
                await _playerSkillDomainService.Add(mySkill);

                player.Pot -= needPot;
                await _playerDomainService.Update(player);

                await _mudProvider.ShowMessage(player.Id, $"你消耗潜能{needPot},学会了[{skill.Name}]!");
                return Unit.Value;
            }


            if (player.Level * 10 < mySkill.Level)
            {
                await _mudProvider.ShowMessage(player.Id, $"武功最高等级不能超过自身等级的10倍!");
                return Unit.Value;
            }

            if (mySkill.Level >= playerWare.Level && !skill.IsBase)
            {
                await _mudProvider.ShowMessage(player.Id, $"你已经无法从秘籍上学到什么了!");
                return Unit.Value;
            }

            var @int = player.Int * 3 + player.IntAdd;
            var nextLevelExp = (mySkill.Level + 1) * (mySkill.Level + 1) * 50;
            var levelUpExp = nextLevelExp - mySkill.Level * mySkill.Level * 50;

            Random random = new Random();
            exp = random.Next(1, levelUpExp / 10);
            needPot = exp * 100 / @int;

            var effect = exp * 1000 / levelUpExp;

            string effectWords;
            if (effect > 80)
            {
                effectWords = "恍然大悟";
            }
            else if (effect > 50)
            {
                effectWords = "有所顿悟";
            }
            else if (effect > 20)
            {
                effectWords = "略有所获";
            }
            else if (effect > 10)
            {
                effectWords = "略有所获";
            }
            else
            {
                effectWords = "似乎没有什么进展";
            }

            player.Pot -= needPot;
            await _playerDomainService.Update(player);
            mySkill.SkillName = skill.Name;
            mySkill.Exp += exp;
            await _mudProvider.ShowMessage(player.Id, $"你消耗潜能{needPot},{effectWords},[{skill.Name}]经验增加{exp}!");

            if (mySkill.Exp > nextLevelExp)
            {
                mySkill.Level++;
                await _mudProvider.ShowMessage(player.Id, $"[{skill.Name}]等级上升为 Lv.{mySkill.Level}!");
            }



            await _playerSkillDomainService.Update(mySkill);



            await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);

            return Unit.Value;
        }

19 View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private async Task DoWork(PlayerEnreplacedy player)
        {
            await _mudProvider.ShowMessage(player.Id, $"你正在{player.Status}。。。");
            WorkTypeEnum workType = WorkTypeEnum.伐木;
            switch (player.Status)
            {
                case PlayerStatusEnum.伐木:
                    workType = WorkTypeEnum.伐木;
                    break;
                case PlayerStatusEnum.挖矿:
                    workType = WorkTypeEnum.挖矿;
                    break;
                case PlayerStatusEnum.打猎:
                    workType = WorkTypeEnum.打猎;
                    break;
                case PlayerStatusEnum.采药:
                    workType = WorkTypeEnum.采药;
                    break;
                case PlayerStatusEnum.钓鱼:
                    workType = WorkTypeEnum.钓鱼;
                    break;
                case PlayerStatusEnum.打工:
                    workType = WorkTypeEnum.打工;
                    break;

                default:
                    return;
            }

            var ids = (await _roomItemDropDomainService.GetAll()).Where(x => x.RoomId == player.RoomId).Select(x=>x.ItemDropId).ToList();

            var itemDrop = (await _itemDropDomainService.GetAll()).Where(x => ids.Contains(x.Id)).FirstOrDefault(x => x.WorkType == workType);
            if (itemDrop == null)
            {
                return;
            }
           

            var itemDropRates = (await _itemDropRateDomainService.GetAll()).Where(x => x.ItemDropId == itemDrop.Id).ToList();
            if (itemDropRates?.Count == 0)
            {
                return;
            }

            var random = new Random();
            int maxWeight = 100;//掉落总权重
            var itemDropModels = new List<ItemDropRateModel>();
            foreach (var itemDropRate in itemDropRates.OrderBy(x=>x.Order))
            {
                if (itemDropRate.Percent < random.Next(0, 100))
                {
                    continue;
                }

                int number = random.Next(Math.Min(itemDropRate.MinNumber, itemDropRate.MaxNumber), itemDropRate.MaxNumber + 1);
                if (number <= 0)
                {
                    continue;
                }

                //掉落
                maxWeight -= itemDropRate.Weight;

                var itemDropModel = new ItemDropRateModel
                {
                    DropType = itemDropRate.DropType,
                    Number = number,
                    WareId = itemDropRate.WareId
                };
                itemDropModels.Add(itemDropModel);



                if (maxWeight <= 0)
                {
                    break;
                }
            }

            if (itemDropModels.Count == 0)
            {
                //没有掉落
                return;
            }

            var playerAttributeChanged = false;
            List<string> dropContents = new List<string>() ;

            foreach (var itemDropModel in itemDropModels)
            {
                switch (itemDropModel.DropType)
                {
                    case ItemDropTypeEnum.潜能:
                        playerAttributeChanged = true;
                        player.Pot += itemDropModel.Number;
                        dropContents.Add($"潜能 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.经验:
                        playerAttributeChanged = true;
                        player.Exp += itemDropModel.Number;
                        dropContents.Add($"经验 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.金钱:
                        playerAttributeChanged = true;
                        player.Money += itemDropModel.Number;
                        dropContents.Add($" +{itemDropModel.Number.ToMoney()}");
                        break;
                    case ItemDropTypeEnum.物品:
                        #region MyRegion
                        int wareId = itemDropModel.WareId;
                        int number = itemDropModel.Number;

                        var ware = await _wareDomainService.Get(wareId);
                        if (ware == null)
                        {
                            continue;
                        }

                        dropContents.Add($"{number}{ware.Unit}{ware.Name}");

                        var canStack = ware.Category != WareCategoryEnum.武器;

                        if (canStack)
                        {
                            var playerWare = await _playerWareDomainService.Get(x => x.WareId == ware.Id && x.PlayerId == player.Id);
                            if (playerWare == null)
                            {
                                playerWare = new PlayerWareEnreplacedy
                                {
                                    IsBind = false,
                                    IsTemp = false,
                                    Level = 1,
                                    Number = number,
                                    Damage = 0,
                                    PlayerId = player.Id,
                                    Status = WareStatusEnum.卸下,
                                    WareId = wareId,
                                    WareName = ware.Name
                                };
                                await _playerWareDomainService.Add(playerWare);
                            }
                            else
                            {
                                playerWare.Number += number;
                                await _playerWareDomainService.Update(playerWare);
                            }
                        }
                        else
                        {
                            var playerWare = new PlayerWareEnreplacedy
                            {
                                IsBind = false,
                                IsTemp = false,
                                Level = 1,
                                Number = number,
                                Damage = 0,
                                PlayerId = player.Id,
                                Status = WareStatusEnum.卸下,
                                WareId = wareId,
                                WareName = ware.Name
                            };
                            await _playerWareDomainService.Add(playerWare);
                        }
                        #endregion


                        break;
                }
               
            }

            if (playerAttributeChanged)
            {
                await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            }


            if (dropContents.Count > 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"获得{ string.Join(",", dropContents)   }。");   
            }


        }

19 View Source File : Util.cs
License : MIT License
Project Creator : a34546

public static string GenerateCode(int length)
        {
            var result = new char[length];

            for (int i = 0; i < length; i++)
            {
                result[i] = charsArray[random.Next(charsArrayLength)];
            }

            return new string(result);
        }

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public WorkbookStream ObfuscateAutoOpen(string localizedLabel = "Auto_Open")
        {
            Random randomUnicodeChar = new Random();
            string[] badUnicodeChars = { "\ufefe", "\uffff", "\ufeff", "\ufffe", "\uffef", "\ufff0", "\ufff1", "\ufff6", "\ufefd", "\u0000", "\udddd" };
            int indexLabel = 0;
            string unicodeLabelWithBadChars = "";
            List<Lbl> labels = GetAllRecordsByType<Lbl>();
            Lbl autoOpenLbl = labels.First(l => l.fBuiltin && l.Name.Value.Equals("\u0001") ||
                                                l.Name.Value.ToLower().StartsWith(localizedLabel.ToLower()));
            Lbl replaceLabelStringLbl = ((BiffRecord)autoOpenLbl.Clone()).AsRecordType<Lbl>();

            //Characters that work
            //fefe, ffff, feff, fffe, ffef, fff0, fff1, fff6, fefd, 0000, dddd
            //Pretty much any character that is invalid unicode - though \ucccc doesn't seem to work - need better criteria for parsing

            foreach (char localizedLabelChar in localizedLabel)
            {
                indexLabel = randomUnicodeChar.Next(localizedLabel.Length);
                for (var i = 0; i < 10; i += 1)
                {
                    unicodeLabelWithBadChars += badUnicodeChars[indexLabel];
                }
                unicodeLabelWithBadChars += localizedLabelChar;
            }
            replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(unicodeLabelWithBadChars, true));
            replaceLabelStringLbl.fBuiltin = false;

            // Hidden removes from the label manager entirely, but doesn't seem to work if fBuiltin is false
            // replaceLabelStringLbl.fHidden = true;

            WorkbookStream obfuscatedStream = ReplaceRecord(autoOpenLbl, replaceLabelStringLbl);
            obfuscatedStream = obfuscatedStream.FixBoundSheetOffsets();
            return obfuscatedStream;
        }

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public WorkbookStream ObfuscateAutoOpen(string localizedLabel = "Auto_Open")
        {
            Random randomUnicodeChar = new Random();
            string[] badUnicodeChars = { "\ufefe", "\uffff", "\ufeff", "\ufffe", "\uffef", "\ufff0", "\ufff1", "\ufff6", "\ufefd", "\u0000", "\udddd" };
            int indexLabel = 0;
            string unicodeLabelWithBadChars = "";
            List<Lbl> labels = GetAllRecordsByType<Lbl>();
            Lbl autoOpenLbl = labels.First(l => l.fBuiltin && l.Name.Value.Equals("\u0001") ||
                                                l.Name.Value.ToLower().StartsWith(localizedLabel.ToLower()));
            Lbl replaceLabelStringLbl = ((BiffRecord)autoOpenLbl.Clone()).AsRecordType<Lbl>();

            //Characters that work
            //fefe, ffff, feff, fffe, ffef, fff0, fff1, fff6, fefd, 0000, dddd
            //Pretty much any character that is invalid unicode - though \ucccc doesn't seem to work - need better criteria for parsing

            foreach (char localizedLabelChar in localizedLabel)
            {
                indexLabel = randomUnicodeChar.Next(localizedLabel.Length);
                for (var i = 0; i < 10; i += 1)
                    unicodeLabelWithBadChars += badUnicodeChars[indexLabel];
            
                unicodeLabelWithBadChars += localizedLabelChar;
            }
            replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(unicodeLabelWithBadChars, true));
            replaceLabelStringLbl.fBuiltin = false;

            // Hidden removes from the label manager entirely, but doesn't seem to work if fBuiltin is false
            // replaceLabelStringLbl.fHidden = true;

            WorkbookStream obfuscatedStream = ReplaceRecord(autoOpenLbl, replaceLabelStringLbl);
            obfuscatedStream = obfuscatedStream.FixBoundSheetOffsets();
            return obfuscatedStream;
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aaaddress1

static string getObfscuteName(string localizedLabel)
        {
            string[] badUnicodeChars = { "\ufefe", "\uffff", "\ufeff", "\ufffe", "\uffef", "\ufff0", "\ufff1", "\ufff6", "\ufefd", "\u0000", "\udddd" };
            string unicodeLabelWithBadChars = "";
   
            //Characters that work
            //fefe, ffff, feff, fffe, ffef, fff0, fff1, fff6, fefd, 0000, dddd
            //Pretty much any character that is invalid unicode - though \ucccc doesn't seem to work - need better criteria for parsing

            foreach (char localizedLabelChar in localizedLabel)
            {
                int indexLabel = (new Random()).Next(localizedLabel.Length);
                for (var i = 0; i < 10; i += 1)
                    unicodeLabelWithBadChars += badUnicodeChars[indexLabel];
                unicodeLabelWithBadChars += localizedLabelChar;
            }
            return unicodeLabelWithBadChars;
        }

19 View Source File : Common.cs
License : Apache License 2.0
Project Creator : aadreja

public static string Random(int length = 8)
        {
            string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            var randomString = new StringBuilder();
            var random = new Random();

            for (int i = 0; i < length; i++)
                randomString.Append(chars[random.Next(chars.Length)]);

            return randomString.ToString();
        }

19 View Source File : PlayerServer.cs
License : Apache License 2.0
Project Creator : AantCoder

public bool GetKeyReconnect()
        {
            if ((DateTime.UtcNow - KeyReconnectTime).TotalMinutes < 30
                && !string.IsNullOrEmpty(KeyReconnect1))
                return false;

            KeyReconnectTime = DateTime.UtcNow;
            var rnd = new Random((int)(DateTime.UtcNow.Ticks & int.MaxValue));
            var key = "o6*#fn`~ыggTgj0&9 gT54Qa[g}t,23rfr4*vcx%%4/\"d!2" + rnd.Next(int.MaxValue).ToString()
                + DateTime.UtcNow.Date.AddHours(DateTime.UtcNow.Hour).ToBinary().ToString()
                + Public.Login;
            var hash = new CryptoProvider().GetHash(key);

            KeyReconnect2 = KeyReconnect1;
            KeyReconnect1 = hash;

            return true;
        }

19 View Source File : PriceRangeExtensions.cs
License : Apache License 2.0
Project Creator : Aaronontheweb

public static decimal NextDecimalSample(this Random random)
        {
            var sample = 1m;
            //After ~200 million tries this never took more than one attempt but it is possible to generate combinations of a, b, and c with the approach below resulting in a sample >= 1.
            while (sample >= 1)
            {
                var a = random.NextInt32();
                var b = random.NextInt32();
                //The high bits of 0.9999999999999999999999999999m are 542101086.
                var c = random.Next(542101087);
                sample = new decimal(a, b, c, false, 28);
            }
            return sample;
        }

19 View Source File : HasQuarterState.cs
License : GNU General Public License v3.0
Project Creator : abishekaditya

public void TurnCrank()
        {
            Console.WriteLine("You turned the crank");
            var winner = _random.Next(10);
            if ((winner == 5) && (Machine.Count > 1))
                Machine.State = Machine.WinnerState;
            else
            {
                Machine.State = Machine.SoldState;
            }
        }

19 View Source File : SeriesCustomTooltips3DChart.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void Initialize()
        {
            var xyzDataSeries3D = new XyzDataSeries3D<double>();

            for (int i = 0, pointIndex = 0; i < Count; i++)
            {
                var m1 = _random.Next(2) == 0 ? -1 : 1;
                var m2 = _random.Next(2) == 0 ? -1 : 1;
                var x1 = _random.NextDouble() * m1;
                var x2 = _random.NextDouble() * m2;

                if (x1 * x1 + x2 * x2 > 1) continue;

                var x = 2 * x1 * Math.Sqrt(1 - x1 * x1 - x2 * x2);
                var y = 2 * x2 * Math.Sqrt(1 - x1 * x1 - x2 * x2);
                var z = 1 - 2 * (x1 * x1 + x2 * x2);

                // Append an XYZ Point with random color
                // Set the PointMetadata.Tag which we bind to in the View 
                xyzDataSeries3D.Append(x, y, z, new PointMetadata3D(GetRandomColor(), 3.0f, false, 
                    string.Format("PointMetadata Index {0}", ++pointIndex)));
            }

            SciChart.RenderableSeries[0].DataSeries = xyzDataSeries3D;
        }

19 View Source File : MixedCharts.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void MixedCharts_OnLoaded(object sender, RoutedEventArgs e)
        {
            var leftDataSeries0 = new UniformXyDataSeries<double>();
            var leftDataSeries1 = new UniformXyDataSeries<double>();

            var rightDataSeries0 = new XyDataSeries<DateTime, double>();
            var rightDataSeries1 = new XyDataSeries<DateTime, double>();

            var random = new Random();

            for (int i = 0; i < 20; i++)
            {
                leftDataSeries0.Append(random.Next(10));
                leftDataSeries1.Append(random.Next(10));

                rightDataSeries0.Append(DateTime.Now.AddHours(i), random.Next(10));
                rightDataSeries1.Append(DateTime.Now.AddHours(i), random.Next(10));
            }

            sciChart.RenderableSeries[0].DataSeries = leftDataSeries0;
            sciChart.RenderableSeries[1].DataSeries = leftDataSeries1;

            sciChart.RenderableSeries[2].DataSeries = rightDataSeries0;
            sciChart.RenderableSeries[3].DataSeries = rightDataSeries1;

            sciChart.ZoomExtents();
        }

19 View Source File : FastPalettedScatterCharts.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private static Color GetRandomColor(Random random)
        {
            return Color.FromArgb(0xFF, (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255));
        }

19 View Source File : VitalSignsIndicatorsProvider.cs
License : MIT License
Project Creator : ABTSoftware

private string RandomString(IReadOnlyList<string> values)
        {
            return values[_random.Next(values.Count)];
        }

19 View Source File : World.cs
License : MIT License
Project Creator : ABTSoftware

public int NextRandomIndex()
        {
            lock (_rng)
            {
                return _rng.Next(People.Length);
            }
        }

19 View Source File : VitalSignsIndicatorsProvider.cs
License : MIT License
Project Creator : ABTSoftware

private int RandomInt(IReadOnlyList<int> values)
        {
            return values[_random.Next(values.Count)];
        }

19 View Source File : VerticalCharts.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private void VerticalXAxis_OnLoaded(object sender, RoutedEventArgs e)
        {
            var leftDataSeries0 = new UniformXyDataSeries<double>();
            var leftDataSeries1 = new UniformXyDataSeries<double>();

            var rightDataSeries0 = new UniformXyDataSeries<double>();
            var rightDataSeries1 = new UniformXyDataSeries<double>();

            var random = new Random(0);

            for (int i = 0; i < 20; i++)
            {
                leftDataSeries0.Append(random.Next(10));
                leftDataSeries1.Append(random.Next(10));

                rightDataSeries0.Append(random.Next(10));
                rightDataSeries1.Append(random.Next(10));
            }

            sciChartLeft.RenderableSeries[0].DataSeries = leftDataSeries0;
            sciChartLeft.RenderableSeries[1].DataSeries = leftDataSeries1;

            sciChartRight.RenderableSeries[0].DataSeries = rightDataSeries0;
            sciChartRight.RenderableSeries[1].DataSeries = rightDataSeries1;
        }

19 View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware

public Color GetRandomColor()
        {
            return Color.FromArgb(0xFF, (byte)_random.Next(255), (byte)_random.Next(255), (byte)_random.Next(255));
        }

19 View Source File : HistogramBarDemoProjectViewModel.cs
License : MIT License
Project Creator : ABTSoftware

public void LoadRandomData(int candlesCount, int ticksPerCandle)
        {
            _data = null;
            _ticksPerCandle = ticksPerCandle;

            var dataSource = new RandomWalkGenerator();
            var ticksCount = (candlesCount + 1) * ticksPerCandle;
            _data = dataSource.GetRandomWalkSeries(ticksCount).YData.ToArray();

            _index = 0;
            for (int j = 0; j < candlesCount; j++)
            {
                var date = _baseTime.AddMinutes(j * 30);
                var volume = _random.Next(100);
                var bidOrAsk = _random.Next(2) == 0 ? BidOrAsk.Bid : BidOrAsk.Ask;
                var replacedulativeVolume = default(double);

                var metaData = new CandlestickMetaData();
                metaData.AddTick(new CandleTick
                {
                    BidOrAsk = bidOrAsk,
                    Price = _data[_index],
                    Volume = volume,
                    TimeStamp = date
                });

                replacedulativeVolume += bidOrAsk.Equals(BidOrAsk.Ask) ? volume : -volume;

                var high = replacedulativeVolume > 0 ? replacedulativeVolume : 0;
                var low = replacedulativeVolume < 0 ? replacedulativeVolume : 0;

                _dataSeries1.Append(date, replacedulativeVolume, high, low, replacedulativeVolume);
                _dataSeries0.Append(date, _data[_index], _data[_index], _data[_index], _data[_index], metaData);
                _candleCount = _dataSeries0.Count;

                replacedulativeVolume = AddTicks(ticksPerCandle, date, replacedulativeVolume);

                _filterDataSeries.Append(date, _movingAverage.Push(replacedulativeVolume).Current);
            }
        }

See More Examples