Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Single(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1341 Examples
19
View Source File : ReaderTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task<string> GetFirstName(int id)
{
await Task.Delay(50);
return Data.Single(i => i.Id == id).FirstName;
}
19
View Source File : ReaderTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task<string> GetLastName(int id)
{
await Task.Delay(50);
return Data.Single(i => i.Id == id).LastName;
}
19
View Source File : ReaderTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task<int> GetWin(int id)
{
await Task.Delay(50);
return Data.Single(i => i.Id == id).Win;
}
19
View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
private object CallPrivateGenericMethod(Type typeOfT, string privateMethodName, object[] parameters)
{
var methodInfo = ((TypeInfo) typeof(TypeFuzzer)).DeclaredMethods.Single(m =>
m.IsGenericMethod && m.IsPrivate && m.Name.Contains(privateMethodName));
var generic = methodInfo.MakeGenericMethod(typeOfT);
// private T GenerateInstanceOf<T>(int recursionLevel)
var result = generic.Invoke(this, parameters);
return result;
}
19
View Source File : GeographyExpert.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public static StateProvinceArea GiveMeStateProvinceAreaOf(string cityName)
{
return CitiesOfTheWorld.Single(c => c.CityName == cityName).StateProvinceArea;
}
19
View Source File : GeographyExpert.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public static Country GiveMeCountryOf(string cityName)
{
return CitiesOfTheWorld.Single(c => c.CityName == cityName).Country;
}
19
View Source File : GeographyExpert.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public static string GiveMeZipCodeFormatOf(string cityName)
{
return CitiesOfTheWorld.Single(c => c.CityName == cityName).ZipCodeFormat;
}
19
View Source File : LanguageHelper.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private string GetFileContents(string filename)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
string resourceName = replacedembly.GetManifestResourceNames().Single(str => str.EndsWith(filename));
using (Stream stream = replacedembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
19
View Source File : FundingTypeConverter.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return values.Single(v => v.Value == reader.Value.ToString()).Key;
}
19
View Source File : BitfinexErrors.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
internal static BitfinexError GetError(BitfinexErrorKey key)
{
return ErrorRegistrations.Single(e => e.Key == key).Value;
}
19
View Source File : ActivationConfigurationTests.cs
License : MIT License
Project Creator : ababik
License : MIT License
Project Creator : ababik
[TestMethod]
public void ConfigureByConstructorAndParameters_InvalidParameter_Fail()
{
var user = new User(1, "Joe", "Doe");
var constructor = user.GetType().GetConstructor(new[] { typeof(string), typeof(string) });
var type = typeof(Employee);
var firstNameParameter = type.GetConstructor(new[] { typeof(Guid), typeof(string), typeof(string) }).GetParameters().Single(x => x.Name == "firstName");
var firstNameProperty = type.GetProperty("FirstName");
try
{
var config = new ActivationConfiguration()
.Configure(constructor, new Dictionary<ParameterInfo, PropertyInfo>() { [firstNameParameter] = firstNameProperty });
}
catch (Exception ex) when (ex.Message == $"Invalid parameter '{firstNameParameter.Name}'. Parameter must be a member of '{constructor.DeclaringType}' constructor.")
{
return;
}
replacedert.Fail();
}
19
View Source File : Instrument.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static Instrument Parse(string instrumentString)
{
return new[] { EurUsd, Indu, Spx500, CrudeOil, Test }.Single(x => x.Symbol.ToUpper(CultureInfo.InvariantCulture) == instrumentString.ToUpper(CultureInfo.InvariantCulture));
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static async Task<AscData> ReadResourceToAscData(
string resourceName, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
{
var result = await Task.Run(() =>
{
var asm = replacedembly.GetExecutingreplacedembly();
var resource = asm.GetManifestResourceNames()
.Single(x => x.Contains(resourceName));
using (var stream = asm.GetManifestResourceStream(resource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
return ReadFromStream(streamReader, colorMapFunction, reportProgress);
}
});
return result;
}
19
View Source File : TimeFrame.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public static TimeFrame Parse(string input)
{
return new[] {Minute5, Minute15, Hourly, Daily}.Single(x => x.Value.ToUpper(CultureInfo.InvariantCulture) == input.ToUpper(CultureInfo.InvariantCulture));
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public IEnumerable<TradeData> GetTradeticks()
{
var dataSource = new List<TradeData>();
var asm = replacedembly.GetExecutingreplacedembly();
var csvResource = asm.GetManifestResourceNames().Single(x => x.ToUpper(CultureInfo.InvariantCulture).Contains("TRADETICKS.CSV.GZ"));
using (var stream = asm.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var data = new TradeData();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
data.TradeDate = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
data.TradePrice = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
data.TradeSize = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
dataSource.Add(data);
line = streamReader.ReadLine();
}
}
return dataSource;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public List<WeatherData> LoadWeatherData()
{
var values = new List<WeatherData>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("WeatherData.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var tokens = line.Split(',');
values.Add(new WeatherData
{
// ID, Date, MinTemp, MaxTemp, Rainfall, Sunshine, UVIndex, WindSpd, WindDir, Forecast, LocalStation
ID = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
Date = DateTime.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo),
MinTemp = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
MaxTemp = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
Rainfall = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo),
Sunshine = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo),
UVIndex = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo),
WindSpeed = int.Parse(tokens[7], NumberFormatInfo.InvariantInfo),
WindDirection = (WindDirection) Enum.Parse(typeof(WindDirection), tokens[8]),
Forecast = tokens[9],
LocalStation = bool.Parse(tokens[10])
});
line = streamReader.ReadLine();
}
}
return values;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public double[] LoadWaveformData()
{
var values = new List<double>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("Waveform.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
View Source File : SweepingEcg.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private double[] LoadWaveformData(string filename)
{
var values = new List<double>();
// Load the waveform.csv file for the source data
var asm = typeof (SweepingEcg).replacedembly;
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains(filename));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var streamReader = new StreamReader(stream))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
View Source File : ChapmanKolmogorov.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public DBHazardPDF GetHazardByTransitionCode(int code)
{
var ret = hazards.Single(s => s.StateFromToID == code);
return ret;
}
19
View Source File : ControlFlowGraphBuilder.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public VariableDeclaration VariableFor(BindingSymbol symbol)
{
return variables.Single(v => v.Symbol == symbol);
}
19
View Source File : Client.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void DeleteRow(Guid id)
{
_rows.Single(x => x.Id == id).Deleted = DateTimeOffset.Now;
}
19
View Source File : Client.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void UpdateRow(ClientTableSchema row)
{
var dbRow = _rows.Single(x => x.Id == row.Id);
if (string.IsNullOrEmpty(dbRow.Original))
dbRow.Original = JsonConvert.SerializeObject(row);
dbRow.Name = row.Name;
dbRow.Description = row.Description;
dbRow.LastUpdated = DateTimeOffset.Now;
}
19
View Source File : ServerApi.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public void DifferentialSync(List<string> jsonUpdate)
{
foreach (var item in jsonUpdate)
{
dynamic update = JsonConvert.DeserializeObject(item);
var lastUpdated = (DateTimeOffset)update.LastUpdated;
var id = (Guid)update.Id;
var dbRow = _rows.Single(x => x.Id == id);
if (((JObject)update)["Name"] != null)
dbRow.Name = update.Name;
if (((JObject)update)["Description"] != null)
dbRow.Description = update.Description;
dbRow.LastUpdated = DateTimeOffset.Now;
dbRow.ClientLastUpdated = lastUpdated;
}
}
19
View Source File : ServerApi.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
private void Update(TableSchema row)
{
if (row.Deleted.HasValue)
{
var dbRow = _rows.Single(x => x.Id == row.Id);
dbRow.Deleted = row.Deleted;
dbRow.LastUpdated = row.LastUpdated;
}
else
{
var dbRow = _rows.Single(x => x.Id == row.Id);
if (dbRow.ClientLastUpdated > row.LastUpdated)
{
// Conflict
// Here you can just do a server, or client wins scenario, on a whole row basis.
// E.g take the servers word or the clients word
// e.g. Server - wins - Ignore changes and just update time.
dbRow.LastUpdated = DateTimeOffset.Now;
dbRow.ClientLastUpdated = row.LastUpdated;
}
else // Client is new than server
{
dbRow.Name = row.Name;
dbRow.Description = row.Description;
dbRow.LastUpdated = DateTimeOffset.Now;
dbRow.ClientLastUpdated = row.LastUpdated;
}
}
}
19
View Source File : InterpolatedStringVisitor.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
protected override IMethodSymbol GetStringFormatOverloadToCall()
{
return StringFormatOverloads.Single(f => f.Parameters[0].Type.SpecialType == SpecialType.System_String
&& f.Parameters[1].Type.SpecialType == SpecialType.System_Object
&& f.Parameters.Length == _numberOfArguments + 1);
}
19
View Source File : InterpolatedStringVisitor.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
protected override IMethodSymbol GetStringFormatOverloadToCall()
{
return StringFormatOverloads.Single(f => f.Parameters[0].Type.SpecialType == SpecialType.System_String
&& f.Parameters[1].Type is IArrayTypeSymbol { ElementType: { SpecialType: SpecialType.System_Object } }
&& f.Parameters.Length == 2);
}
19
View Source File : BenchmarkTestBase.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private async Task StartNodeAsync()
{
var ownAddress = await _accountService.GetAccountAsync();
var callList = new List<ContractInitializationMethodCall>();
callList.Add(nameof(TokenContractContainer.TokenContractStub.Create), new CreateInput
{
Symbol = _nativeSymbol,
TokenName = "ELF_Token",
TotalSupply = TokenTotalSupply,
Decimals = 8,
Issuer = ownAddress,
IsBurnable = true
});
callList.Add(nameof(TokenContractContainer.TokenContractStub.SetPrimaryTokenSymbol),
new SetPrimaryTokenSymbolInput {Symbol = _nativeSymbol});
callList.Add(nameof(TokenContractContainer.TokenContractStub.Issue), new IssueInput
{
Symbol = _nativeSymbol,
Amount = TokenTotalSupply,
To = ownAddress,
Memo = "Issue"
});
var tokenContractCode = Codes.Single(kv => kv.Key.Split(",").First().Trim().EndsWith("Mulreplacedoken")).Value;
var dto = new OsBlockchainNodeContextStartDto
{
ZeroSmartContract = typeof(BasicContractZero),
ChainId = ChainHelper.ConvertBase58ToChainId("AELF"),
SmartContractRunnerCategory = KernelConstants.CodeCoverageRunnerCategory,
};
var genesisSmartContractDto = new GenesisSmartContractDto
{
Code = tokenContractCode,
SystemSmartContractName = TokenSmartContractAddressNameProvider.Name,
};
genesisSmartContractDto.AddGenesisTransactionMethodCall(callList.ToArray());
dto.InitializationSmartContracts.Add(genesisSmartContractDto);
await _osBlockchainNodeContextService.StartAsync(dto);
}
19
View Source File : TestContractTestBase.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
protected void InitializePatchedContracts()
{
BasicContractZeroStub = GetContractZeroTester(DefaultSenderKeyPair);
//deploy test contract1
var basicFunctionPatchedCode = PatchedCodes.Single(kv => kv.Key.EndsWith("BasicFunction")).Value;
CheckCode(basicFunctionPatchedCode);
BasicFunctionContractAddress = AsyncHelper.RunSync(async () =>
await DeployContractAsync(
KernelConstants.CodeCoverageRunnerCategory,
basicFunctionPatchedCode,
TestBasicFunctionContractSystemName,
DefaultSenderKeyPair));
TestBasicFunctionContractStub = GetTestBasicFunctionContractStub(DefaultSenderKeyPair);
AsyncHelper.RunSync(async () => await InitialBasicFunctionContract());
//deploy test contract2
var basicSecurityContractCode = PatchedCodes.Single(kv => kv.Key.EndsWith("BasicSecurity")).Value;
BasicSecurityContractAddress = AsyncHelper.RunSync(async () =>
await DeployContractAsync(
KernelConstants.CodeCoverageRunnerCategory,
basicSecurityContractCode,
TestBasicSecurityContractSystemName,
DefaultSenderKeyPair));
TestBasicSecurityContractStub = GetTestBasicSecurityContractStub(DefaultSenderKeyPair);
AsyncHelper.RunSync(async () => await InitializeSecurityContract());
CheckCode(basicSecurityContractCode);
}
19
View Source File : ContractTester.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private byte[] GetContractCodeByName(string contractName)
{
return Codes.Single(kv => kv.Key.Split(",").First().Trim().EndsWith(contractName)).Value;
}
19
View Source File : CalculateFunctionProviderTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void CheckBlockExecutedData(BlockStateSet blockStateSet,
Dictionary<string, CalculateFunction> functionMap)
{
var chainContext = new ChainContext
{
BlockHash = blockStateSet.BlockHash,
BlockHeight = blockStateSet.BlockHeight
};
var functionMapFromBlockExecutedData =
_calculateFunctionProvider.GetCalculateFunctions(chainContext);
foreach (var key in functionMap.Keys)
{
var fromExecutedData = functionMapFromBlockExecutedData.Values.Single(d =>
((FeeTypeEnum) d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
var actual = functionMap.Values.Single(d =>
((FeeTypeEnum) d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
fromExecutedData.CalculateFeeCoefficients.ShouldBe(actual.CalculateFeeCoefficients);
}
}
19
View Source File : CalculateFunctionExecutedDataServiceTests.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void CheckBlockExecutedData(BlockStateSet blockStateSet,
Dictionary<string, CalculateFunction> functionMap)
{
var chainContext = new ChainContext
{
BlockHash = blockStateSet.BlockHash,
BlockHeight = blockStateSet.BlockHeight
};
var functionMapFromBlockExecutedData =
_calculateFunctionExecutedDataService.GetBlockExecutedData(chainContext,
GetBlockExecutedDataKey());
foreach (var key in functionMap.Keys)
{
var fromExecutedData = functionMapFromBlockExecutedData.Values.Single(d =>
((FeeTypeEnum) d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
var actual = functionMap.Values.Single(d =>
((FeeTypeEnum) d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
fromExecutedData.CalculateFeeCoefficients.ShouldBe(actual.CalculateFeeCoefficients);
}
}
19
View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames
License : MIT License
Project Creator : 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
View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void removeButton_Click(object sender, EventArgs e)
{
StringCollection removals = new StringCollection();
foreach (DataGridViewRow row in localGrid.Rows)
{
if (Convert.ToBoolean(row.Cells[0].Value))
{
removals.Add(row.Cells[5].Value.ToString());
}
}
foreach (string pak in removals)
{
if (Directory.Exists(Path.Combine(pakDir, pak)))
{
DeleteDirectory(Path.Combine(pakDir, pak));
}
if (Directory.Exists(Path.Combine(pakDir, "~" + pak)))
{
DeleteDirectory(Path.Combine(pakDir, "~" + pak));
}
gridSelections.Remove(pak);
string jsonString = File.ReadAllText(mainForm.localJSON);
var list = JsonConvert.DeserializeObject<List<PAK>>(jsonString);
list.Remove(list.Single( s => s.modDir == pak));
var convertedJSON = JsonConvert.SerializeObject(list);
File.WriteAllText(mainForm.localJSON, convertedJSON);
}
saveSettings();
populateGrid(localJSON);
}
19
View Source File : DiscriminatedUnionConverter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
Type unionType = UnionTypeLookupCache.Get(value.GetType());
Union union = UnionCache.Get(unionType);
int tag = (int)union.TagReader.Invoke(value);
UnionCase caseInfo = union.Cases.Single(c => c.Tag == tag);
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue(caseInfo.Name);
if (caseInfo.Fields != null && caseInfo.Fields.Length > 0)
{
object[] fields = (object[])caseInfo.FieldReader.Invoke(value);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
writer.WriteStartArray();
foreach (object field in fields)
{
serializer.Serialize(writer, field);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
}
19
View Source File : CommonUtils.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
public static string ReadreplacedemblyFile(string name)
{
// Determine path
var replacedembly = replacedembly.GetExecutingreplacedembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(EasyJob)))
{
resourcePath = replacedembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = replacedembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
this IQueryable<TOuter> outer,
IQueryable<TInner> inner,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<TOuter, TInner, TResult>> resultSelector)
{
MethodInfo groupJoin = typeof(Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
.MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(LeftJoinIntermediate<TOuter, TInner>));
MethodInfo selectMany = typeof(Queryable).GetMethods()
.Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
.MakeGenericMethod(typeof(LeftJoinIntermediate<TOuter, TInner>), typeof(TInner), typeof(TResult));
var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> { OneOuter = oneOuter, ManyInners = manyInners });
MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);
var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
(t => t.ManyInners.DefaultIfEmpty());
ParameterExpression paramUser = resultSelector.Parameters.First();
ParameterExpression paramNew = Expression.Parameter(typeof(LeftJoinIntermediate<TOuter, TInner>), "t");
MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");
LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body) ?? throw new InvalidOperationException(), paramNew, resultSelector.Parameters.Skip(1).First());
MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);
return outer.Provider.CreateQuery<TResult>(exprSelectMany);
}
19
View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
private static MethodInfo GetEnumerableMethod(string name, int parameterCount = 0, Func<MethodInfo, bool> predicate = null)
{
return typeof(Enumerable)
.GetTypeInfo()
.GetDeclaredMethods(name)
.Single(_ => _.GetParameters().Length == parameterCount && (predicate == null || predicate(_)));
}
19
View Source File : WorkerHostService.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
public async Task LaunchInstanceAsync(string hostId, string imageId, int numberOfInstances, int maxIdleTimeSec)
{
var host = _hosts.Single(h => h.Id == hostId);
try
{
await host.LaunchInstanceAsync(imageId, numberOfInstances, maxIdleTimeSec);
}
catch (Exception e)
{
throw new WorkerHostException(e);
}
}
19
View Source File : WorkerHostService.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
public async Task TerminateInstanceAsync(string hostId, string instanceId)
{
var host = _hosts.Single(h => h.Id == hostId);
try
{
await host.TerminateInstanceAsync(instanceId);
}
catch (Exception e)
{
throw new WorkerHostException(e);
}
}
19
View Source File : DatabaseObjects.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private void button1_Click(object sender, EventArgs e)
{
foreach (TreeNode tableNode in triStateTreeView1.Nodes[0].Nodes)
{
if (!tableNode.Checked)
tables.Remove(tables.Single(t => t.Name == tableNode.Text));
}
foreach (TreeNode viewNode in triStateTreeView1.Nodes[1].Nodes)
{
if (!viewNode.Checked)
views.Remove(views.Single(v => v.Name == viewNode.Text));
}
this.DialogResult = DialogResult.OK;
}
19
View Source File : XmlUtilitiesTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[Test]
public void FindAvailableAppenderRefLocations_ShouldFindAppropriateRefs()
{
XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
xmlDoc.LoadXml("<log4net>\n" +
" <appender name=\"appender0\">\n" +
" <appender-ref ref=\"appender1\" />\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender1\">\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender2\">\n" +
" </appender>\n" +
" <appender name=\"appender3\">\n" +
" </appender>\n" +
" <appender name=\"asyncAppender\" type=\"Log4Net.Async.AsyncForwardingAppender,Log4Net.Async\">\n" +
" <appender-ref ref=\"appender0\" />\n" +
" </appender>\n" +
" <root>\n" +
" <appender-ref ref=\"asyncAppender\" />\n" +
" </root>\n" +
" <logger name=\"whatev\">\n" +
" </logger>\n" +
"</log4net>");
IEnumerable<IAcceptAppenderRef> refs = XmlUtilities.FindAvailableAppenderRefLocations(xmlDoc.FirstChild);
replacedert.AreEqual(3, refs.Count());
refs.Single(r => r.Node.Name == "root");
refs.Single(r => r.Node.Attributes?["type"]?.Value == AppenderDescriptor.Async.TypeNamespace);
refs.Single(r => r.Node.Name == "logger");
}
19
View Source File : XmlUtilitiesTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[Test]
public void FindAvailableAppenderRefLocations_ShouldFindAppropriateRefs()
{
XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
xmlDoc.LoadXml("<log4net>\n" +
" <appender name=\"appender0\">\n" +
" <appender-ref ref=\"appender1\" />\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender1\">\n" +
" <appender-ref ref=\"appender2\" />\n" +
" </appender>\n" +
" <appender name=\"appender2\">\n" +
" </appender>\n" +
" <appender name=\"appender3\">\n" +
" </appender>\n" +
" <appender name=\"asyncAppender\" type=\"Log4Net.Async.AsyncForwardingAppender,Log4Net.Async\">\n" +
" <appender-ref ref=\"appender0\" />\n" +
" </appender>\n" +
" <root>\n" +
" <appender-ref ref=\"asyncAppender\" />\n" +
" </root>\n" +
" <logger name=\"whatev\">\n" +
" </logger>\n" +
"</log4net>");
IEnumerable<IAcceptAppenderRef> refs = XmlUtilities.FindAvailableAppenderRefLocations(xmlDoc.FirstChild);
replacedert.AreEqual(3, refs.Count());
refs.Single(r => r.Node.Name == "root");
refs.Single(r => r.Node.Attributes?["type"]?.Value == AppenderDescriptor.Async.TypeNamespace);
refs.Single(r => r.Node.Name == "logger");
}
19
View Source File : TestHelpers.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
internal static void replacedertAppenderSkeletonPropertiesExist(IEnumerable<IProperty> properties)
{
//Single throws if the specified type is not found, which is good enough to fail the test
//No replacederts needed
properties.Single(p => p.GetType() == typeof(TypeAttribute));
properties.Single(p => p.GetType() == typeof(Name));
properties.Single(p => p.GetType() == typeof(StringValueProperty) && ((StringValueProperty)p).Name == "Error Handler:");
properties.Single(p => p.GetType() == typeof(Threshold));
properties.Single(p => p.GetType() == typeof(Layout));
properties.Single(p => p.GetType() == typeof(Editor.ConfigProperties.Filters));
properties.Single(p => p.GetType() == typeof(IncomingRefs));
properties.Single(p => p.GetType() == typeof(Params));
}
19
View Source File : TestHelpers.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
internal static void replacedertBufferingAppenderSkeletonPropertiesExist(IEnumerable<IProperty> properties)
{
//Single throws if the specified type is not found, which is good enough to fail the test
//No replacederts needed
properties.Single(p => p.GetType() == typeof(NumericProperty<int>));
properties.Single(p => p.GetType() == typeof(Fix));
properties.Single(p => p.GetType() == typeof(BooleanPropertyBase) && ((BooleanPropertyBase)p).Name == "Lossy:");
properties.Single(p => p.GetType() == typeof(StringValueProperty) && ((StringValueProperty)p).Name == "Evaluator:");
properties.Single(p => p.GetType() == typeof(StringValueProperty) && ((StringValueProperty)p).Name == "Lossy Evaluator:");
}
19
View Source File : AppenderDescriptorTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[TestCaseSource(nameof(sAppenderData))]
public void EachAppender_ShouldHaveCorrectAppenderField(string name, AppenderType type, string typeNamespace, string elementName)
{
mAppenders.Single(a => AreEqual((AppenderDescriptor)a.GetValue(null), name, type, typeNamespace, elementName));
}
19
View Source File : AppenderDescriptorTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[Test]
public void EachAppender_ShouldHaveTestData()
{
foreach (FieldInfo info in mAppenders)
{
sAppenderData.Single(f => AreEqual((AppenderDescriptor)info.GetValue(null), (string)f.Arguments[0], (AppenderType)f.Arguments[1], (string)f.Arguments[2], (string)f.Arguments[3]));
}
}
19
View Source File : FilterDescriptorTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[TestCaseSource(nameof(sFilterData))]
public void EachFilter_ShouldHaveCorrectFilterField(string name, FilterType type, string typeNamespace, string elementName)
{
mFilters.Single(f => AreEqual((FilterDescriptor)f.GetValue(null), name, type, typeNamespace, elementName));
}
19
View Source File : FilterDescriptorTest.cs
License : MIT License
Project Creator : alexleen
License : MIT License
Project Creator : alexleen
[Test]
public void EachFilter_ShouldHaveTestData()
{
foreach (FieldInfo info in mFilters)
{
sFilterData.Single(f => AreEqual((FilterDescriptor)info.GetValue(null), (string)f.Arguments[0], (FilterType)f.Arguments[1], (string)f.Arguments[2], (string)f.Arguments[3]));
}
}
19
View Source File : HardwareInfo.cs
License : Apache License 2.0
Project Creator : alexyakunin
License : Apache License 2.0
Project Creator : alexyakunin
public static int? GetRamSize()
{
try {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
var cmd = Command.Run("wmic", "computersystem", "get", "TotalPhysicalMemory");
var stringValue = cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
return (int) Math.Round(long.Parse(stringValue) / Sizes.GB);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
var cmd = Command.Run("cat", "/proc/meminfo");
var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
.ToPairs().Single(p => p.Name == "MemTotal")
.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
return (int) Math.Round(long.Parse(stringValue) * Sizes.KB / Sizes.GB);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
var cmd = Command.Run("system_profiler", "SPHardwareDataType");
var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
.ToPairs().Single(p => p.Name == "Memory")
.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
return (int) Math.Round(double.Parse(stringValue));
}
return null;
}
catch {
return null;
}
}
19
View Source File : CoursesControllerTests.cs
License : MIT License
Project Creator : alimon808
License : MIT License
Project Creator : alimon808
private List<Course> Courses()
{
return new List<Course>
{
new Course { ID = 1, CourseNumber = 1050, replacedle = "Chemistry", Credits = 3, DepartmentID = Departments().Single( s => s.Name == "Engineering").ID },
new Course { ID = 2, CourseNumber = 4022, replacedle = "Microeconomics", Credits = 3, DepartmentID = Departments().Single( s => s.Name == "Economics").ID },
new Course { ID = 3, CourseNumber = 4041, replacedle = "Macroeconomics", Credits = 3, DepartmentID = Departments().Single( s => s.Name == "Economics").ID },
new Course { ID = 4, CourseNumber = 1045, replacedle = "Calculus", Credits = 4, DepartmentID = Departments().Single( s => s.Name == "Mathematics").ID },
new Course { ID = 5, CourseNumber = 3141, replacedle = "Trigonometry", Credits = 4, DepartmentID = Departments().Single( s => s.Name == "Mathematics").ID },
new Course { ID = 6, CourseNumber = 2021, replacedle = "Composition", Credits = 3, DepartmentID = Departments().Single( s => s.Name == "English").ID },
new Course { ID = 7, CourseNumber = 2042, replacedle = "Literature", Credits = 4, DepartmentID = Departments().Single( s => s.Name == "English").ID }
};
}
See More Examples