System.Random.Next()

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

1245 Examples 7

19 Source : G_CUIColorPicker.cs
with MIT License
from 1ZouLTReX1

public void SetRandomColor()
        {
            var rng = new System.Random();
            var r = ( rng.Next() % 1000 ) / 1000.0f;
            var g = ( rng.Next() % 1000 ) / 1000.0f;
            var b = ( rng.Next() % 1000 ) / 1000.0f;
            Color = new Color( r, g, b );
        }

19 Source : QQTea.cs
with MIT License
from 499116344

public static byte[] Encrypt(byte[] In, int offset, int len, byte[] key)
        {
            var temp = new byte[In.Length];
            Buffer.BlockCopy(In, 0, temp, 0, In.Length);
            var random = new Random();
            var num = (len + 10) % 8;
            if (num != 0)
            {
                num = 8 - num;
            }

            var array = new byte[len + num + 10];
            array[0] = (byte) ((random.Next() & 248) | num);
            for (var i = 1; i < num + 3; i++)
            {
                array[i] = (byte) (random.Next() & 255);
            }

            Array.Copy(temp, 0, array, num + 3, len);
            for (var j = num + 3 + len; j < array.Length; j++)
            {
                array[j] = 0;
            }

            var array2 = new byte[len + num + 10];
            for (var k = 0; k < array2.Length; k += 8)
            {
                Code(array, 0, k, array2, 0, k, key);
            }

            return array2;
        }

19 Source : QQTea.cs
with MIT License
from 499116344

private static int Rand()
        {
            var random = new Random();
            return random.Next();
        }

19 Source : TLV_0006.cs
with MIT License
from 499116344

public byte[] Get_Tlv(QQUser user)
        {
            if (WSubVer == 0x0002)
            {
                if (user.TXProtocol.BufTgtgt == null)
                {
                    var data = new BinaryWriter(new MemoryStream());
                    data.BeWrite(new Random(Guid.NewGuid().GetHashCode()).Next()); //随机4字节??
                    data.BeWrite(WSubVer); //wSubVer
                    data.BeWrite(user.QQ); //QQ号码
                    data.BeWrite(user.TXProtocol.DwSsoVersion);
                    data.BeWrite(user.TXProtocol.DwServiceId);
                    data.BeWrite(user.TXProtocol.DwClientVer);
                    data.BeWrite((ushort) 0);
                    data.Write(user.TXProtocol.BRememberPwdLogin);
                    data.Write(user.MD51); //密码的一次MD5值,服务器用该MD5值验证用户密码是否正确
                    data.BeWrite(user.TXProtocol.DwServerTime); //登录时间
                    data.Write(new byte[13]); //固定13字节
                    data.Write(Util.IPStringToByteArray(user.TXProtocol.DwClientIP)); //IP地址
                    data.BeWrite(user.TXProtocol.DwIsp); //dwISP
                    data.BeWrite(user.TXProtocol.DwIdc); //dwIDC
                    data.WriteKey(user.TXProtocol.BufComputerIdEx); //机器码
                    data.Write(user.TXProtocol.BufTgtgtKey); //00DD临时密钥(通过验证时客户端用该密钥解密服务端发送回来的数据)

                    user.TXProtocol.BufTgtgt =
                        QQTea.Encrypt(data.BaseStream.ToBytesArray(), user.Md52());
                }
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            var tlv = new BinaryWriter(new MemoryStream());
            tlv.Write(user.TXProtocol.BufTgtgt);
            FillHead(Command);
            FillBody(tlv.BaseStream.ToBytesArray(), tlv.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

19 Source : Redirection.Reactive.cs
with MIT License
from 71

private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
        {
            // Make id
            do
            {
                id = ObservingRedirectionsIdGenerator.Next();
            }
            while (ObservingRedirections.ContainsKey(id));

            // Creates an array containing all parameter types
            int diff = method.IsStatic ? 0 : 1;

            ParameterInfo[] originalParameters = method.GetParameters();
            Type[] originalParameterTypes = new Type[originalParameters.Length + diff];

            if (diff == 1 /* !method.IsStatic */)
                originalParameterTypes[0] = method.DeclaringType;

            for (int i = 0; i < originalParameters.Length; i++)
            {
                originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
            }

            // Create an identical method
            bool isCtor = method is ConstructorInfo;
            Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;

            DynamicMethod dyn = new DynamicMethod(
                name:              method.Name,
                attributes:        MethodAttributes.Public | MethodAttributes.Static,
                callingConvention: CallingConventions.Standard,
                returnType:        returnType,
                parameterTypes:    originalParameterTypes,
                owner:             method.DeclaringType,
                skipVisibility:    true);

            // Make the method call the observable
            ILGenerator il = dyn.GetILGenerator();
            {
                // This is in a block to make every more readable,
                // the following comments describe what's happening in the generated method.

                // Emit "this", or "null"
                if (method.IsStatic)
                {
                    il.Emit(OpCodes.Ldnull);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);

                    if (method.DeclaringType.GetTypeInfo().IsValueType)
                    {
                        il.Emit(OpCodes.Ldobj, method.DeclaringType);
                        il.Emit(OpCodes.Box, method.DeclaringType);
                    }
                }

                // Create an array containing all parameters
                il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
                il.Emit(OpCodes.Newarr, typeof(object));

                for (int i = 0; i < originalParameters.Length; i++)
                {
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg, i + diff);

                    Type parameterType = originalParameterTypes[i + diff];

                    if (parameterType.GetTypeInfo().IsValueType)
                        il.Emit(OpCodes.Box, parameterType);

                    il.Emit(OpCodes.Stelem_Ref);
                }

                // Array is still on stack (thanks to dup)
                // Emit id
                il.Emit(OpCodes.Ldc_I4, id);

                // Call "hook" method
                il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));

                // Return returned result
                // (But first, cast it if needed)
                if (returnType == typeof(void))
                    il.Emit(OpCodes.Pop);
                else if (returnType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Unbox_Any, returnType);
                else if (returnType != typeof(object))
                    il.Emit(OpCodes.Castclreplaced, returnType);

                il.Emit(OpCodes.Ret);
            }

            // Return the redirection
            return new MethodRedirection(method, dyn, false);
        }

19 Source : BrowsePage.cs
with GNU General Public License v3.0
from 9vult

private void BtnAdd_Clicked(object sender, EventArgs e)
        {
            string url = txtUrl.Text;
            string name = string.Empty;
            string num = string.Empty;

            if (url == "" || url == null)
            {
                PopUp("Error", "Please enter a URL");
                return;
            }

            if (url.StartsWith("https://mangadex.org/replacedle/"))
            {
                // TODO: Name
                name = url.Split('/')[5];
                num = url.Split('/')[4];
                url = "https://mangadex.org/api/manga/" + num;

                Manga m = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);

                MClient.dbm.GetMangaDB().Add(m);

                foreach (Chapter c in m.GetChapters())
                {
                    MClient.dlm.AddToQueue(new MangaDexDownload(c));
                }
                // Start downloading the first one
                MClient.dlm.DownloadNext();
            }
            else if (url.StartsWith("https://nhentai.net/g/"))
            {
                num = url.Split('/')[4];
                name = txtName.Text != "" ? txtName.Text : "Hentai " + new Random().Next();

                JObject hJson = new JObject(
                    new JProperty("hentai",
                        new JObject(
                            new JProperty("replacedle", name),
                            new JProperty("num", num),
                            new JProperty("url", url))));

                DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));

                Hentai h = new Hentai(hDir, hJson.ToString());
                MClient.dbm.GetMangaDB().Add(h);

                Chapter ch = h.GetChapters()[0];
                MClient.dlm.AddToQueue(new NhentaiDownload(ch));
                // Start downloading the first one
                MClient.dlm.DownloadNext();
            } else
            {
                PopUp("Error", "Invalid URL!");
                return;
            }
            PopUp("Info", "Download started!\nPlease do not close MikuReader until the download is complete.");
        }

19 Source : MicroVM.CPU.cs
with MIT License
from a-downing

