Here are the examples of the csharp api System.Random.Next(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4354 Examples
19
View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : 00000vish
License : GNU General Public License v3.0
Project Creator : 00000vish
public static int GetRandomNumber(int min, int max)
{
lock (getrandom) // synchronize
{
return getrandom.Next(min, max);
}
}
19
View Source File : cUtils.cs
License : MIT License
Project Creator : 0xPh0enix
License : MIT License
Project Creator : 0xPh0enix
internal static string GenStr(int iLenght)
{
Random rRandom = new Random();
const string sSymbols = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
char[] cResult = new char[iLenght];
for (int i = 0; i < iLenght; i++)
{
cResult[i] = sSymbols[rRandom.Next(0, sSymbols.Length)];
}
return new string(cResult);
}
19
View Source File : HelpEngine.cs
License : MIT License
Project Creator : 0xLaileb
License : MIT License
Project Creator : 0xLaileb
public int Int(int min, int max) => random.Next(min, max);
19
View Source File : HelpEngine.cs
License : MIT License
Project Creator : 0xLaileb
License : MIT License
Project Creator : 0xLaileb
public float Float(int min, int max) => random.Next(min * 100, max * 100) / 100;
19
View Source File : DefaultCaptchaImageGenerator.cs
License : MIT License
Project Creator : 1992w
License : MIT License
Project Creator : 1992w
public void DrawDisorderLine(Graphics graph, int width, int height)
{
Pen linePen = new Pen(new SolidBrush(Color.Black), 3);
for (int i = 0; i < rand.Next(3, 5); i++)
{
linePen.Color = GetRandomDeepColor();
Point startPoint = new Point(rand.Next(0, width), rand.Next(0, height));
Point endPoint = new Point(rand.Next(0, width), rand.Next(0, height));
graph.DrawLine(linePen, startPoint, endPoint);
}
}
19
View Source File : DefaultCaptchaImageGenerator.cs
License : MIT License
Project Creator : 1992w
License : MIT License
Project Creator : 1992w
private void DrawCaptchaCode(Graphics graph, int width, int height, string captchaCode)
{
SolidBrush fontBrush = new SolidBrush(Color.Black);
int fontSize = GetFontSize(width, captchaCode.Length);
Font font = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
for (int i = 0; i < captchaCode.Length; i++)
{
fontBrush.Color = GetRandomDeepColor();
int shiftPx = fontSize / 6;
float x = i * fontSize + rand.Next(-shiftPx, shiftPx) + rand.Next(-shiftPx, shiftPx);
int maxY = height - fontSize;
if (maxY < 0) maxY = 0;
float y = rand.Next(0, maxY);
graph.DrawString(captchaCode[i].ToString(), font, fontBrush, x, y);
}
}
19
View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v
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
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 : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY
License : Mozilla Public License 2.0
Project Creator : 1M50RRY
public string GenerateKey()
{
string abc = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
string result = "";
Random rnd = new Random();
int iter = rnd.Next(5, abc.Length);
for (int i = 0; i < iter; i++)
result += abc[rnd.Next(0, abc.Length)];
return result;
}
19
View Source File : Tunneler.cs
License : MIT License
Project Creator : 1upD
License : MIT License
Project Creator : 1upD
public override void Step(AlifeMap map)
{
try {
int seed = this.X + this.Y + this.Z + (int)this.Direction + this.Height + this.Width + (int)System.DateTime.Now.Ticks;
// Get random number
Random random = new Random(seed);
double sample = random.NextDouble();
// Check turn probability. If turning, change direction 90 degrees
if (sample < this.ProbTurn)
{
sample = random.NextDouble();
int polarity = sample > 0.5 ? 1 : -1;
this.Direction = AlifeDirectionOperations.Add(this.Direction, polarity);
}
// Get new random seed
sample = random.NextDouble();
// Check reproduction probability
if (sample < this.ProbReproduce)
{
sample = random.NextDouble();
int polarity = sample > 0.5 ? 1 : -1;
AlifeDirection childDirection = AlifeDirectionOperations.Add(this.Direction, polarity);
int widthDecay = random.Next(this.MinWidthDecayRate, this.MaxWidthDecayRate);
int heightDecay = random.Next(this.MinHeightDecayRate, this.MaxHeightDecayRate);
Tunneler child = new Tunneler(this.Style, this.X, this.Y, this.Z, this.Width - widthDecay, this.Height - heightDecay, this.MaxLifetime - this.LifetimeDecayRate, this.MaxLifetime - this.LifetimeDecayRate, this.ProbReproduce, this.ProbTurn, this.ProbAscend, childDirection);
map.Agents.Add(child);
}
else
{
sample = random.NextDouble();
if (sample < this.ProbSpawnRoomer)
{
Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3), mustDeploy: false);
map.Agents.Add(child);
}
}
// Get new random seed
sample = random.NextDouble();
// Check a s c e n d probability
if (sample < this.ProbAscend)
{
sample = random.NextDouble();
int verticalDistance = random.Next(1, Math.Min(this.Height, this.MaxVerticalDrop));
int polarity = sample > 0.5 ? verticalDistance : -verticalDistance;
this.Z += polarity;
}
else
{
// Update location
switch (this.Direction)
{
case AlifeDirection.East:
this.X++;
break;
case AlifeDirection.North:
this.Y++;
break;
case AlifeDirection.West:
this.X--;
break;
case AlifeDirection.South:
this.Y--;
break;
case AlifeDirection.Up:
this.Z++;
break;
case AlifeDirection.Down:
this.Z--;
break;
}
}
// Mark location
// Nasty nested four loop to handle the added spaces from the height and width
bool vertical = this.Direction == AlifeDirection.North || this.Direction == AlifeDirection.South;
for (int x = this.X; x <= (vertical ? this.X + this.Width : this.X); x++)
{
for (int y = this.Y; y <= (vertical ? this.Y : this.Y + this.Width); y++)
{
for (int z = this.Z; z <= this.Z + this.Height; z++)
{
map.MarkLocation(this.Style, x, y, z);
}
}
}
if (this.Lifetime == 1 && this.SpawnRoomerOnDeath)
{
log.Debug(string.Format("Tunneler died at {0}, {1}, {2}.", this.X, this.Y, this.Z));
// Add a roomer
Roomer child = new Roomer(x: this.X, y: this.Y, z: this.Z, style: this.Style, height: Math.Max(this.Height, 2), maxWidth: Math.Min(this.Width * 2, 3));
map.Agents.Add(child);
}
this.Lifetime--;
}
catch (Exception e){
log.Error("Error in Tunneler Step function: ", e);
}
}
19
View Source File : Common.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
{
byte[] b = new byte[4];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
Random r = new Random(BitConverter.ToInt32(b, 0));
string s = null, str = custom;
if (useNum == true) { str += "0123456789"; }
if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>[email protected][\\]^_`{|}~"; }
for (int i = 0; i < length; i++)
{
s += str.Substring(r.Next(0, str.Length - 1), 1);
}
return s;
}
19
View Source File : MapCodeGenResolverAllowPrivateDump.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public _PrivateTest1 Init()
{
Random ran = new Random();
A = ran.Next(0,int.MaxValue);
B = ran.Next(0, int.MaxValue);
return this;
}
19
View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY
License : Mozilla Public License 2.0
Project Creator : 1M50RRY
private static string Pump()
{
Random rnd = new Random();
int size = rnd.Next(1000, 1000000);
byte[] gen = new byte[size];
rnd.NextBytes(gen);
string filename = "Garbage.bin";
File.WriteAllBytes(filename, gen);
return filename;
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne
License : GNU General Public License v3.0
Project Creator : 1RedOne
private void GetWait()
{
Random random = new Random();
int w = random.Next(3, 7);
System.Threading.Thread.Sleep(100 * w);
}
19
View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : 3DBear
License : MIT License
Project Creator : 3DBear
private static IEnumerable<T> ShuffleIterator<T>(
this IEnumerable<T> source, Random rng)
{
var buffer = source.ToList();
for (int i = 0; i < buffer.Count; i++)
{
int j = rng.Next(i, buffer.Count);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
19
View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
private string GenerateFuzzerName(bool upperCased = true)
{
// We are explicitly not using the Random field here to prevent from doing side effects on the deterministic fuzzer instances (depending on whether or not we specified a name)
var index = new Random().Next(0, 1500);
return $"fuzzer{index}";
}
19
View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public bool HeadsOrTails()
{
return InternalRandom.Next(0, 2) == 1;
}
19
View Source File : NumberExtensions.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public static byte FuzzDecimalScaleBetween(byte minValue, byte maxValue, Random random)
{
const byte minScaleForADecimal = 0;
const byte maxScaleForADecimal = 28;
ThrowIfMinIsGreaterThanMax(minValue, maxValue);
ThrowIfNotInAcceptableRange(minValue, maxValue, minScaleForADecimal, maxScaleForADecimal);
// Adjust the inclusiveness of the Fuzzer API to the exclusiveness of the Random API.
var inclusiveMaxScale = (maxValue == maxScaleForADecimal) ? maxScaleForADecimal : maxValue + 1;
var scale = (byte)random.Next(minValue, inclusiveMaxScale);
return scale;
}
19
View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
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 : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
private async Task FightingNpc(PlayerEnreplacedy player, NpcEnreplacedy npc)
{
var actionPoint = await _redisDb.StringGet<int>(string.Format(RedisKey.ActionPoint, player.Id));
if (actionPoint < 10)
{
actionPoint++;
}
Random random = new Random();
actionPoint -= random.Next(0, 4);
if (actionPoint <= 0)
{
actionPoint = 0;
}
await _redisDb.StringSet(string.Format(RedisKey.ActionPoint, player.Id), actionPoint);
await _mudProvider.ShowActionPoint(player.Id, actionPoint);
await _mudProvider.ShowMessage(player.Id, $"【切磋】你正在攻击[{npc.Name}]。。。");
await _mudProvider.AddFightingTarget(player.Id, new FightingTargetModel
{
TargetId = npc.Id,
TargetName = npc.Name,
Hp = npc.Hp,
Mp = npc.Mp,
MaxHp = npc.MaxHp,
MaxMp = npc.MaxMp,
TargetType = TargetTypeEnum.Npc
});
}
19
View Source File : RecurringQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<bool> Publish<T>(string uniqueId, T t, int delayMin, int delayMax = 0)
{
var channel = t.GetType().Name.ToLower();
var key = $"{queueName}_{channel}";
Random rnd = new Random();
var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
if (delay < 2000)
{
delay = 2000;
}
var message = new QueueData<T>
{
DelayMin = delayMin,
DelayMax = delayMax,
Data = t,
DelayTime = DateTime.Now.AddMilliseconds(delay)
};
var isSuccess = await _redisDb.HashSet(key, uniqueId, message);
if (isSuccess)
{
await RemoveCache(channel);
}
return isSuccess;
}
19
View Source File : DelayedQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<bool> Publish<T>(int playerId, T t, int delayMin, int delayMax = 0)
{
var channel = t.GetType().Name.ToLower();
Random rnd = new Random();
var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
var timestamp = DateTimeOffset.Now.AddSeconds(delay).ToUnixTimeSeconds();
var hasAdd = await _redisDb.SortedSetAdd($"{queueName}_{channel}", playerId.ToString(), timestamp);
if (hasAdd)
{
return await _redisDb.StringSet($"{queueName}_{channel}_{playerId}", t, DateTime.Now.AddSeconds(delay).AddDays(1));
}
return await Task.FromResult(false);
}
19
View Source File : NpcCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(ChatWithNpcCommand command, CancellationToken cancellationToken)
{
var playerId = command.PlayerId;
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
return Unit.Value;
}
var npcId = command.NpcId;
var npc = await _npcDomainService.Get(npcId);
if (npc == null)
{
return Unit.Value;
}
if (npc.Type != NpcTypeEnum.人物)
{
await _bus.RaiseEvent(new DomainNotification($"指令 错误!"));
return Unit.Value;
}
await _mudProvider.ShowMessage(player.Id, $"与 [{npc.Name}] 闲聊中...");
var chatWithNpcLike = await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpcLike, playerId, npcId));
if (chatWithNpcLike > 0)
{
return Unit.Value;
}
Random random = new Random();
int kar = Math.Abs(npc.Kar - player.Kar);
if (random.Next(1, 100) > kar)
{
var npcLiking = await _npcLikingDomainService.Get(x => x.PlayerId == player.Id && x.NpcId == npcId);
if (npcLiking == null)
{
npcLiking = new NpcLikingEnreplacedy
{
CreatedTime = DateTime.Now,
NpcId = npcId,
Liking = 1,
PlayerId = player.Id
};
await _npcLikingDomainService.Add(npcLiking);
}
else
{
if (npcLiking.Liking < 20)
{
npcLiking.Liking++;
await _npcLikingDomainService.Update(npcLiking);
}
}
await _mudProvider.ShowMessage(player.Id, $"交谈甚欢,与[{npc.Name}]的好感度上升");
}
await _bus.RaiseEvent(new ChatWithNpcEvent(playerId, npc.Id)).ConfigureAwait(false);
return Unit.Value;
}
19
View Source File : PlayerCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(CreateCommand command, CancellationToken cancellationToken)
{
var name = command.Name;
var gender = command.Gender;
var userId = command.UserId;
var str = command.Str;
var @int = command.Int;
var dex = command.Dex;
var con = command.Con;
var player = await _playerDomainService.Get(p => p.Name == name);
if (player != null)
{
await _bus.RaiseEvent(new DomainNotification("角色名已被使用,请更改!"));
return Unit.Value;
}
player = await _playerDomainService.Get(x => x.UserId == userId);
if (player != null)
{
await _bus.RaiseEvent(new DomainNotification("已经超过最大可创建角色数!"));
return Unit.Value;
}
if (str + @int + dex + con != 80)
{
await _bus.RaiseEvent(new DomainNotification("所有先天属性之和必须为80!"));
return Unit.Value;
}
var roomId = _appConfig.Site.BornRoomId;
if (roomId <= 0)
{
await _bus.RaiseEvent(new DomainNotification("未设置出生地点!"));
return Unit.Value;
}
var room = await _roomDomainService.Get(roomId);
if (room == null)
{
await _bus.RaiseEvent(new DomainNotification("设置的出生地点不存在!"));
return Unit.Value;
}
Random random = new Random();
player = new PlayerEnreplacedy
{
CreateDate = DateTime.Now,
LastDate = DateTime.Now,
Level = 1,
Name = name,
UserId = userId,
Status = PlayerStatusEnum.空闲,
Gender = gender,
Age = 14 * 12,
ConAdd = 0,
DexAdd = 0,
FactionId = 0,
IntAdd = 0,
Money = 0,
RoomId = roomId,
replacedle = "",
StrAdd = 0,
Atk = 0,
Str = str,
Con = con,
Int = @int,
Dex = dex,
Exp = 0,
Cor = 20,
Cps = 20,
Pot = 0,
Kar = random.Next(1, 100),
Def = 0,
Hp = 0,
LimitMp = 0,
MaxHp = 0,
MaxMp = 0,
Mp = 0,
Hit = 0,
Parry = 0,
Flee = 0,
Per = random.Next(10, 50),
Nrg = 0
};
player.Computed();
await _playerDomainService.Add(player);
var jwtAccount = new JwtAccount
{
UserId = userId,
Email = _account.Email,
PlayerId = player.Id,
PlayerName = player.Name
};
await _httpAccessor.HttpContext.SignIn("user", jwtAccount);
if (await Commit())
{
await _bus.RaiseEvent(new CreatedEvent(player)).ConfigureAwait(false);
}
return Unit.Value;
}
19
View Source File : PlayerCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public async Task<Unit> Handle(InitGameCommand command, CancellationToken cancellationToken)
{
_logger.LogDebug($"Handle InitGameCommand:{JsonConvert.SerializeObject(command)}");
var playerId = command.PlayerId;
if (playerId <= 0)
{
await _bus.RaiseEvent(new DomainNotification($"请重新进入!"));
return Unit.Value;
}
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
await _bus.RaiseEvent(new DomainNotification($"角色不存在!"));
return Unit.Value;
}
var room = await _roomDomainService.Get(player.RoomId);
if (room == null)
{
await _bus.RaiseEvent(new DomainNotification("房间不存在!"));
return Unit.Value;
}
player.LastDate = DateTime.Now;
await _cache.GetOrCreateAsync(CacheKey.IsActivityIn24Hours, async x => {
x.AbsoluteExpiration = DateTime.UtcNow.AddHours(24);
Random random = new Random();
player.Kar = random.Next(1, 100);
return await Task.FromResult(true);
});
player.Computed();
await _playerDomainService.Update(player);
if (await Commit())
{
await _bus.RaiseEvent(new InitGameEvent(player)).ConfigureAwait(false);
await _bus.RaiseEvent(new PlayerInRoomEvent(player, room)).ConfigureAwait(false);
}
return Unit.Value;
}
19
View Source File : HashEncode.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public static string GetRandomValue()
{
Random Seed = new Random();
string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
return RandomVaule;
}
19
View Source File : GH_Cloud.cs
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
License : GNU Lesser General Public License v3.0
Project Creator : 9and3
private void ResolveDisplay() {
Random random = new Random();
this.DisplayCloud = null;
this.DisplayCloud = new PointCloud();
if (this.m_value.Count < 1000) {
this.DisplayCloud.AddRange(this.m_value.GetPoints());
return;
}
int count = checked(this.m_value.Count - 1);
for (int i = 0; i <= count; i = checked(i + 1000)) {
long num = (long)random.Next(0, checked(this.m_value.Count() - 1));
this.DisplayCloud.Add(this.m_value[checked((int)num)].Location);
this.DisplayCloud[checked(this.DisplayCloud.Count() - 1)].Color = (this.m_value[checked((int)num)].Color);
}
}
19
View Source File : ProgressAnimations.cs
License : MIT License
Project Creator : a-luna
License : MIT License
Project Creator : a-luna
public static string RandomBrailleSequence()
{
var rand = new Random();
var sequence = string.Empty;
foreach(int i in Enumerable.Range(0, 40))
{
var charIndex = rand.Next(10241, 10496);
var randChar = Strings.ChrW(charIndex);
sequence += randChar;
}
return sequence;
}
19
View Source File : FrmAbout.cs
License : MIT License
Project Creator : A-Tabeshfard
License : MIT License
Project Creator : A-Tabeshfard
private void FrmAbout_Load(object sender, EventArgs e)
{
System.Drawing.Image image = default;
switch (random.Next(1, 7))
{
case 1:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_01));
}
break;
case 2:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_02));
}
break;
case 3:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_03));
}
break;
case 4:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_04));
}
break;
case 5:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_05));
}
break;
case 6:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_06));
}
break;
case 7:
{
image = Common.Extensions.ImageExtensions.ToImage(Common.Extensions.ImageExtensions.ImageToByteArray(Resource.Images.PNG.Logo_07));
}
break;
}
logoPictureBox.Image = image;
}
19
View Source File : RtmpSession.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal uint MakeUniqueMessageStreamId()
{
// TBD use uint.MaxValue
return (uint)_random.Next(1, 20);
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestBufferSegmentSize()
{
var random = new Random();
replacedert.ThrowsException<ArgumentOutOfRangeException>(() => new ByteBuffer(0));
for (int i = 0; i < 10000; i++)
{
var size = random.Next(1, 500);
var len1 = random.Next(0, 100);
var len2 = random.Next(0, 200);
var buffer = new ByteBuffer(size);
var bytes1 = new byte[len1];
var bytes2 = new byte[len2];
random.NextBytes(bytes1);
random.NextBytes(bytes2);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(bytes2);
var length = buffer.Length;
replacedert.AreEqual(length, len1 + len2);
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, len1).SequenceEqual(bytes1));
replacedert.IsTrue(outBuffer.replacedpan(len1, len2).SequenceEqual(bytes2));
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestBufferLengthDifferentBufferSegmentSize()
{
var random = new Random();
for (int i = 0; i < 1000; i++)
{
var len1 = random.Next(0, 3000);
var len2 = random.Next(0, 3000);
var bytes1 = new byte[len1];
var bytes2 = new byte[len2];
random.NextBytes(bytes1);
random.NextBytes(bytes2);
var buffer = new ByteBuffer(random.Next(10, 3000));
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(bytes2);
replacedert.AreEqual(len1 + len2, buffer.Length);
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestBufferLength()
{
var random = new Random();
for (int i = 0; i < 1000; i++)
{
var len1 = random.Next(0, 3000);
var len2 = random.Next(0, 3000);
var bytes1 = new byte[len1];
var bytes2 = new byte[len2];
random.NextBytes(bytes1);
random.NextBytes(bytes2);
var buffer = new ByteBuffer();
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(bytes2);
replacedert.AreEqual(len1 + len2, buffer.Length);
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer4DifferentBufferSegmentSize()
{
for (int i = 0; i < 10000; i++)
{
var random = new Random();
var buffer = new ByteBuffer(random.Next(1, 3000));
var bytes1 = new byte[1024];
var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(data);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, 1024).SequenceEqual(bytes1));
replacedert.AreEqual(outBuffer[1024], data);
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer5DifferentBufferSegmentSize()
{
for (int i = 0; i < 10000; i++)
{
var random = new Random();
var buffer = new ByteBuffer(512);
var bytes1 = new byte[4096];
var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(data);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
var test1 = new byte[2];
var test2 = new byte[3];
var test3 = new byte[512];
var test4 = new byte[1024];
buffer.TakeOutMemory(test1.replacedpan());
buffer.TakeOutMemory(test2.replacedpan());
buffer.TakeOutMemory(test3);
buffer.TakeOutMemory(test4);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(test1.replacedpan().SequenceEqual(bytes1.replacedpan(0, 2)));
replacedert.IsTrue(test2.replacedpan().SequenceEqual(bytes1.replacedpan(2, 3)));
replacedert.IsTrue(test3.replacedpan().SequenceEqual(bytes1.replacedpan(5, 512)));
replacedert.IsTrue(test4.replacedpan().SequenceEqual(bytes1.replacedpan(517, 1024)));
replacedert.IsTrue(outBuffer.replacedpan(0, 4096 - 5 - 512 - 1024).SequenceEqual(bytes1.replacedpan(517 + 1024)));
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestParalleWriteAndRead()
{
var random = new Random();
var buffer = new ByteBuffer(512, 35767);
var th1 = new Thread(() =>
{
byte i = 0;
while (true)
{
var arr = new byte[new Random().Next(256, 512)];
for (var j = 0; j < arr.Length; j++)
{
arr[j] = i;
i++;
if (i > 100)
{
i = 0;
}
}
buffer.WriteToBuffer(arr);
}
});
th1.IsBackground = true;
th1.Start();
var th2 = new Thread(() =>
{
while (true)
{
var arr = new byte[new Random().Next(129, 136)];
if (buffer.Length >= arr.Length)
{
buffer.TakeOutMemory(arr);
for (int i = 1; i < arr.Length; i++)
{
replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
}
}
}
});
th2.IsBackground = true;
th2.Start();
Thread.Sleep(TimeSpan.FromSeconds(30));
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestAsyncWriteAndRead()
{
var buffer = new ByteBuffer(512, 35767);
short c = 0;
Func<Task> th1 = async () =>
{
byte i = 0;
while (c < short.MaxValue)
{
var arr = new byte[new Random().Next(256, 512)];
for (var j = 0; j < arr.Length; j++)
{
arr[j] = i;
i++;
if (i > 100)
{
i = 0;
}
}
await buffer.WriteToBufferAsync(arr);
c++;
}
};
Func<Task> th2 = async () =>
{
while (c < short.MaxValue)
{
var arr = new byte[new Random().Next(129, 136)];
if (buffer.Length >= arr.Length)
{
await buffer.TakeOutMemoryAsync(arr);
for (int i = 1; i < arr.Length; i++)
{
replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
}
}
}
};
var t = th1();
th2();
t.Wait();
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer3DifferentBufferSegmentSize()
{
for (int i = 0; i < 10000; i++)
{
var random = new Random();
var buffer = new ByteBuffer(random.Next(1, 3000));
var bytes1 = new byte[3];
var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(data);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
replacedert.AreEqual(outBuffer[3], data);
}
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestClearAndCopyToDifferentBufferSegmentSize()
{
var random = new Random();
var buffer = new ByteBuffer(random.Next(1, 3000));
var bytes1 = new byte[4000];
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
outBuffer.replacedpan().Clear();
buffer.TakeOutMemory(outBuffer);
replacedert.IsFalse(outBuffer.Any(b => b != 0));
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer4()
{
var buffer = new ByteBuffer();
var random = new Random();
var bytes1 = new byte[1024];
var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(data);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, 1024).SequenceEqual(bytes1));
replacedert.AreEqual(outBuffer[1024], data);
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer3()
{
var buffer = new ByteBuffer();
var random = new Random();
var bytes1 = new byte[3];
var data = (byte)random.Next(byte.MinValue, byte.MaxValue);
random.NextBytes(bytes1);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(data);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
replacedert.AreEqual(outBuffer[3], data);
}
19
View Source File : TestUnlimitedBuffer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
[TestMethod]
public void TestWriteToBuffer1DifferentBufferSegmentSize()
{
for (int i = 0; i < 10000; i++)
{
var random = new Random();
var buffer = new ByteBuffer(random.Next(1, 3000));
var bytes1 = new byte[3];
var bytes2 = new byte[7];
random.NextBytes(bytes1);
random.NextBytes(bytes2);
buffer.WriteToBuffer(bytes1);
buffer.WriteToBuffer(bytes2);
var length = buffer.Length;
var outBuffer = ArrayPool<byte>.Shared.Rent(length);
buffer.TakeOutMemory(outBuffer);
replacedert.IsTrue(outBuffer.replacedpan(0, 3).SequenceEqual(bytes1));
replacedert.IsTrue(outBuffer.replacedpan(3, 7).SequenceEqual(bytes2));
}
}
19
View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
private static void randJunk(ref string currLineAddition, ref string extraCodeAddition, bool forceJunk = false)
{
if (!shouldGeneratJunk() && !forceJunk) return;
junk_count++;
switch (rnd.Next(0, 5))
{
case 2:
currLineAddition = "lea esp, [esp-8]\n" +
"mov dword ptr [esp+4], offset obfusca_" + label_extra_count + "\n" +
"mov dword ptr [esp+0], offset obfusca_" + (label_extra_count + 1) + "\n" +
"ret\n" +
"obfusca_" + label_extra_count + ":\n";
extraCodeAddition = "obfusca_" + (label_extra_count + 1) + ":\n" +
"lea esp, [esp+4]\n" +
"jmp dword ptr [esp-4]\n" +
"int 3\n";
label_extra_count += 2;
break;
case 3:
currLineAddition = "push eax\n" +
"lea esp, [esp-8]\n" +
"mov dword ptr [esp+0], offset obfusca_" + label_extra_count + "\n" +
"mov dword ptr [esp+4], offset obfusca_" + (label_extra_count + 1) + "\n" +
"mov eax, [esp+4]\n" +
"xchg eax, [esp+0]\n" +
"mov [esp+4], eax\n" +
"ret\n" +
"obfusca_" + label_extra_count + ":\n" +
"pop eax\n";
extraCodeAddition = "obfusca_" + (label_extra_count + 1) + ":\n" +
"lea esp, [esp+4]\n" +
"jmp dword ptr [esp-4]\n" +
"int 3\n";
label_extra_count += 2;
break;
case 0:
currLineAddition = "pushf\n" +
"sub esp, 5\nlea esp, [esp-3]\n" +
"mov dword ptr [esp+4], offset obfusca_" + label_extra_count + "\n" +
"mov dword ptr [esp+0], offset obfusca_" + (label_extra_count + 1) + "\n" +
"jmp dword ptr [esp+0]\n" +
"obfusca_" + label_extra_count + ":\n";
extraCodeAddition = "obfusca_" + (label_extra_count + 1) + ":\n" +
"lea esp, [esp+8]\n" +
"popf\n" +
"jmp dword ptr [esp-8]\n" +
"int 3\n";
label_extra_count += 2;
break;
case 1:
currLineAddition = "push offset obfusca_" + label_extra_count + "\n" +
"push offset obfusca_" + (label_extra_count + 1) + "\n" +
"ret\n" +
"obfusca_" + label_extra_count + ":\n";
extraCodeAddition = "obfusca_" + (label_extra_count + 1) + ":\n" +
"ret\n" +
"int 3\n";
label_extra_count += 2;
break;
default:
currLineAddition = "pushf\nxor edi, esi\nxor edi, esi\npopf\nnop\n";
extraCodeAddition = "int 0x2e\n";
break;
}
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
private static Stack<AbstractPtg> GetAntireplacedysisCharSubroutineForInt(ushort charInt, string varName, string decoyVarName,
int functionLabelOffset)
{
int numAndArgs = 2;
List<AbstractPtg> ptgList = new List<AbstractPtg>();
ptgList.Add(new PtgFuncVar(FtabValues.IF, 3, AbstractPtg.PtgDataType.VALUE));
ptgList.Add(new PtgMissArg());
ptgList.Add(new PtgFuncVar(FtabValues.USERDEFINEDFUNCTION, 1, AbstractPtg.PtgDataType.VALUE));
ptgList.Add(new PtgName(functionLabelOffset));
ptgList.Add(new PtgFuncVar(FtabValues.AND, numAndArgs, AbstractPtg.PtgDataType.VALUE));
Random r = new Random();
int correctArg = r.Next(0, numAndArgs);
for (int i = 0; i < numAndArgs; i += 1)
{
ptgList.Add(new PtgFuncVar(FtabValues.SET_NAME, 2, AbstractPtg.PtgDataType.VALUE));
if (i == correctArg)
{
ptgList.Add(new PtgInt(charInt));
ptgList.Add(new PtgStr(varName, true));
}
else
{
ptgList.Add(new PtgInt((ushort)r.Next(1,255)));
ptgList.Add(new PtgStr(decoyVarName, true));
}
}
ptgList.Reverse();
return new Stack<AbstractPtg>(ptgList);
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static Stack<AbstractPtg> GetObfuscatedCharPtgForInt(ushort charInt)
{
Stack<AbstractPtg> ptgStack = new Stack<AbstractPtg>();
Random r = new Random();
//Allegedly we max out at 0xFF for column values...could be a nice accidental way of creating alternate references though
//Generate a random PtgRef to start the stack - if it's an empty cell, this is a no-op if we end with a PtgConcat
ptgStack.Push(new PtgRef(r.Next(1000, 2000), r.Next(0x20, 0x9F), false, false, AbstractPtg.PtgDataType.VALUE));
ptgStack.Push(new PtgNum(charInt));
ptgStack.Push(new PtgInt(0));
ptgStack.Push(new PtgFunc(FtabValues.ROUND, AbstractPtg.PtgDataType.VALUE));
//An alternate way to invoke the CHAR function by using PtgFuncVar instead
// ptgStack.Push(new PtgFuncVar(FtabValues.CHAR, 1, AbstractPtg.PtgDataType.VALUE));
ptgStack.Push(new PtgFunc(FtabValues.CHAR, AbstractPtg.PtgDataType.VALUE));
//Merge the random PtgRef we generate at the beginning
ptgStack.Push(new PtgConcat());
return ptgStack;
}
19
View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
private static bool shouldGeneratJunk()
{
return (rnd.Next(0, 100) < Properties.Settings.Default.obfusPcnt);
}
19
View Source File : obfuscator.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
private static void obfuscatCode(string orginalCode, ref string currLineAddition, ref string extraCodeAddition, bool forceJunk = false)
{
currLineAddition = orginalCode + "\r\n";
extraCodeAddition = "";
if (!shouldGeneratJunk() && !forceJunk) return;
obfuscat_code_count++;
Match m = new Regex(@"mov[\x20\t]+([^,]+),(.+)").Match(orginalCode);
if (m.Success)
{
currLineAddition = string.Format(
"push {1} \r\n" +
"call obfusca_{2} \r\n" +
"pop {0} \r\n",
m.Groups[1].Value, m.Groups[2].Value, label_extra_count
);
extraCodeAddition = string.Format(
"obfusca_{0}: \r\n" +
"pushf \r\n" +
"push ecx \r\n" +
"mov ecx, {2} \r\n" +
"obfusca_{1}: \r\n" +
"loop obfusca_{1} \r\n" +
"pop ecx \r\n" +
"popf \r\n" +
"ret \r\n", label_extra_count, label_extra_count+1, rnd.Next(5, 128)
);
label_extra_count += 2;
return;
}
m = new Regex(@"call[\x20\t]+(.+)").Match(orginalCode);
if (m.Success)
{
currLineAddition = string.Format(
"push offset obfusca_{1} \r\n" +
"push offset {0} \r\n" +
"ret \r\n" +
"obfusca_{1}:",
m.Groups[1].Value, label_extra_count
);
extraCodeAddition = "";
label_extra_count += 1;
return;
}
currLineAddition = string.Format(
"obfusca_{1}: \r\n" +
"call obfusca_{2} \r\n" +
"loop obfusca_{1} \r\n" +
"obfusca_{2}: \r\n" +
"call obfusca_{3} \r\n"+
"loop obfusca_{1} \r\n" +
"obfusca_{3}: \r\n" +
"call obfusca_{4} \r\n" +
"loop obfusca_{2} \r\n" +
"obfusca_{4}: \r\n" +
"lea esp, [esp+12] \r\n" +
"{0} \r\n",
orginalCode, label_extra_count, label_extra_count + 1, label_extra_count + 2, label_extra_count + 3
);
label_extra_count += 4;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<BiffRecord> ConvertChunkedStringToFormulas(List<string> chunkedString, int rwStart, int colStart, int dstRw,
int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
{
bool instaEval = false;
if (chunkedString[0].StartsWith(MacroPatterns.InstaEvalMacroPrefix))
{
if (packingMethod != SheetPackingMethod.ArgumentSubroutines)
{
throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval");
}
instaEval = true;
chunkedString[0] = chunkedString[0].Replace(MacroPatterns.InstaEvalMacroPrefix, "");
}
List<BiffRecord> formulaList = new List<BiffRecord>();
List<Cell> concatCells = new List<Cell>();
int curRow = rwStart;
int curCol = colStart;
foreach (string str in chunkedString)
{
List<Cell> createdCells = new List<Cell>();
//TODO [Stealth] Perform additional operations to obfuscate static =CHAR(#) signature
foreach (char c in str)
{
Stack<AbstractPtg> ptgStack = GetPtgStackForChar(c, packingMethod);
ushort charValue = Convert.ToUInt16(c);
if (charValue > 0xFF)
{
ptgStack = new Stack<AbstractPtg>();
ptgStack.Push(new PtgStr("" + c, true));
}
Cell curCell = new Cell(curRow, curCol, ixfe);
createdCells.Add(curCell);
Formula charFrm = new Formula(curCell, FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack));
byte[] formulaBytes = charFrm.GetBytes();
formulaList.Add(charFrm);
curRow += 1;
}
Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol);
concatCells.Add(new Cell(curRow, curCol, ixfe));
formulaList.Add(concatFormula);
curRow += 1;
}
Formula concatConcatFormula = BuildConcatCellsFormula(concatCells, curRow, curCol);
formulaList.Add(concatConcatFormula);
curRow += 1;
PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE);
Random r = new Random();
int randomBitStuffing = r.Next(1, 32) * 0x100;
PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false);
Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval);
formulaList.Add(formula);
return formulaList;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
public static List<BiffRecord> BuildFORMULAFunctionCall(List<Cell> createdCells, int curRow, int curCol, int dstRw, int dstCol, SheetPackingMethod packingMethod, bool instaEval)
{
List<BiffRecord> formulaList = new List<BiffRecord>();
Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol);
formulaList.Add(concatFormula);
curRow += 1;
PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE);
Random r = new Random();
int randomBitStuffing = r.Next(1, 32) * 0x100;
PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false);
Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval);
formulaList.Add(formula);
return formulaList;
}
19
View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
private static List<BiffRecord> BuildFORMULAFunctionCall(List<Cell> createdCells, int curRow, int curCol, int dstRw, int dstCol, SheetPackingMethod packingMethod, bool instaEval)
{
List<BiffRecord> formulaList = new List<BiffRecord>();
Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol);
formulaList.Add(concatFormula);
curRow += 1;
PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE);
Random r = new Random();
int randomBitStuffing = r.Next(1, 32) * 0x100;
PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false);
Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval);
formulaList.Add(formula);
return formulaList;
}
See More Examples