public bool Cycle(out Status status, int numCycles = 1) {
            savedStatus = Status.UNDEFINED;

            for(int i = 0; i < numCycles; i++) {
                if(savedStatus != Status.UNDEFINED) {
                    status = savedStatus;
                    return false;
                }

                if((flags & (uint)Flag.INTERRUPTS_ENABLED) != 0 && pendingInterrupts.Count != 0) {
                    uint addr = pendingInterrupts.Dequeue();

                    replacedignMemory(registers[(int)Register.SP], pc);
                    registers[(int)Register.SP] += 4;
                    pc = addr;

                    if(savedStatus != Status.UNDEFINED) {
                        status = savedStatus;
                        return false;
                    }
                }

                if(pc >= instructions.Length) {
                    status = Status.OUT_OF_INSTRUCTIONS;
                    return false;
                }

                uint inst = instructions[pc++];
                Opcode opcode = (Opcode)((inst & (uint)Instruction.OPCODE_MASK) >> (int)Instruction.OPCODE_SHIFT);
                Cond cond = (Cond)((inst & (int)Instruction.COND_MASK) >> (int)Instruction.COND_SHIFT);
                uint op1Flag = inst & (uint)Instruction.OP1_FLAG_MASK;
                uint op2Flag = inst & (uint)Instruction.OP2_FLAG_MASK;
                uint op3Flag = inst & (uint)Instruction.OP3_FLAG_MASK;
                uint immediate = 0;
                bool nextIsImmediate = false;

                /*Program.Print("");
                Program.PrintVar(nameof(pc), pc);
                Program.Print($"instruction: {opcode}.{cond}");
                Program.Print($"instruction bits: {Convert.ToString(inst, 2).PadLeft(32, '0')}");
                Program.Print($"flags: {Convert.ToString(flags & (uint)Flag.EQUAL, 2).PadLeft(32, '0')}");*/

                if(op1Flag == 0) {
                    immediate = inst & (uint)Instruction.IMM1_MASK;

                    if(immediate == (uint)Instruction.IMM1_MASK) {
                        nextIsImmediate = true;
                    }
                } else if(op2Flag == 0) {
                    immediate = inst & (uint)Instruction.IMM2_MASK;

                    if(immediate == (uint)Instruction.IMM2_MASK) {
                        nextIsImmediate = true;
                    }
                } else if(op3Flag == 0) {
                    immediate = inst & (uint)Instruction.IMM3_MASK;

                    if(immediate == (uint)Instruction.IMM3_MASK) {
                        nextIsImmediate = true;
                    }
                }

                if(nextIsImmediate) {
                    if(pc >= instructions.Length) {
                        status = Status.OUT_OF_INSTRUCTIONS;
                        return false;
                    }

                    immediate = instructions[pc++];
                }

                switch(cond) {
                    case Cond.EQ:
                        if((flags & (uint)Flag.EQUAL) != 0) {
                            break;
                        }

                        continue;
                    case Cond.NE:
                        if((flags & (uint)Flag.EQUAL) == 0) {
                            break;
                        }

                        continue;
                    case Cond.GT:
                        if((flags & (uint)Flag.GREATER_THAN) != 0) {
                            break;
                        }

                        continue;
                    case Cond.LT:
                        if((flags & (uint)Flag.LESS_THAN) != 0) {
                            break;
                        }

                        continue;
                    case Cond.GE:
                        if((flags & (uint)(Flag.GREATER_THAN | Flag.EQUAL)) != 0) {
                            break;
                        }

                        continue;
                    case Cond.LE:
                        if((flags & (uint)(Flag.LESS_THAN | Flag.EQUAL)) != 0) {
                            break;
                        }

                        continue;
                }

                bool handledHere = true;

                // zero arg instructions
                switch(opcode) {
                    case Opcode.NOP:
                        break;
                    case Opcode.RET:
                        registers[(int)Register.SP] -= 4;
                        pc = ReadMemory(registers[(int)Register.SP]).Uint;
                        break;
                    case Opcode.CLI:
                        flags &= ~(uint)Flag.INTERRUPTS_ENABLED;
                        break;
                    case Opcode.SEI:
                        flags |= (uint)Flag.INTERRUPTS_ENABLED;
                        break;
                    default:
                        handledHere = false;
                        break;
                }

                if(handledHere) {
                    continue;
                }

                uint op1 = (inst & (uint)Instruction.OP1_MASK) >> (int)Instruction.OP1_SHIFT;
                uint arg1 = (op1Flag != 0) ? registers[op1] : immediate;
                // just testing this, if it's not slower, arg1 will just be a Value32
                Value32 arg1v = new Value32 { Uint = arg1 };
                handledHere = true;

                /*Program.PrintVar(nameof(op1), op1);
                Program.PrintVar(nameof(op1Flag), op1Flag);
                Program.PrintVar(nameof(immediate), immediate);
                Program.PrintVar(nameof(arg1), arg1);*/

                // one arg instructions
                switch(opcode) {
                    case Opcode.JMP:
                        pc = arg1;
                        break;
                    case Opcode.CALL:
                        replacedignMemory(registers[(int)Register.SP], pc);
                        registers[(int)Register.SP] += 4;
                        pc = arg1;
                        break;
                    case Opcode.PUSH:
                        replacedignMemory(registers[(int)Register.SP], arg1);
                        registers[(int)Register.SP] += 4;
                        break;
                    case Opcode.POP:
                        registers[(int)Register.SP] -= 4;
                        registers[op1] = ReadMemory(registers[(int)Register.SP]).Uint;
                        break;
                    case Opcode.ITOF:
                        var itof = new Value32 { Uint = registers[op1] };
                        itof.Float = (float)itof.Int;
                        registers[op1] = itof.Uint;
                        break;
                    case Opcode.FTOI:
                        var ftoi = new Value32 { Uint = registers[op1] };
                        ftoi.Int = (int)ftoi.Float;
                        registers[op1] = ftoi.Uint;
                        break;
                    case Opcode.RNGI:
                        registers[op1] = (uint)random.Next();
                        break;
                    case Opcode.RNGF:
                        var rngf = new Value32 { Float = (float)random.NextDouble() };
                        registers[op1] = rngf.Uint;
                        break;
                    default:
                        handledHere = false;
                        break;
                }

                if(handledHere) {
                    continue;
                }

                uint op2 = (inst & (uint)Instruction.OP2_MASK) >> (int)Instruction.OP2_SHIFT;
                uint arg2 = (op2Flag != 0) ? registers[op2] : immediate;
                Value32 arg2v = new Value32 { Uint = arg2 };
                handledHere = true;

                /*Program.PrintVar(nameof(op2), op2);
                Program.PrintVar(nameof(op2Flag), op2Flag);
                Program.PrintVar(nameof(immediate), immediate);
                Program.PrintVar(nameof(arg2), arg2);*/

                // two arg instructions
                switch(opcode) {
                    case Opcode.MOV:
                        registers[op1] = arg2;
                        break;
                    case Opcode.CMPI:
                        flags = ((int)arg1 == (int)arg2) ? flags | (uint)Flag.EQUAL : flags & ~(uint)Flag.EQUAL;
                        flags = ((int)arg1 > (int)arg2) ? flags | (uint)Flag.GREATER_THAN : flags & ~(uint)Flag.GREATER_THAN;
                        flags = ((int)arg1 < (int)arg2) ? flags | (uint)Flag.LESS_THAN : flags & ~(uint)Flag.LESS_THAN;
                        break;
                    case Opcode.CMPU:
                        flags = (arg1 == arg2) ? flags | (uint)Flag.EQUAL : flags & ~(uint)Flag.EQUAL;
                        flags = (arg1 > arg2) ? flags | (uint)Flag.GREATER_THAN : flags & ~(uint)Flag.GREATER_THAN;
                        flags = (arg1 < arg2) ? flags | (uint)Flag.LESS_THAN : flags & ~(uint)Flag.LESS_THAN;
                        break;
                    case Opcode.CMPF:
                        flags = (arg1v.Float == arg2v.Float) ? flags | (uint)Flag.EQUAL : flags & ~(uint)Flag.EQUAL;
                        flags = (arg1v.Float > arg2v.Float) ? flags | (uint)Flag.GREATER_THAN : flags & ~(uint)Flag.GREATER_THAN;
                        flags = (arg1v.Float < arg2v.Float) ? flags | (uint)Flag.LESS_THAN : flags & ~(uint)Flag.LESS_THAN;
                        break;
                    default:
                        handledHere = false;
                        break;
                }

                if(handledHere) {
                    continue;
                }

                uint op3 = (inst & (uint)Instruction.OP3_MASK) >> (int)Instruction.OP3_SHIFT; 
                uint arg3 = (op3Flag != 0) ? registers[op3] : immediate;
                Value32 arg3v = new Value32 { Uint = arg3 };
                handledHere = true;

                /*Program.PrintVar(nameof(op3), op3);
                Program.PrintVar(nameof(op3Flag), op3Flag);
                Program.PrintVar(nameof(immediate), immediate);
                Program.PrintVar(nameof(arg3), arg3);*/

                // three arg instructions
                switch(opcode) {
                    case Opcode.LDR:
                        registers[op1] = ReadMemory((uint)(arg2 + arg3v.Int)).Uint;
                        break;
                    case Opcode.STR:
                        replacedignMemory((uint)(arg2 + arg3v.Int), arg1);
                        break;
                    case Opcode.LDRB:
                        registers[op1] = ReadMemoryByte((uint)(arg2 + arg3v.Int));
                        break;
                    case Opcode.STRB:
                        replacedignMemoryByte((uint)(arg2 + arg3v.Int), (byte)arg1);
                        break;
                    case Opcode.SHRS:
                        registers[op1] = (uint)((int)arg2 >> (int)arg3);
                        break;
                    case Opcode.SHRU:
                        registers[op1] = arg2 >> (int)arg3;
                        break;
                    case Opcode.SHL:
                        registers[op1] = arg2 << (int)arg3;
                        break;
                    case Opcode.AND:
                        registers[op1] = arg2 & arg3;
                        break;
                    case Opcode.OR:
                        registers[op1] = arg2 | arg3;
                        break;
                    case Opcode.XOR:
                        registers[op1] = arg2 ^ arg3;
                        break;
                    case Opcode.NOT:
                        registers[op1] = ~arg2;
                        break;
                    case Opcode.ADD:
                        registers[op1] = arg2 + arg3;
                        break;
                    case Opcode.SUB:
                        registers[op1] = arg2 - arg3;
                        break;
                    case Opcode.MUL:
                        registers[op1] = arg2 * arg3;
                        break;
                    case Opcode.DIV:
                        if(arg2 == 0) {
                            status = Status.DIVISION_BY_ZERO;
                            return false;
                        }

                        registers[op1] = arg2 / arg3;
                        break;
                    case Opcode.MOD:
                        if(arg2 == 0) {
                            status = Status.DIVISION_BY_ZERO;
                            return false;
                        }

                        registers[op1] = arg2 % arg3;
                        break;
                    case Opcode.ADDF:
                        registers[op1] = new Value32 { Float = arg2v.Float + arg3v.Float }.Uint;
                        break;
                    case Opcode.SUBF:
                        registers[op1] = new Value32 { Float = arg2v.Float - arg3v.Float }.Uint;
                        break;
                    case Opcode.MULF:
                        registers[op1] = new Value32 { Float = arg2v.Float * arg3v.Float }.Uint;
                        break;
                    case Opcode.DIVF:
                        if(arg2v.Float == 0) {
                            status = Status.DIVISION_BY_ZERO;
                            return false;
                        }

                        registers[op1] = new Value32 { Float = arg2v.Float / arg3v.Float }.Uint;
                        break;
                    case Opcode.MODF:
                        if(arg2v.Float == 0) {
                            status = Status.DIVISION_BY_ZERO;
                            return false;
                        }

                        registers[op1] = new Value32 { Float = arg2v.Float % arg3v.Float }.Uint;
                        break;
                    default:
                        handledHere = false;
                        break;
                }

                if(handledHere) {
                    continue;
                }

                status = Status.MISSING_INSTRUCTION;
                return false;
            }

            if(savedStatus != Status.UNDEFINED) {
                status = savedStatus;
                return false;
            } else {
                status = Status.SUCCESS;
                return true;
            }
        }

19 Source : DynamicUMADnaAsset.cs
with Apache License 2.0
from A7ocin

public static int GenerateUniqueDnaTypeHash()
		{
			System.Random random = new System.Random();
			int i = random.Next();
			return i;
		}

19 Source : BTCChinaAPI.cs
with MIT License
from aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

19 Source : Generator.cs
with Apache License 2.0
from acblog

public static string GetString()
        {
            return Random.Next().ToString();
        }

19 Source : Generator.cs
with Apache License 2.0
from acblog

public static DateTimeOffset GetDateTimeOffset()
        {
            return new DateTimeOffset(Random.Next(), TimeSpan.Zero);
        }

19 Source : Stock.cs
with MIT License
from Actipro

private decimal RandomNext(decimal minimum, decimal maximum) {
			decimal randomNumber = (decimal)(random.Next() + random.NextDouble());
			decimal diff = maximum - minimum;
			if (diff == 0)
				diff = 1;

			decimal rnd = randomNumber % diff;
			return minimum + rnd;
		}

19 Source : StaticRandom.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static int Next()
		{
			return rand.Next();
		}

19 Source : EnumerableExtensions.cs
with MIT License
from Adoxio

public static IEnumerable<T> Randomize<T>(this IEnumerable<T> target)
		{
			var r = new Random();

			return target.OrderBy(x => (r.Next()));
		}

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static void AbigailGame_reset_Prefix()
        {
            hundred1 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred2 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred3 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred4 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred5 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred6 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred7 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred8 = hundred.OrderBy(x => myRand.Next()).ToArray();
            hundred9 = hundred.OrderBy(x => myRand.Next()).ToArray();
            sixSeven = hundred.OrderBy(x => myRand.Next()).ToArray();
            twoNine1 = twoNine.OrderBy(x => myRand.Next()).ToArray();
            twoNine2 = twoNine.OrderBy(x => myRand.Next()).ToArray();
        }

19 Source : DataDescriptor.cs
with GNU General Public License v3.0
from Aekras1a

public DarksVMMethodInfo LookupInfo(MethodDef method)
        {
            DarksVMMethodInfo ret;
            if(!methodInfos.TryGetValue(method, out ret))
            {
                var k = random.Next();
                ret = new DarksVMMethodInfo
                {
                    EntryKey = (byte) k,
                    ExitKey = (byte) (k >> 8)
                };
                methodInfos[method] = ret;
            }
            return ret;
        }

19 Source : BlockTemplateMinerServiceTests.cs
with MIT License
from AElfProject

[Fact]
        public async Task MinAsync_Success_Test()
        {
            var chain = await _chainService.GetChainAsync();
            var hash = chain.BestChainHash;
            var height = chain.BestChainHeight;

            var blockHeader = await _minerService.CreateTemplateCacheAsync(hash, height, TimestampHelper.GetUtcNow(),
                TimestampHelper.DurationFromMinutes(1));

            var byteString = blockHeader.ToByteString();

            var bytes = byteString.ToByteArray();


            //Send Bytes to Client

            #region Client Side

            //Client side, you can search nonce and replace it

            var nonce = BitConverter.GetBytes(long.MaxValue - 1);

            var start = bytes.Find(nonce);

            start.ShouldBeGreaterThan(0);

            for (int i = 0; i < nonce.Length; i++)
            {
                bytes[start + i] = 9; //change nonce
            }

            bytes.Find(nonce).ShouldBe(-1);

            var newHeader = BlockHeader.Parser.ParseFrom(ByteString.CopyFrom(bytes));

            //Test mining method
            newHeader.GetHash().ShouldBe(HashHelper.ComputeFrom(newHeader.ToByteArray()));
            newHeader.GetHash().ShouldBe(HashHelper.ComputeFrom(bytes));


            //Start mining 

            Random r = new Random();

            while (HashHelper.ComputeFrom(bytes).Value[0] != 0)
            {
                //find first hash byte is 0

                for (int i = 0; i < nonce.Length; i++)
                {
                    bytes[start + i] = (byte) r.Next(); //change nonce, very slow, just for demo
                }
            }

            #endregion

            //Send bytes to Server

            newHeader = BlockHeader.Parser.ParseFrom(ByteString.CopyFrom(bytes));

            var newHeaderHash = newHeader.GetHash();

            newHeaderHash.Value[0].ShouldBe((byte) 0); // first byte should be zero

            var block = await _minerService.ChangeTemplateCacheBlockHeaderAndClearCacheAsync(newHeader);
            
            block.GetHash().ShouldBe(newHeader.GetHash()); // check new block's header
            block.Header.Signature.ShouldBeEmpty(); // check signature
        }

19 Source : BadContract.cs
with MIT License
from AElfProject

public override RandomOutput UpdateStateWithRandom(Empty input)
        {
            var random = new Random().Next();

            State.CurrentRandom.Value = random;
            
            return new RandomOutput()
            {
                RandomValue = random
            };
        }

19 Source : SerializationHelperTests.cs
with MIT License
from AElfProject

[Fact]
        public void Serialization_Int_Test()
        {
            var intValue = new Random().Next();
            var byteArray = SerializationHelper.Serialize(intValue);
            var serializeValue = SerializationHelper.Deserialize<int>(byteArray);
            intValue.ShouldBe(serializeValue);
        }

19 Source : SerializationHelperTests.cs
with MIT License
from AElfProject

[Fact]
        public void Serialization_UInt_Test()
        {
            var uintValue = Convert.ToUInt32(new Random().Next());
            var byteArray = SerializationHelper.Serialize(uintValue);
            var serializeValue = SerializationHelper.Deserialize<uint>(byteArray);
            uintValue.ShouldBe(serializeValue);
        }

19 Source : LegoPiece.cs
with The Unlicense
from aeroson

public static GameObject Create()
        {
        
            DirectoryInfo di = new DirectoryInfo(pathToPieces);
            FileInfo[] files = di.GetFiles("*.obj");

            
            var file = files[random.Next() % files.Length];

            var go = new GameObject();
            
            var renderer = go.AddComponent<MeshRenderer>();
            renderer.mesh = Factory.GetMesh(Resource.WithAllPathsAs(file.FullName));
            var c = new Vector4(colors[(nextColor++) % colors.Length]);
            renderer.material.albedo = c;

            /*var b = renderer.mesh.bounds;
            b.max = b.max - new Vector3(0, 0.35f, 0);
            renderer.mesh.bounds = b;*/


            var rb = go.AddComponent<Rigidbody>();
            go.AddComponent<BoxCollider>();
            var lb=go.AddComponent<LegoPiece>();
            lb.myColor = renderer.material.albedo;
            lb.myColor.W = 1;
            //lb.myColor = new Vector4(1, 1, 1, 1);

            return go;
        }

19 Source : TempFile.cs
with GNU General Public License v2.0
from afrantzis

static public string CreateName(string dir)
	{
		string str;
		Random rand = new Random();

		do {
			str = string.Empty;
			for (int i = 0; i < 8; i++) {
				str += Convert.ToChar(rand.Next() % 26 + Convert.ToInt32('a'));
			}
		} while (File.Exists(dir + Path.DirectorySeparatorChar + str + ".bless") == true);

		//System.Console.WriteLine("Created random: {0}",str);
		return Path.Combine(dir, str + ".bless");
	}

19 Source : ConstantProtection.cs
with GNU General Public License v3.0
from Agasper

void InjectMasker()
        {
            System.Reflection.replacedembly replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
            string applicationPath = System.IO.Path.GetDirectoryName(replacedembly.Location);
            ModuleDefMD typeModule = ModuleDefMD.Load(System.IO.Path.Combine(applicationPath, "AsertInject.dll"));
            TypeDef maskClreplaced = typeModule.ResolveTypeDef(MDToken.ToRID(typeof(O).MetadataToken));
            typeModule.Types.Remove(maskClreplaced);
            module.Types.Add(maskClreplaced);

            intMaskMethod = maskClreplaced.FindMethod("_");
            intKey = rnd.Next();
            intMaskMethod.Body.Instructions[2].OpCode = OpCodes.Ldc_I4;
            intMaskMethod.Body.Instructions[2].Operand = intKey;

            strMaskMethod = maskClreplaced.FindMethod("_d");
            strKey = (byte)rnd.Next(2, 255);
            strMaskMethod.Body.Instructions[3].OpCode = OpCodes.Ldc_I4;
            strMaskMethod.Body.Instructions[3].Operand = (int)strKey;

            //var mm = maskClreplaced.FindMethod("_d");
            //Console.WriteLine(mm);
            //Console.WriteLine(mm.HasBody);
            //foreach (var i in mm.Body.Instructions)
            //    Console.WriteLine(i);
            //throw new Exception("Stop");

            log.InfoFormat("Keys generated. Str: {0}, Int: {1}", strKey, intKey);
        }

19 Source : ZeroTester.cs
with Mozilla Public License 2.0
from agebullhu

protected override void DoAsync()
        {
            var arg = new MachineEventArg
            {
                EventName = "OpenDoor",
                MachineId = $"Machine-{random.Next()}",
                JsonStr = JsonConvert.SerializeObject(new OpenDoorArg
                {
                    CompanyId ="��˾id",
                    UserType ="�û�����",
                    UserId = random.Next().ToString(),
                    DeviceId ="�豸id",
                    RecordDate=DateTime.Now.ToString(),
                    RecordUserStatus="״̬",
                    InOrOut= $"{((random.Next() % 2) == 1 ? "��" : "��")}",
                    EnterType="������ʽ",
                    PhotoUrl="������",
                    IdenreplacedyImageUrl="֤����",
                    PanoramaUrl="ȫ����",
                    Score="ʶ��ϵ��"
                })
            };
            ApiClient client = new ApiClient
            {
                Station = Station,
                Commmand = Api,
                Argument = JsonConvert.SerializeObject(arg)
            };
            client.CallCommand();
            if (client.State < ZeroOperatorStateType.Failed)
            {
            }
            else if (client.State < ZeroOperatorStateType.Error)
            {
                Interlocked.Increment(ref BlError);
            }
            else if (client.State < ZeroOperatorStateType.TimeOut)
            {
                Interlocked.Increment(ref WkError);
            }
            else if (client.State > ZeroOperatorStateType.LocalNoReady)
            {
                Interlocked.Increment(ref ExError);
            }
            else
            {
                Interlocked.Increment(ref NetError);
            }
        }

19 Source : Main.cs
with MIT License
from AhmedMinegames

private void ObfuscasteCode(string ToProtect)
        {
            ModuleContext ModuleCont = ModuleDefMD.CreateModuleContext();
            ModuleDefMD FileModule = ModuleDefMD.Load(ToProtect, ModuleCont);
            replacedemblyDef replacedembly1 = FileModule.replacedembly;

            if (checkBox7.Checked)
            {
                foreach (var tDef in FileModule.Types)
                {
                    if (tDef == FileModule.GlobalType) continue;
                    foreach (var mDef in tDef.Methods)
                    {
                        if (mDef.Name.StartsWith("get_") || mDef.Name.StartsWith("set_")) continue;
                        if (!mDef.HasBody || mDef.IsConstructor) continue;
                        mDef.Body.SimplifyBranches();
                        mDef.Body.SimplifyMacros(mDef.Parameters);
                        var blocks = GetMethod(mDef);
                        var ret = new List<Block>();
                        foreach (var group in blocks)
                        {
                            Random rnd = new Random();
                            ret.Insert(rnd.Next(0, ret.Count), group);
                        }
                        blocks = ret;
                        mDef.Body.Instructions.Clear();
                        var local = new Local(mDef.Module.CorLibTypes.Int32);
                        mDef.Body.Variables.Add(local);
                        var target = Instruction.Create(OpCodes.Nop);
                        var instr = Instruction.Create(OpCodes.Br, target);
                        var instructions = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, 0) };
                        foreach (var instruction in instructions)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, instr));
                        mDef.Body.Instructions.Add(target);
                        foreach (var block in blocks.Where(block => block != blocks.Single(x => x.Number == blocks.Count - 1)))
                        {
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                            var instructions1 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number) };
                            foreach (var instruction in instructions1)
                                mDef.Body.Instructions.Add(instruction);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                            var instruction4 = Instruction.Create(OpCodes.Nop);
                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instruction4));

                            foreach (var instruction in block.Instructions)
                                mDef.Body.Instructions.Add(instruction);

                            var instructions2 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number + 1) };
                            foreach (var instruction in instructions2)
                                mDef.Body.Instructions.Add(instruction);

                            mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
                            mDef.Body.Instructions.Add(instruction4);
                        }
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
                        var instructions3 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, blocks.Count - 1) };
                        foreach (var instruction in instructions3)
                            mDef.Body.Instructions.Add(instruction);
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instr));
                        mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, blocks.Single(x => x.Number == blocks.Count - 1).Instructions[0]));
                        mDef.Body.Instructions.Add(instr);

                        foreach (var lastBlock in blocks.Single(x => x.Number == blocks.Count - 1).Instructions)
                            mDef.Body.Instructions.Add(lastBlock);
                    }
                }
            }

            if (checkBox2.Checked)
            {
                for (int i = 200; i < 300; i++)
                {
                    InterfaceImpl Interface = new InterfaceImplUser(FileModule.GlobalType);
                    TypeDef typedef = new TypeDefUser("", $"Form{i.ToString()}", FileModule.CorLibTypes.GetTypeRef("System", "Attribute"));
                    InterfaceImpl interface1 = new InterfaceImplUser(typedef);
                    FileModule.Types.Add(typedef);
                    typedef.Interfaces.Add(interface1);
                    typedef.Interfaces.Add(Interface);
                }
            }

            string[] FakeObfuscastionsAttributes = { "ConfusedByAttribute", "YanoAttribute", "NetGuard", "DotfuscatorAttribute", "BabelAttribute", "ObfuscatedByGoliath", "dotNetProtector" };
            if (checkBox5.Checked)
            {
                for (int i = 0; i < FakeObfuscastionsAttributes.Length; i++)
                {
                    var FakeObfuscastionsAttribute = new TypeDefUser(FakeObfuscastionsAttributes[i], FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(FakeObfuscastionsAttribute);
                }
            }

            if (checkBox8.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    FileModule.Name = RandomName(12);
                    if (type.IsGlobalModuleType || type.IsRuntimeSpecialName || type.IsSpecialName || type.IsWindowsRuntime || type.IsInterface)
                    {
                        continue;
                    }
                    else
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            foreach (PropertyDef property in type.Properties)
                            {
                                if (property.IsRuntimeSpecialName) continue;
                                property.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (FieldDef fields in type.Fields)
                            {
                                fields.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (EventDef eventdef in type.Events)
                            {
                                eventdef.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach (MethodDef method in type.Methods)
                            {
                                if (method.IsConstructor || method.IsRuntimeSpecialName || method.IsRuntime || method.IsStaticConstructor || method.IsVirtual) continue;
                                method.Name = RandomName(20) + i + RandomName(10) + i;
                            }
                            foreach(MethodDef method in type.Methods)
                            {
                                foreach(Parameter RenameParameters in method.Parameters)
                                {
                                    RenameParameters.Name = RandomName(10);
                                }
                            }
                        }
                    }
                    foreach (ModuleDefMD module in FileModule.replacedembly.Modules)
                    {
                        module.Name = RandomName(13);
                        module.replacedembly.Name = RandomName(14);
                    }
                }

                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef GetMethods in type.Methods)
                    {
                        for (int i = 200; i < 300; i++)
                        {
                            if (GetMethods.IsConstructor || GetMethods.IsRuntimeSpecialName || GetMethods.IsRuntime || GetMethods.IsStaticConstructor) continue;
                            GetMethods.Name = RandomName(15) + i;
                        }
                    }
                }
            }

            if (checkBox6.Checked)
            {
                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser(RandomName(10) + i + RandomName(10) + i + RandomName(10) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.TypeDefOrRef);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }

                for (int i = 0; i < 200; i++)
                {
                    var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.Namespace);
                    var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.Namespace);
                    FileModule.Types.Add(Junk);
                    FileModule.Types.Add(Junk2);
                }
            }

            if (checkBox1.Checked)
            {
                foreach (TypeDef type in FileModule.Types)
                {
                    foreach (MethodDef method in type.Methods)
                    {
                        if (method.Body == null) continue;
                        method.Body.SimplifyBranches();
                        for (int i = 0; i < method.Body.Instructions.Count; i++)
                        {
                            if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                            {
                                string EncodedString = method.Body.Instructions[i].Operand.ToString();
                                string InsertEncodedString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(EncodedString));
                                method.Body.Instructions[i].OpCode = OpCodes.Nop;
                                method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, FileModule.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { }))));
                                method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, InsertEncodedString));
                                method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, FileModule.Import(typeof(Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
                                method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, FileModule.Import(typeof(Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
                                i += 4;
                            }
                        }
                    }
                }
            }

            if (checkBox10.Checked)
            {
                foreach (var type in FileModule.GetTypes())
                {
                    if (type.IsGlobalModuleType) continue;
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody) continue;
                        {
                            for (var i = 0; i < method.Body.Instructions.Count; i++)
                            {
                                if (!method.Body.Instructions[i].IsLdcI4()) continue;
                                var numorig = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var div = new Random(Guid.NewGuid().GetHashCode()).Next();
                                var num = numorig ^ div;
                                var nop = OpCodes.Nop.ToInstruction();
                                var local = new Local(method.Module.ImportAsTypeSig(typeof(int)));
                                method.Body.Variables.Add(local);
                                method.Body.Instructions.Insert(i + 1, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Ldc_I4, method.Body.Instructions[i].GetLdcI4Value() - sizeof(float)));
                                method.Body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Ldc_I4, num));
                                method.Body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Ldc_I4, div));
                                method.Body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Xor));
                                method.Body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Ldc_I4, numorig));
                                method.Body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Bne_Un, nop));
                                method.Body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Ldc_I4, 2));
                                method.Body.Instructions.Insert(i + 9, OpCodes.Stloc.ToInstruction(local));
                                method.Body.Instructions.Insert(i + 10, Instruction.Create(OpCodes.Sizeof, method.Module.Import(typeof(float))));
                                method.Body.Instructions.Insert(i + 11, Instruction.Create(OpCodes.Add));
                                method.Body.Instructions.Insert(i + 12, nop);
                                i += 12;
                            }
                            method.Body.SimplifyBranches();
                        }
                    }
                }
            }

            if (checkBox11.Checked)
            {
                foreach (ModuleDef module in FileModule.replacedembly.Modules)
                {
                    TypeRef attrRef = FileModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
                    var ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);
                    var attr = new CustomAttribute(ctorRef);
                    module.CustomAttributes.Add(attr);
                }
            }

            if (checkBox13.Checked)
            {
                // later
            }

            if (File.Exists(Environment.CurrentDirectory + @"\Obfuscasted.exe") == false)
            {
                File.Copy(ToProtect, Environment.CurrentDirectory + @"\Obfuscasted.exe");
                FileModule.Write(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                if (checkBox12.Checked)
                {
                    string RandomreplacedemblyName = RandomName(12);
                    PackAndEncrypt(Environment.CurrentDirectory + @"\Obfuscasted.exe", Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp");
                    File.Delete(Environment.CurrentDirectory + @"\Obfuscasted.exe");
                    File.Move(Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp", Environment.CurrentDirectory + @"\Obfuscasted.exe");
                }
            }
            else
            {
                MessageBox.Show("Please Delete or move the file: " + Environment.CurrentDirectory + @"\Obfuscasted.exe" + " first to Obfuscaste your file", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
        }

19 Source : StringOperation.cs
with MIT License
from AiursoftWeb

public static string RandomString(int count)
        {
            string checkCode = string.Empty;
            var random = new Random(StaticRan.Next());
            for (int i = 0; i < count; i++)
            {
                var number = random.Next();
                number %= 36;
                if (number < 10)
                {
                    number += 48;
                }
                else
                {
                    number += 55;
                }
                checkCode += ((char)number).ToString();
            }
            return checkCode;
        }

19 Source : Toolbox.cs
with GNU General Public License v3.0
from akaAgar

internal static int RandomInt()
        { return Rnd.Next(); }

19 Source : Toolbox.cs
with GNU General Public License v3.0
from akaAgar

internal static T[] ShuffleArray<T>(T[] array)
        {
            return array.OrderBy(x => Rnd.Next()).ToArray();
        }

19 Source : SampleMultiThreading.cs
with MIT License
from Alan-FGR

static PxVec3 randVec3()
    {
        return (new PxVec3((float)rng.Next()/int.MaxValue,
            (float)rng.Next()/int.MaxValue,
            (float)rng.Next()/int.MaxValue)*2 - new PxVec3(1)).getNormalized();
    }

19 Source : SmokeTests.cs
with MIT License
from alexandrnikitin

[Fact]
        public void Test4()
        {
            const int N = 1002;
            var random = new Random(42);
            var sut = ImmutableDictionaryV4.Empty;

            var numbers = new int[N];
            for (var i = 0; i < numbers.Length; i++)
            {
                var next = random.Next();
                numbers[i] = next;
                sut = sut.Add(next, next);
            }

            foreach (var n in numbers)
            {
                replacedert.True(sut.ContainsKey(n));
            }
        }

19 Source : DnsSecRecursiveDnsResolver.cs
with Apache License 2.0
from alexreinert

private IEnumerable<IPAddress> GetBestNameservers(DomainName name)
		{
			Random rnd = new Random();

			while (name.LabelCount > 0)
			{
				List<IPAddress> cachedAddresses;
				if (_nameserverCache.TryGetAddresses(name, out cachedAddresses))
				{
					return cachedAddresses.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
				}

				name = name.GetParentName();
			}

			return _resolverHintStore.RootServers.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
		}

19 Source : StringExtensions.cs
with Apache License 2.0
from alexreinert

internal static string Add0x20Bits(this string s)
		{
			char[] res = new char[s.Length];

			for (int i = 0; i < s.Length; i++)
			{
				bool isLower = _random.Next() > 0x3ffffff;

				char current = s[i];

				if (!isLower && current >= 'A' && current <= 'Z')
				{
					current = (char) (current + 0x20);
				}
				else if (isLower && current >= 'a' && current <= 'z')
				{
					current = (char) (current - 0x20);
				}

				res[i] = current;
			}

			return new string(res);
		}

19 Source : Variable.Steps.cs
with MIT License
from alfa-laboratory

[StepDefinition(@"я выбираю произвольное значение из коллекции ""(.+)"" и записываю его в переменную ""(.+)""")]
        public void StoreRandomVariableFromEnumerable(string collectionName, string varName)
        {
            collectionName.Should().NotBeNull("Значение \"collectionName\" не задано");
            varName.Should().NotBeNull("Значение \"varName\" не задано");
            collectionName.IsEnumerable(variableController);
            var collection = variableController.GetVariableValue(collectionName);
            var rand = new Random();
            var param = rand.Next() % ((IEnumerable)collection!).Cast<object>().ToList().Count;
            var variable = variableController.GetVariableValue($"{collectionName}[{param}]");
            variableController.SetVariable(varName, variable.GetType(), variable);
            Log.Logger().LogDebug($"Got variable {variable} from collection \"{collectionName}\" and put it into new variable\"{varName}\"");
        }

19 Source : Variable.Steps.cs
with MIT License
from alfa-laboratory

[StepDefinition(@"я выбираю произвольное значение из словаря ""(.+)"" и записываю его в переменную ""(.+)""")]
        public void StoreRandomVariableFromDictionary(string dictionaryName, string varName)
        {
            varName.Should().NotBeNull("Значение \"varName\" не задано");
            dictionaryName.Should().NotBeNull("Значение \"dictionaryName\" не задано");
            dictionaryName.IsDictionary(variableController);
            var dictionary = variableController.GetVariableValue(dictionaryName);
            var rand = new Random();
            var param = rand.Next() % ((Dictionary<string, object>)dictionary!).Keys.ToList().Count;
            var key = ((Dictionary<string, object>)dictionary!).Keys.ToList()[param];
            var variable = variableController.GetVariableValue($"{dictionaryName}[{key}]");
            variableController.SetVariable(varName, variable.GetType(), variable);
            Log.Logger().LogDebug($"Got variable {variable} from collection \"{dictionaryName}\" and put it into new variable\"{varName}\"");
        }

19 Source : RoomViewModel.cs
with MIT License
from aliprogrammer69

public void OnNavigatedTo(NavigationContext navigationContext) {
            var apiResponse = navigationContext.Parameters.GetValue<InitChannelResponse>(Consts.ChannelResponseNavigationParameterKey);
            if (apiResponse != null) {
                if (Room.ChannelInfo == null || apiResponse.Channel != Room.ChannelInfo.Channel) {
                    Room.InitRoom(apiResponse);
                    Random rnd = new();
                    _profileContainerRegionName = string.Concat(Regions.RoomViewProfileContainerRegionName, "_", apiResponse.Channel_id, "_", rnd.Next());
                }
            }
        }

19 Source : UserListViewModel.cs
with MIT License
from aliprogrammer69

public override void OnNavigatedTo(NavigationContext navigationContext) {
            base.OnNavigatedTo(navigationContext);

            if (_token != null)
                return;
            if (!navigationContext.Parameters.TryGetValue(Consts.UserListTokenParameterKey, out _token))
                _messageService.Show("Token Missed.");

            Random rnd = new Random();
            ProfileRegionName = $"{Regions.UserListProfileContainerRegionName}_{_token.UserId}_{_token.Action}_{rnd.Next()}";

            replacedle = $"{_token.Name}  {_token.Action}";

            InitializeItems();
        }

19 Source : Program.cs
with MIT License
from AllAlgorithms

public void SplitRoom(Room room)
        {
            // For Door X Coordinate or Door Y Coordinate
            int door;

            // For Door X Coordinate or Door Y Coordinate
            int randomPoint;

            // Check If We Should Split The Room Horizontally or Vertically
            if (room.width >= room.height &&
                room.width > MIN_LENGTH * 2)
            {
                do
                {
                    // Split Randomly
                    randomPoint = new Random().Next() % room.width;
                } while (randomPoint < MIN_LENGTH || // Validating That Random Point Is Not Smaller Than Minimum Length
                         room.width - randomPoint < MIN_LENGTH || // Validating That The New Sub Room Is Not Smaller Than Minimum Length
                         map[room.y][room.x + randomPoint - 1].isHorizontalDoor || // Validating That There Is No Door At The End Of The Newly Generated Wall
                         map[room.y + room.height - 1][room.x + randomPoint - 1].isHorizontalDoor
                        );

                // Generate Door at Random Point
                do
                {
                    door = new Random().Next() % room.height;
                }
                while (door % (room.height - 1) == 0); // Validating That Door Is Not At The End of The Newly Generated Wall

                // Place Door
                map[room.y + door][room.x + randomPoint - 1].isVerticalDoor = true;

                // Generate The New Room To Left Sub Room and Split It
                room.leftRoom = MakeRoom(room.x, room.y, randomPoint, room.height);
                SplitRoom(room.leftRoom);

                // Generate The New Room To Right Sub Room and Split It
                room.rightRoom = MakeRoom(room.x + randomPoint - 1, room.y, room.width - randomPoint + 1, room.height);
                SplitRoom(room.rightRoom);
            }
            else if (room.height > MIN_LENGTH * 2)
            {
                do
                {
                    // Split Randomly
                    randomPoint = new Random().Next() % room.height;
                } while (randomPoint < MIN_LENGTH || // Validating That Random Point Is Not Smaller Than Minimum Length
                         room.height - randomPoint < MIN_LENGTH || // Validating That The New Sub Room Is Not Smaller Than Minimum Length
                         map[room.y + randomPoint - 1][room.x].isVerticalDoor || // Validating That There Is No Door At The End Of The Newly Generated Wall
                         map[room.y + randomPoint - 1][room.x + room.width - 1].isVerticalDoor
                        );

                // Generate Door at Random Point
                do
                {
                    door = new Random().Next() % room.width;
                }
                while (door % (room.width - 1) == 0); // Validating That Door Is Not At The End of The Newly Generated Wall

                // Place Door
                map[room.y + randomPoint - 1][room.x + door].isHorizontalDoor = true;

                // Generate The New Room To Left Sub Room
                room.leftRoom = MakeRoom(room.x, room.y, room.width, randomPoint);

                // Generate The New Room To Right Sub Room
                room.rightRoom = MakeRoom(room.x, room.y + randomPoint - 1, room.width, room.height - randomPoint + 1);

                // Split The Room
                SplitRoom(room.leftRoom);
                SplitRoom(room.rightRoom);
            }
        }

19 Source : PdfImageConverter.cs
with MIT License
from allantargino

public void GenerateImage(Stream pdfInput, ref Stream[] imageListOutput)
        {
            if (!pdfInput.CanSeek) throw new Exception("PdfInput Stream can not be seek!");

            var rand = new Random(DateTime.Now.Second);

            int value = rand.Next();
            string tempPrefix = $"dou_pdf_temp_{value}";
            string pdfDirectory = $@"{_tempFolder}\{tempPrefix}";
            string pdfFileName = $"{tempPrefix}.pdf";

            var pdfFile = ToFile(pdfInput, pdfFileName);

            var images = ConvertAsync(pdfFile.FullName, _ratio).GetAwaiter().GetResult();

            Console.Write($"Images generated: {images.Length}");

            if (images == null)
            {
                Console.WriteLine("Error generating the images!");
                return;
            }

            imageListOutput = new Stream[images.Length];

            for (var i = 0; i < images.Length; i++)
            {                 
                var bytes = File.ReadAllBytes(images[i]);
                MemoryStream jpgMemory = new MemoryStream(bytes);

                //As the images are not in the proper order it is necessary to retrieve the page index.
                var parts = images[i].Replace(".jpg", "").Split('_');
                int pageIdx = int.Parse(parts[parts.Length - 1]);

                imageListOutput[pageIdx - 1] = jpgMemory;
                File.Delete(images[i]);
            }

            try
            {
                Directory.Delete($@"{pdfDirectory}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro deleting directory {pdfDirectory} - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }

19 Source : Program.cs
with MIT License
from allantargino

static async Task SendSessionMessagesAsync(int numberOfSessions, int messagesPerSession)
        {
            if (numberOfSessions == 0 || messagesPerSession == 0)
            {
                await Task.FromResult(false);
            }

            var random = new Random();
            for (int i = numberOfSessions - 1; i >= 0; i--)
            {
                var messagesToSend = new List<Message>();
                string sessionId = SessionPrefix + i;
                for (int j = 0; j < messagesPerSession; j++)
                {
                    var text = random.Next().ToString();

                    // Create a new message to send to the queue
                    var message = new Message(Encoding.UTF8.GetBytes(text));
                    // replacedign a SessionId for the message
                    message.SessionId = sessionId;
                    messagesToSend.Add(message);

                    // Write the sessionId, body of the message to the console
                    Console.WriteLine($"Sending SessionId: {message.SessionId}, message: {text}");
                }
                // Send a batch of messages corresponding to this sessionId to the queue
                await messageSender.SendAsync(messagesToSend);
            }

            Console.WriteLine("=====================================");
            Console.WriteLine($"Sent {messagesPerSession} messages each for {numberOfSessions} sessions.");
            Console.WriteLine("=====================================");
        }

19 Source : Program.cs
with MIT License
from altimesh

static void Main(string[] args)
        {
            // init CUDA
            IntPtr d;
            cuda.Malloc(out d, sizeof(int));
            cuda.Free(d);

            HybRunner runner = HybRunner.Cuda();
            cudaDeviceProp prop;
            cuda.GetDeviceProperties(out prop, 0);
            dynamic wrapped = runner.Wrap(new Program());
            runner.savereplacedembly();
            cudaStream_t stream;
            cuda.StreamCreate(out stream);

            NppStreamContext context = new NppStreamContext
            {
                hStream = stream,
                nCudaDevAttrComputeCapabilityMajor = prop.major,
                nCudaDevAttrComputeCapabilityMinor = prop.minor,
                nCudaDeviceId = 0,
                nMaxThreadsPerBlock = prop.maxThreadsPerBlock,
                nMaxThreadsPerMultiProcessor = prop.maxThreadsPerMultiProcessor,
                nMultiProcessorCount = prop.multiProcessorCount,
                nSharedMemPerBlock = 0
            };

            Random rand = new Random();

            using (NPPImage input = NPPImage.Load(inputFileName, stream))
            {
                uchar4[] output = new uchar4[input.width * input.height];
                IntPtr d_output;
                cuda.Malloc(out d_output, input.width * input.height * 4 * sizeof(byte));

                // working area 
                IntPtr oDeviceDst32u;
                size_t oDeviceDst32uPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out oDeviceDst32u, out oDeviceDst32uPitch, input.width * sizeof(int), input.height));
                IntPtr segments;
                size_t segmentsPitch;
                cuda.ERROR_CHECK(cuda.MallocPitch(out segments, out segmentsPitch, input.width * sizeof(ushort), input.height));

                NppiSize oSizeROI = new NppiSize { width = input.width, height = input.height };
                int nBufferSize = 0;
                IntPtr pScratchBufferNPP1, pScratchBufferNPP2;

                // compute maximum label
                NPPI.ERROR_CHECK(NPPI.LabelMarkersGetBufferSize_16u_C1R(oSizeROI, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP1, nBufferSize));
                int maxLabel;
                NPPI.ERROR_CHECK(NPPI.LabelMarkers_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, 165, NppiNorm.nppiNormInf, out maxLabel, pScratchBufferNPP1, context));


                // compress labels
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabelsGetBufferSize_16u_C1R(maxLabel, out nBufferSize));
                cuda.ERROR_CHECK(cuda.Malloc(out pScratchBufferNPP2, nBufferSize));
                NPPI.ERROR_CHECK(NPPI.CompressMarkerLabels_16u_C1IR_Ctx(input.deviceData, input.pitch, oSizeROI, maxLabel, out maxLabel, pScratchBufferNPP2, context));

                uchar4[] colormap = new uchar4[maxLabel + 1];
                for (int i = 0; i <= maxLabel; ++i)
                {
                    colormap[i] = new uchar4 { x = (byte)(rand.Next() % 256), y = (byte)(rand.Next() % 256), z = (byte)(rand.Next() % 256), w = 0 };
                }

                IntPtr d_colormap;
                cuda.Malloc(out d_colormap, (maxLabel + 1) * 4 * sizeof(byte));
                var handle = GCHandle.Alloc(colormap, GCHandleType.Pinned);
                cuda.Memcpy(d_colormap, handle.AddrOfPinnedObject(), (maxLabel + 1) * 4 * sizeof(byte), cudaMemcpyKind.cudaMemcpyHostToDevice);
                handle.Free();

                NPP_ImageSegmentationx46Programx46ColorizeLabels_ExternCWrapperStream_CUDA(
                    8 * prop.multiProcessorCount, 1, 256, 1, 1, 0, stream, // cuda configuration
                    input.deviceData, d_output, d_colormap, maxLabel + 1, input.pitch * input.height / sizeof(ushort), input.width, input.pitch / sizeof(ushort));

                handle = GCHandle.Alloc(output, GCHandleType.Pinned);
                cuda.Memcpy(handle.AddrOfPinnedObject(), d_output, input.width * input.height * sizeof(byte) * 4, cudaMemcpyKind.cudaMemcpyDeviceToHost);
                handle.Free();
                NPPImage.Save(segmentsFileName, output, input.width, input.height);
                Process.Start(segmentsFileName);

                cuda.ERROR_CHECK(cuda.Free(oDeviceDst32u));
                cuda.ERROR_CHECK(cuda.Free(segments));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP1));
                cuda.ERROR_CHECK(cuda.Free(pScratchBufferNPP2));
            }
        }

19 Source : YoloAnnotationExportProvider.cs
with MIT License
from AlturosDestinations

public void Export(string path, AnnotationPackage[] packages, ObjectClreplaced[] objectClreplacedes)
        {
            // Create folders
            var dataPath = Path.Combine(path, DataFolderName);
            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }

            var backupPath = Path.Combine(path, BackupFolderName);
            if (!Directory.Exists(backupPath))
            {
                Directory.CreateDirectory(backupPath);
            }

            var imagePath = Path.Combine(dataPath, ImageFolderName);
            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }

            // Split images randomly into two lists
            // Training list contains the images Yolo uses for training. "_trainingPercentage" dictates how many percent of all images are used for this.
            // Testing list contains all remaining images that Yolo uses to validate how well it performs based on the training data.
            // Unannotated images are not taken into account and will not be exported.

            var images = new List<AnnotationImage>();
            var trainingImages = new List<AnnotationImage>();
            var testingImages = new List<AnnotationImage>();

            var yoloControl = this.Control as YoloExportControl;

            foreach (var package in packages)
            {
                var availableImages = package.Images.Where(o => o.BoundingBoxes != null && o.BoundingBoxes.Count != 0).ToList();
                availableImages.RemoveAll(o => !o.BoundingBoxes.Any(p => objectClreplacedes.Select(q => q.Id).Contains(p.ObjectIndex)));

                var rng = new Random();
                var shuffledImages = availableImages.OrderBy(o => rng.Next()).ToList();

                var count = (int)(shuffledImages.Count * (yoloControl.TrainingPercentage / 100.0));
                trainingImages.AddRange(shuffledImages.Take(count));
                testingImages.AddRange(shuffledImages.Skip(count));

                images.AddRange(availableImages);
            }

            this._exportedNames = new Dictionary<AnnotationImage, string>();
            for (var i = 0; i < images.Count; i++)
            {
                var image = images[i];
                var newName = $"export{i.ToString("D5")}{Path.GetExtension(image.ImageName)}";
                this._exportedNames[image] = newName;
            }

            this.CreateFiles(dataPath, imagePath, images.ToArray(), objectClreplacedes);
            this.CreateMetaData(dataPath, trainingImages.ToArray(), testingImages.ToArray(), objectClreplacedes);

            var yoloConfigPath = yoloControl.UseTinyYoloConfig ? TinyYoloConfigPath : YoloConfigPath;
            this.CreateYoloConfig(path, yoloConfigPath, objectClreplacedes);
            this.CreateCommandFile(path);
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static int RandInt32(this Random random)
        {
            return random.Next();
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static uint RandUInt32(this Random random)
        {
            return (uint)random.Next();
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static int RandInt32()
        {
            return random.Next();
        }

19 Source : RandomHelper.cs
with MIT License
from AnotherEnd15

public static uint RandUInt32()
        {
            return (uint)random.Next();
        }

19 Source : ResourcesDownloader.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async Task DownloadAsync()
        {
            lock (Random)
            {
                if (this.preplaced)
                {
                    return;
                }

                this.preplaced = true;
            }

            if (this.IsDebugSkip)
            {
                return;
            }

            UpdateChecker.IsSustainSplash = true;

            var isDownloaded = false;

            using (var wc = new WebClient()
            {
                CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
            })
            {
                var temp = GetTempFileName();

                await wc.DownloadFileTaskAsync(RemoteResourcesListUri, temp);
                var list = File.ReadAllText(temp);
                File.Delete(temp);

                using (var sr = new StringReader(list))
                {
                    while (sr.Peek() > -1)
                    {
                        var line = sr.ReadLine().Trim();

                        if (string.IsNullOrEmpty(line) ||
                            line.StartsWith("#"))
                        {
                            continue;
                        }

                        var values = line.Split(' ');
                        if (values.Length < 2)
                        {
                            continue;
                        }

                        var local = GetPath(values[0]);
                        var remote = values[1];
                        var md5Remote = values.Length >= 3 ? values[2] : string.Empty;
                        var isForceUpdate = false;

                        if (values.Length >= 4)
                        {
                            bool.TryParse(values[3], out isForceUpdate);
                        }

                        if (File.Exists(local))
                        {
                            UpdateChecker.SetMessageToSplash($"Checking... {Path.GetFileName(local)}");

                            if (isForceUpdate)
                            {
                                // NO-OP
                            }
                            else
                            {
                                var md5Local = FileHelper.GetMD5(local);

                                if (IsVerifyHash(md5Local, md5Remote))
                                {
                                    if (!EnvironmentHelper.IsDebug)
                                    {
                                        AppLog.DefaultLogger.Info($"Checking... {local}. It was up-to-date.");
                                        continue;
                                    }
                                }
                            }
                        }

                        FileHelper.CreateDirectory(local);

                        UpdateChecker.SetMessageToSplash($"Downloading... {Path.GetFileName(local)}");

                        temp = GetTempFileName();
                        await wc.DownloadFileTaskAsync(
                            new Uri($"{remote}?random={Random.Next()}"),
                            temp);

                        var md5New = FileHelper.GetMD5(temp);

                        if (IsVerifyHash(md5New, md5Remote))
                        {
                            File.Copy(temp, local, true);
                            AppLog.DefaultLogger.Info($"Downloaded... {local}, verify is completed.");
                        }
                        else
                        {
                            if (EnvironmentHelper.IsDebug)
                            {
                                File.Copy(temp, local, true);
                            }

                            AppLog.DefaultLogger.Info($"Downloaded... {local}. Error, it was an inccorrect hash.");
                        }

                        File.Delete(temp);

                        isDownloaded = true;
                        await Task.Yield();
                    }
                }
            }

            UpdateChecker.SetMessageToSplash($"Resources update is now complete.");
            UpdateChecker.IsSustainSplash = false;

            if (isDownloaded)
            {
                await Task.Delay(TimeSpan.FromSeconds(0.3));
            }
        }

19 Source : PCGTests.cs
with Apache License 2.0
from AnthonyLloyd

[Fact]
        public void PCG_Fast()
        {
            var pcg = new PCG(1);
            var rnd = new Random();
            Check.Faster(
                () => pcg.Next(),
                () => rnd.Next(),
                repeat: 100, threads: 1
            )
            .Output(writeLine);
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

private object? GetTestValue(Type type)
        {
            if (!type.IsValueType)
            {
                return null;
            }

            if (type.IsEnum)
            {
                var defaultValue = Activator.CreateInstance(type);

                var values = Enum.GetValues(type);
                if (values.Length <= 1)
                    return defaultValue;
                else
                    return values.Cast<object>().First(x => !x.Equals(defaultValue));
            }
            else if (type == typeof(int))
            {
                var random = new Random();
                return random.Next();
            }
            else
            {
                throw new NotImplementedException();
            }
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

static void DoServerWork(ModbusRtuServer server)
        {
            var random = new Random();

            // Option A: normal performance version, more flexibility

            /* get buffer in standard form (Span<short>) */
            var registers = server.GetHoldingRegisters();
            registers.SetLittleEndian<int>(address: 5, random.Next());

            // Option B: high performance version, less flexibility

            /* interpret buffer as array of bytes (8 bit) */
            var byte_buffer = server.GetHoldingRegisterBuffer<byte>();
            byte_buffer[20] = (byte)(random.Next() >> 24);

            /* interpret buffer as array of shorts (16 bit) */
            var short_buffer = server.GetHoldingRegisterBuffer<short>();
            short_buffer[30] = (short)(random.Next(0, 100) >> 16);

            /* interpret buffer as array of ints (32 bit) */
            var int_buffer = server.GetHoldingRegisterBuffer<int>();
            int_buffer[40] = random.Next(0, 100);
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

static void DoServerWork(ModbusTcpServer server)
        {
            var random = new Random();

            // Option A: normal performance version, more flexibility

                /* get buffer in standard form (Span<short>) */
                var registers = server.GetHoldingRegisters();
                registers.SetLittleEndian<int>(address: 5, random.Next());

            // Option B: high performance version, less flexibility

                /* interpret buffer as array of bytes (8 bit) */
                var byte_buffer = server.GetHoldingRegisterBuffer<byte>();
                byte_buffer[20] = (byte)(random.Next() >> 24);

                /* interpret buffer as array of shorts (16 bit) */
                var short_buffer = server.GetHoldingRegisterBuffer<short>();
                short_buffer[30] = (short)(random.Next(0, 100) >> 16);

                /* interpret buffer as array of ints (32 bit) */
                var int_buffer = server.GetHoldingRegisterBuffer<int>();
                int_buffer[40] = random.Next(0, 100);
        }

See More Examples