Here are the examples of the csharp api System.Collections.Generic.List.Add(System.Collections.Generic.KeyValuePair) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1577 Examples
19
Source : Disassembler.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
formatterOutput.writer = output;
targets.Clear();
sortedTargets.Clear();
bool uppercaseHex = formatter.Options.UppercaseHex;
output.Write(commentPrefix);
output.WriteLine("================================================================================");
output.Write(commentPrefix);
output.WriteLine(method.MethodFullName);
uint codeSize = 0;
foreach (var info in method.Code)
codeSize += (uint)info.Code.Length;
var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
var instrCount = method.Instructions.Count;
var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");
void Add(ulong address, TargetKind kind) {
if (!targets.TryGetValue(address, out var addrInfo))
targets[address] = new AddressInfo(kind);
else if (addrInfo.Kind < kind)
addrInfo.Kind = kind;
}
if (method.Instructions.Count > 0)
Add(method.Instructions[0].IP, TargetKind.Unknown);
foreach (ref var instr in method.Instructions) {
switch (instr.FlowControl) {
case FlowControl.Next:
case FlowControl.Interrupt:
break;
case FlowControl.UnconditionalBranch:
Add(instr.NextIP, TargetKind.Unknown);
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.ConditionalBranch:
case FlowControl.XbeginXabortXend:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.Call:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Call);
break;
case FlowControl.IndirectBranch:
Add(instr.NextIP, TargetKind.Unknown);
// Unknown target
break;
case FlowControl.IndirectCall:
// Unknown target
break;
case FlowControl.Return:
case FlowControl.Exception:
Add(instr.NextIP, TargetKind.Unknown);
break;
default:
Debug.Fail($"Unknown flow control: {instr.FlowControl}");
break;
}
var baseReg = instr.MemoryBase;
if (baseReg == Register.RIP || baseReg == Register.EIP) {
int opCount = instr.OpCount;
for (int i = 0; i < opCount; i++) {
if (instr.GetOpKind(i) == OpKind.Memory) {
if (method.Contains(instr.IPRelativeMemoryAddress))
Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
break;
}
}
}
else if (instr.MemoryDisplSize >= 2) {
ulong displ;
switch (instr.MemoryDisplSize) {
case 2:
case 4: displ = instr.MemoryDisplacement; break;
case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
default:
Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
goto case 8;
}
if (method.Contains(displ))
Add(displ, TargetKind.Branch);
}
}
foreach (var map in method.ILMap) {
if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
info.Kind = TargetKind.BlockStart;
}
else
targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
if (info.ILOffset < 0)
info.ILOffset = map.ilOffset;
}
int labelIndex = 0, methodIndex = 0;
string GetLabel(int index) => LABEL_PREFIX + index.ToString();
string GetFunc(int index) => FUNC_PREFIX + index.ToString();
foreach (var kv in targets) {
if (method.Contains(kv.Key))
sortedTargets.Add(kv);
}
sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
foreach (var kv in sortedTargets) {
var address = kv.Key;
var info = kv.Value;
switch (info.Kind) {
case TargetKind.Unknown:
info.Name = null;
break;
case TargetKind.Data:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.BlockStart:
case TargetKind.Branch:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.Call:
info.Name = GetFunc(methodIndex++);
break;
default:
throw new InvalidOperationException();
}
}
foreach (ref var instr in method.Instructions) {
ulong ip = instr.IP;
if (targets.TryGetValue(ip, out var lblInfo)) {
output.WriteLine();
if (!(lblInfo.Name is null)) {
output.Write(lblInfo.Name);
output.Write(':');
output.WriteLine();
}
if (lblInfo.ILOffset >= 0) {
if (ShowSourceCode) {
foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
output.Write(commentPrefix);
var line = info.Line;
int column = commentPrefix.Length;
WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
output.WriteLine();
if (info.Partial) {
output.Write(commentPrefix);
column = commentPrefix.Length;
WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
output.WriteLine(new string('^', info.Span.Length));
}
}
}
}
}
if (ShowAddresses) {
var address = FormatAddress(bitness, ip, uppercaseHex);
output.Write(address);
output.Write(" ");
}
else
output.Write(formatter.Options.TabSize > 0 ? "\t\t" : " ");
if (ShowHexBytes) {
if (!method.TryGetCode(ip, out var nativeCode))
throw new InvalidOperationException();
var codeBytes = nativeCode.Code;
int index = (int)(ip - nativeCode.IP);
int instrLen = instr.Length;
for (int i = 0; i < instrLen; i++) {
byte b = codeBytes[index + i];
output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
}
int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
for (int i = 0; i < missingBytes; i++)
output.Write(" ");
output.Write(" ");
}
formatter.Format(instr, formatterOutput);
output.WriteLine();
}
}
19
Source : QueryParameters.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public string Add(object value)
{
var paramName = "P" + (_parameters.Count + 1);
_parameters.Add(new KeyValuePair<string, object>(paramName, value));
return paramName;
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static List<KeyValuePair<string, T>> MapToKvList<T>(this object[] list, Encoding encoding)
{
if (list == null) return null;
if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even");
var ret = new List<KeyValuePair<string, T>>();
for (var a = 0; a < list.Length; a += 2)
{
var key = list[a].ToInvariantCultureToString();
var val = list[a + 1];
if (val == null) ret.Add(new KeyValuePair<string, T>(key, default(T)));
else ret.Add(new KeyValuePair<string, T>(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding)));
}
return ret;
}
19
Source : EnumAppservice.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
private List<KeyValuePair<string, string>> GetEnumTypeList<T>()
{
var items = new List<KeyValuePair<string, string>>();
typeof(T).Each(
(name, value, description) => { items.Add(new KeyValuePair<string, string>(description, value)); });
return items;
}
19
Source : EnumAppservice.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
private List<KeyValuePair<string, int>> GetEnumTypeForIntList<T>()
{
var items = new List<KeyValuePair<string, int>>();
typeof(T).Each(
(name, value, description) => { items.Add(new KeyValuePair<string, int>(description, Convert.ToInt32(value))); });
return items;
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
bool GenerateCode() {
numInstructions = 0;
// first preplaced, can't update label addresses yet
for(int i = 0; i < instructions.Count; i++) {
Instruction instruction = instructions[i];
int additionalInstructions = instruction.AdditionalInstructions(true);
if(additionalInstructions != 0) {
instruction.additionalInstructions = new uint[additionalInstructions];
//todo: support more than int, uint, and float
instruction.additionalInstructions[0] = instruction.immediate.var.val32.Uint;
instruction.immediate.var.val32.Uint = GetMaxImmediateValue(instruction.operands.Count + 1);
}
instruction.address = numInstructions;
numInstructions += 1 + additionalInstructions;
instructions[i] = instruction;
}
int growth = 0;
for(int i = 0; i < instructions.Count; i++) {
Instruction instruction = instructions[i];
instruction.address += growth;
if(instruction.immediate.type == Symbol.Type.LABEL) {
uint maxValue = GetMaxImmediateValue(instruction.operands.Count + 1);
var immediate = instruction.immediate;
Instruction target = instructions[instruction.immediate.labelInstructionIndex];
if(target.address + growth >= maxValue) {
growth++;
numInstructions++;
instruction.additionalInstructions = new uint[1];
instruction.additionalInstructions[0] = (uint)(target.address + growth);
instruction.immediate.var.val32.Uint = maxValue;
} else {
instruction.immediate.var.val32.Int = target.address + growth;
}
if(!symbols.ContainsKey(instruction.immediate.name)) {
errors.Add($"missing symbol \"{instruction.immediate.name}\" (this should never happen)");
return false;
}
var symbol = symbols[instruction.immediate.name];
symbol.var.val32.Int = target.address + growth;
symbols[instruction.immediate.name] = symbol;
}
instructions[i] = instruction;
//Print($"{instruction.opcode} [{String.Join(", ", instruction.operands)}] {instruction.immediate.word.Uint} [{(instruction.additionalInstructions == null ? "" : String.Join(", ", instruction.additionalInstructions))}]");
}
List<KeyValuePair<string, Symbol>> changes = new List<KeyValuePair<string, Symbol>>();
foreach(var pair in symbols) {
Symbol symbol = pair.Value;
if(symbol.type == Symbol.Type.LABEL) {
int addr = instructions[symbol.labelInstructionIndex].address;
if(symbol.var.val32.Int != addr) {
symbol.var.val32.Int = addr;
changes.Add(new KeyValuePair<string, Symbol>(pair.Key, symbol));
}
}
}
foreach(var pair in changes) {
symbols[pair.Key] = pair.Value;
}
foreach(var pair in isrs) {
Symbol target = pair.Key;
Symbol replacement = pair.Value;
Instruction targetInstruction = instructions[target.labelInstructionIndex];
Instruction replacementInstruction = instructions[replacement.labelInstructionIndex];
if(targetInstruction.additionalInstructions != null) {
errors.Add($"isr \"{target.name}\" is broken, stub address is too large");
return false;
} else if(replacementInstruction.address >= GetMaxImmediateValue(1)) {
errors.Add($"isr \"{replacement.name}\" address is too large");
return false;
}
targetInstruction.immediate.var.val32.Int = replacementInstruction.address;
instructions[target.labelInstructionIndex] = targetInstruction;
}
return true;
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
bool Parse() {
AllocateRegisters();
numInstructions = 0;
for(int i = 0; i < statements.Count; i++) {
var statement = statements[i];
if(statement.tokens[0].type == Token.Type.LABEL) {
if(symbols.ContainsKey(statement.tokens[0].stringValue)) {
AddError(statement.lineNum, $"redefinition of identifier \"{statement.tokens[0].stringValue}\"");
return false;
} else {
symbols.Add(statement.tokens[0].stringValue, new Symbol {
name = statement.tokens[0].stringValue,
var = new Variable {
type = Variable.Type.NONE
},
labelInstructionIndex = numInstructions,
type = Symbol.Type.LABEL
});
}
} else if(statement.tokens[0].type == Token.Type.INSTRUCTION) {
numInstructions++;
}
}
for(int i = 0; i < statements.Count; i++) {
var statement = statements[i];
if(statement.tokens[0].type == Token.Type.DIRECTIVE) {
if(statement.tokens[0].stringValue == "const" || statement.tokens[0].stringValue == "word") {
if(statement.tokens.Length != 3 || statement.tokens[1].type != Token.Type.IDENTIFIER || (statement.tokens[2].type != Token.Type.INTEGER && statement.tokens[2].type != Token.Type.FLOAT)) {
AddError(statement.lineNum, $"invalid directive");
return false;
}
if(symbols.ContainsKey(statement.tokens[1].stringValue)) {
AddError(statement.lineNum, $"redefinition of identifier \"{statement.tokens[1].stringValue}\"");
return false;
} else {
if(statement.tokens[0].stringValue == "const") {
symbols.Add(statement.tokens[1].stringValue, new Symbol {
name = statement.tokens[1].stringValue,
var = statement.tokens[2].var,
type = Symbol.Type.CONSTANT
});
} else {
int addr = programData.Count;
AddData(statement.tokens[2].var, 4);
symbols.Add(statement.tokens[1].stringValue, new Symbol {
name = statement.tokens[1].stringValue,
var = new Variable{ val32 = new CPU.Value32{ Int = addr }},
type = Symbol.Type.CONSTANT
});
}
}
} else if(statement.tokens[0].stringValue == "isr") {
if(statement.tokens.Length != 3 || statement.tokens[1].type != Token.Type.IDENTIFIER ||statement.tokens[2].type != Token.Type.IDENTIFIER) {
AddError(statement.lineNum, $"invalid directive");
return false;
}
Symbol target;
Symbol replacement;
if(!symbols.TryGetValue(statement.tokens[1].stringValue, out target)) {
AddError(statement.lineNum, $"invalid isr directive, no symbol \"{statement.tokens[1].stringValue}\"");
return false;
} else if(target.type != Symbol.Type.LABEL) {
AddError(statement.lineNum, $"invalid isr directive, symbol \"{statement.tokens[1].stringValue}\" is not a label");
return false;
}
if(!symbols.TryGetValue(statement.tokens[2].stringValue, out replacement)) {
AddError(statement.lineNum, $"invalid isr directive, no symbol \"{statement.tokens[2].stringValue}\"");
return false;
} else if(replacement.type != Symbol.Type.LABEL) {
AddError(statement.lineNum, $"invalid isr directive, symbol \"{statement.tokens[2].stringValue}\" is not a label");
return false;
}
isrs.Add(new KeyValuePair<Symbol, Symbol>(target, replacement));
} else {
AddError(statement.lineNum, $"unknown directive \"{statement.tokens[0].stringValue}\"");
return false;
}
} else if(statement.tokens[0].type == Token.Type.INSTRUCTION) {
var instruction = new Instruction {
opcode = 0,
cond = 0,
operands = new List<CPU.Register>(),
address = 0,
additionalInstructions = null,
immediate = new Symbol {
var = new Variable{ type = Variable.Type.NONE },
type = Symbol.Type.NONE
}
};
if(!TryStringToOpcode(statement.tokens[0].stringValue, out instruction.opcode)) {
AddError(statement.lineNum, $"unknown opcode \"{statement.tokens[0].stringValue}\"");
return false;
}
if(!TryStringToCond(statement.tokens[0].cond, out instruction.cond)) {
AddError(statement.lineNum, $"unknown condition \"{statement.tokens[0].cond}\"");
return false;
}
for(int j = 1; j < statement.tokens.Length; j++) {
if(statement.tokens[j].type == Token.Type.IDENTIFIER) {
Symbol symbol;
if(!symbols.TryGetValue(statement.tokens[j].stringValue, out symbol)) {
AddError(statement.lineNum, $"unknown identifier \"{statement.tokens[j].stringValue}\"");
return false;
}
if(symbol.type == Symbol.Type.REGISTER) {
instruction.operands.Add((CPU.Register)symbol.var.val32.Uint);
} else {
instruction.immediate = symbol;
}
} else if(statement.tokens[j].type == Token.Type.INTEGER || statement.tokens[j].type == Token.Type.FLOAT) {
instruction.immediate = new Symbol {
var = statement.tokens[j].var,
type = Symbol.Type.LITERAL
};
} else {
AddError(statement.lineNum, $"invalid instruction argument \"{statement.tokens[j].stringValue}\"");
return false;
}
}
instructions.Add(instruction);
}
}
return true;
}
19
Source : Amf0Reader.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public bool TryGetPacket(Span<byte> buffer, out List<KeyValuePair<string, object>> headers, out List<Message> messages, out int consumed)
{
headers = default;
messages = default;
consumed = 0;
if (buffer.Length < 1)
{
return false;
}
var version = NetworkBitConverter.ToUInt16(buffer);
buffer = buffer.Slice(sizeof(ushort));
consumed += sizeof(ushort);
var headerCount = NetworkBitConverter.ToUInt16(buffer);
buffer = buffer.Slice(sizeof(ushort));
consumed += sizeof(ushort);
headers = new List<KeyValuePair<string, object>>();
messages = new List<Message>();
for (int i = 0; i < headerCount; i++)
{
if (!TryReadHeader(buffer, out var header, out var headerConsumed))
{
return false;
}
headers.Add(header);
buffer = buffer.Slice(headerConsumed);
consumed += headerConsumed;
}
var messageCount = NetworkBitConverter.ToUInt16(buffer);
buffer = buffer.Slice(sizeof(ushort));
consumed += sizeof(ushort);
for (int i = 0; i < messageCount; i++)
{
if (!TryGetMessage(buffer, out var message, out var messageConsumed))
{
return false;
}
messages.Add(message);
consumed += messageConsumed;
}
return true;
}
19
Source : HuobiAPI.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private string DoMethod2(string method, NameValueCollection jParams)
{
// add some more args for authentication
var seconds = UnixTime.GetFromDateTime(DateTime.UtcNow);
var args = new NameValueDictionary
{
{"created", seconds.ToString(CultureInfo.InvariantCulture)},
{"access_key", m_accessKey},
{"method", method},
{"secret_key", m_secretKey}
};
if (jParams != null)
{
foreach (var key in jParams.AllKeys)
{
args.Add(key, jParams[key]);
}
}
var argsSortedByKey = args.OrderBy(kvp => kvp.Key).ToList();
var sign = GetSignature(argsSortedByKey);
argsSortedByKey.Add( new KeyValuePair<string, string>("sign", sign));
var httpContent = new FormUrlEncodedContent(argsSortedByKey);
var response = WebApi.Client.PostAsync("apiv3/" + method, httpContent).Result;
var resultString = response.Content.ReadreplacedtringAsync().Result;
if (resultString.Contains("code"))
{
var error = JsonConvert.DeserializeObject<HuobiError>(resultString);
throw new HuobiException(method, "Request failed with code: " + error.Code);
}
return resultString;
}
19
Source : RepositoryIntegrationTest.cs
with MIT License
from abelperezok
with MIT License
from abelperezok
[Fact]
public async void TestBatchOperations_IndependentEnreplacedyRepository()
{
var repo = new TestIndependentEnreplacedyRepo(_tableName, _serviceUrl);
var itemsToCreate = new List<KeyValuePair<string, TestEnreplacedy>>();
for (int i = 50; i < 60; i++)
{
var te = new TestEnreplacedy { Id = "TE" + i, Name = "TestEnreplacedy TE" + i };
itemsToCreate.Add(new KeyValuePair<string, TestEnreplacedy>(te.Id, te));
}
await repo.BatchAddItemsAsync(itemsToCreate);
var list = await repo.GSI1QueryAllAsync();
replacedert.Equal(10, list.Count);
for (int i = 0; i < 10; i++)
{
var item = list[i];
var id = i + 50;
replacedert.NotNull(item);
replacedert.Equal("TE" + id, item.Id);
replacedert.Equal("TestEnreplacedy TE" + id, item.Name);
}
var itemsToDelete = new List<string>();
for (int i = 50; i < 60; i++)
{
var te = new TestEnreplacedy { Id = "TE" + i };
itemsToDelete.Add(te.Id);
}
await repo.BatchDeleteItemsAsync(itemsToDelete);
var emptyList = await repo.GSI1QueryAllAsync();
replacedert.Empty(emptyList);
}
19
Source : RepositoryIntegrationTest.cs
with MIT License
from abelperezok
with MIT License
from abelperezok
[Fact]
public async void TestBatchOperations_DependentEnreplacedyRepository()
{
var parent = new TestEnreplacedy { Id = "PTE1" };
var repo = new TestDependentEnreplacedyRepo(_tableName, _serviceUrl);
var itemsToCreate = new List<KeyValuePair<string, TestEnreplacedy>>();
for (int i = 50; i < 60; i++)
{
var te = new TestEnreplacedy { Id = "TE" + i, Name = "TestEnreplacedy TE" + i };
itemsToCreate.Add(new KeyValuePair<string, TestEnreplacedy>(te.Id, te));
}
await repo.BatchAddItemsAsync(parent.Id, itemsToCreate);
var list = await repo.TableQueryItemsByParentIdAsync(parent.Id);
replacedert.Equal(10, list.Count);
for (int i = 0; i < 10; i++)
{
var item = list[i];
var id = i + 50;
replacedert.NotNull(item);
replacedert.Equal("TE" + id, item.Id);
replacedert.Equal("TestEnreplacedy TE" + id, item.Name);
}
var itemsToDelete = new List<string>();
for (int i = 50; i < 60; i++)
{
var te = new TestEnreplacedy { Id = "TE" + i };
itemsToDelete.Add(te.Id);
}
await repo.BatchDeleteItemsAsync(parent.Id, itemsToDelete);
var emptyList = await repo.TableQueryItemsByParentIdAsync(parent.Id);
replacedert.Empty(emptyList);
}
19
Source : MeshSmoother.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static List<Vector3> CalculateSmoothNormals(Vector3[] vertices, Vector3[] normals)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
// Group all vertices that share the same location in space.
var groupedVerticies = new Dictionary<Vector3, List<KeyValuePair<int, Vector3>>>();
for (int i = 0; i < vertices.Length; ++i)
{
var vertex = vertices[i];
List<KeyValuePair<int, Vector3>> group;
if (!groupedVerticies.TryGetValue(vertex, out group))
{
group = new List<KeyValuePair<int, Vector3>>();
groupedVerticies[vertex] = group;
}
group.Add(new KeyValuePair<int, Vector3>(i, vertex));
}
var smoothNormals = new List<Vector3>(normals);
// If we don't hit the degenerate case of each vertex is it's own group (no vertices shared a location), average the normals of each group.
if (groupedVerticies.Count != vertices.Length)
{
foreach (var group in groupedVerticies)
{
var smoothingGroup = group.Value;
// No need to smooth a group of one.
if (smoothingGroup.Count != 1)
{
var smoothedNormal = Vector3.zero;
foreach (var vertex in smoothingGroup)
{
smoothedNormal += normals[vertex.Key];
}
smoothedNormal.Normalize();
foreach (var vertex in smoothingGroup)
{
smoothNormals[vertex.Key] = smoothedNormal;
}
}
}
}
Debug.LogFormat("CalculateSmoothNormals took {0} ms on {1} vertices.", watch.ElapsedMilliseconds, vertices.Length);
return smoothNormals;
}
19
Source : MixedRealityServiceRegistry.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static bool AddService<T>(T serviceInstance, IMixedRealityServiceRegistrar registrar) where T : IMixedRealityService
{
if (serviceInstance == null)
{
// Adding a null service instance is not supported.
return false;
}
if (serviceInstance is IMixedRealityDataProvider)
{
// Data providers are generally not used by application code. Services that intend for clients to
// directly communicate with their data providers will expose a GetDataProvider or similarly named
// method.
return false;
}
Type interfaceType = typeof(T);
T existingService;
if (TryGetService<T>(out existingService, serviceInstance.Name))
{
return false;
}
// Ensure we have a place to put our newly registered service.
if (!registry.ContainsKey(interfaceType))
{
registry.Add(interfaceType, new List<KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>>());
}
List<KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>> services = registry[interfaceType];
services.Add(new KeyValuePair<IMixedRealityService, IMixedRealityServiceRegistrar>(serviceInstance, registrar));
AddServiceToCache(serviceInstance, registrar);
return true;
}
19
Source : FileCache.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
public IEnumerator<KeyValuePair<string, object>> GetEnumerator(string regionName = null)
{
string region = "";
if (string.IsNullOrEmpty(regionName) == false)
{
region = regionName;
}
//AC: This seems inefficient. Wouldn't it be better to do this using a cursor?
List<KeyValuePair<string, object>> enumerator = new List<KeyValuePair<string, object>>();
var keys = CacheManager.GetKeys(regionName);
foreach (string key in keys)
{
enumerator.Add(new KeyValuePair<string, object>(key, this.Get(key, regionName)));
}
return enumerator.GetEnumerator();
}
19
Source : AppleRestClient.cs
with MIT License
from Accedia
with MIT License
from Accedia
internal HttpRequestMessage GenerateRequestMessage(string tokenType, string authorizationCode, string clientSecret, string clientId, string redirectUrl)
{
var bodyAsPairs = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("grant_type", tokenType),
new KeyValuePair<string, string>("redirect_uri", redirectUrl)
};
if (tokenType == TokenType.RefreshToken)
bodyAsPairs.Add(new KeyValuePair<string, string>("refresh_token", authorizationCode));
else
bodyAsPairs.Add(new KeyValuePair<string, string>("code", authorizationCode));
var content = new FormUrlEncodedContent(bodyAsPairs);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
return new HttpRequestMessage(HttpMethod.Post, GlobalConstants.AppleAuthorizeTokenURL) { Content = content };
}
19
Source : DetailViewModelConverters.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
public static DetailViewModel ToDetailViewModel(this ActivatedFeature vm)
{
string displayName = vm.DisplayName;
var items = new List<KeyValuePair<string, string>>();
items.Add(new KeyValuePair<string, string>(nameof(vm.DisplayName), vm.DisplayName));
items.Add(new KeyValuePair<string, string>(nameof(vm.FeatureId), vm.FeatureId.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.LocationId), vm.LocationId.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.FeatureDefinitionScope), vm.FeatureDefinitionScope.ToString()));
items.Add(new KeyValuePair<string, string>("DefinitionVersion", vm.DefinitionVersion == null ? string.Empty : vm.DefinitionVersion.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Version), vm.Version.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.CanUpgrade), vm.CanUpgrade.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.TimeActivated), vm.TimeActivated.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(Properties), PropertiesToString(vm.Properties)));
items.Add(new KeyValuePair<string, string>(nameof(vm.Faulty), vm.Faulty.ToString()));
var dvm = new DetailViewModel(displayName, items);
return dvm;
}
19
Source : DetailViewModelConverters.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
public static DetailViewModel ToDetailViewModel(this FeatureDefinition vm, IEnumerable<ActivatedFeature> activatedFeatures)
{
string displayName = vm.DisplayName;
if (activatedFeatures == null)
{
activatedFeatures = new List<ActivatedFeature>();
}
var items = new List<KeyValuePair<string, string>>();
items.Add(new KeyValuePair<string, string>(nameof(vm.DisplayName), vm.DisplayName));
items.Add(new KeyValuePair<string, string>(nameof(vm.UniqueIdentifier), vm.UniqueIdentifier));
items.Add(new KeyValuePair<string, string>(nameof(vm.Id), vm.Id.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Scope), vm.Scope.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.replacedle), vm.replacedle));
items.Add(new KeyValuePair<string, string>(nameof(vm.Name), vm.Name));
items.Add(new KeyValuePair<string, string>(nameof(vm.CompatibilityLevel), vm.CompatibilityLevel.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Description), vm.Description));
items.Add(new KeyValuePair<string, string>(nameof(vm.Hidden), vm.Hidden.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.SolutionId), vm.SolutionId.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.UIVersion), vm.UIVersion.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Version), vm.Version == null ? string.Empty : vm.Version.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.SandBoxedSolutionLocation), vm.SandBoxedSolutionLocation));
items.Add(new KeyValuePair<string, string>(nameof(vm.Properties), PropertiesToString(vm.Properties)));
items.Add(new KeyValuePair<string, string>("Times Activated in Farm", activatedFeatures.Count().ToString()));
items.Add(ConvertActivatedFeatures(activatedFeatures, true));
var dvm = new DetailViewModel(displayName, items);
return dvm;
}
19
Source : DetailViewModelConverters.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
public static DetailViewModel ToDetailViewModel(this Location vm, IEnumerable<ActivatedFeature> activatedFeatures)
{
string displayName = vm.DisplayName;
if (activatedFeatures == null)
{
activatedFeatures = new List<ActivatedFeature>();
}
var items = new List<KeyValuePair<string, string>>();
items.Add(new KeyValuePair<string, string>(nameof(vm.DisplayName), vm.DisplayName));
items.Add(new KeyValuePair<string, string>(nameof(Core.Common.Constants.Labels.UniqueLocationId), vm.Id.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Scope), vm.Scope.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.Url), vm.Url));
items.Add(new KeyValuePair<string, string>(nameof(vm.DataBaseId), vm.DataBaseId == null? string.Empty : vm.DataBaseId.ToString()));
items.Add(new KeyValuePair<string, string>(nameof(vm.ChildCount), vm.ChildCount.ToString()));
items.Add(new KeyValuePair<string, string>(Core.Common.Constants.Labels.NumberOfActivatedFeatures, activatedFeatures.Count().ToString()));
items.Add(ConvertActivatedFeatures(activatedFeatures, false));
if (!string.IsNullOrEmpty(vm.ParentId))
{
items.Add(new KeyValuePair<string, string>(nameof(vm.ParentId), string.Format("Location Id: {0}", vm.ParentId.ToString())));
}
var dvm = new DetailViewModel(displayName, items);
return dvm;
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<TaskAgent> GetAgentAsync(
int poolId,
int agentId,
bool? includeCapabilities = null,
bool? includereplacedignedRequest = null,
bool? includeLastCompletedRequest = null,
IEnumerable<string> propertyFilters = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("e298ef32-5878-4cab-993c-043836571f42");
object routeValues = new { poolId = poolId, agentId = agentId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (includeCapabilities != null)
{
queryParams.Add("includeCapabilities", includeCapabilities.Value.ToString());
}
if (includereplacedignedRequest != null)
{
queryParams.Add("includereplacedignedRequest", includereplacedignedRequest.Value.ToString());
}
if (includeLastCompletedRequest != null)
{
queryParams.Add("includeLastCompletedRequest", includeLastCompletedRequest.Value.ToString());
}
if (propertyFilters != null && propertyFilters.Any())
{
queryParams.Add("propertyFilters", string.Join(",", propertyFilters));
}
return SendAsync<TaskAgent>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(6.0, 2),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<List<TaskAgent>> GetAgentsAsync(
int poolId,
string agentName = null,
bool? includeCapabilities = null,
bool? includereplacedignedRequest = null,
bool? includeLastCompletedRequest = null,
IEnumerable<string> propertyFilters = null,
IEnumerable<string> demands = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("e298ef32-5878-4cab-993c-043836571f42");
object routeValues = new { poolId = poolId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (agentName != null)
{
queryParams.Add("agentName", agentName);
}
if (includeCapabilities != null)
{
queryParams.Add("includeCapabilities", includeCapabilities.Value.ToString());
}
if (includereplacedignedRequest != null)
{
queryParams.Add("includereplacedignedRequest", includereplacedignedRequest.Value.ToString());
}
if (includeLastCompletedRequest != null)
{
queryParams.Add("includeLastCompletedRequest", includeLastCompletedRequest.Value.ToString());
}
if (propertyFilters != null && propertyFilters.Any())
{
queryParams.Add("propertyFilters", string.Join(",", propertyFilters));
}
if (demands != null && demands.Any())
{
queryParams.Add("demands", string.Join(",", demands));
}
return SendAsync<List<TaskAgent>>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(6.0, 2),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TemplateSchema.cs
with MIT License
from actions
with MIT License
from actions
private void Validate()
{
var oneOfPairs = new List<KeyValuePair<String, OneOfDefinition>>();
foreach (var pair in Definitions)
{
var name = pair.Key;
if (!s_definitionNameRegex.IsMatch(name ?? String.Empty))
{
throw new ArgumentException($"Invalid definition name '{name}'");
}
var definition = pair.Value;
// Delay validation for 'one-of' definitions
if (definition is OneOfDefinition oneOf)
{
oneOfPairs.Add(new KeyValuePair<String, OneOfDefinition>(name, oneOf));
}
// Otherwise validate now
else
{
definition.Validate(this, name);
}
}
// Validate 'one-of' definitions
foreach (var pair in oneOfPairs)
{
var name = pair.Key;
var oneOf = pair.Value;
oneOf.Validate(this, name);
}
}
19
Source : MappingToken.cs
with MIT License
from actions
with MIT License
from actions
public void Add(KeyValuePair<ScalarToken, TemplateToken> item)
{
if (m_items == null)
{
m_items = new List<KeyValuePair<ScalarToken, TemplateToken>>();
}
m_items.Add(item);
m_dictionary = null;
}
19
Source : PipelineTemplateConverter.cs
with MIT License
from actions
with MIT License
from actions
internal static List<KeyValuePair<String, JobContainer>> ConvertToJobServiceContainers(
TemplateContext context,
TemplateToken services,
bool allowExpressions = false)
{
var result = new List<KeyValuePair<String, JobContainer>>();
if (allowExpressions && services.Traverse().Any(x => x is ExpressionToken))
{
return result;
}
var servicesMapping = services.replacedertMapping("services");
foreach (var servicePair in servicesMapping)
{
var networkAlias = servicePair.Key.replacedertString("services key").Value;
var container = ConvertToJobContainer(context, servicePair.Value);
result.Add(new KeyValuePair<String, JobContainer>(networkAlias, container));
}
return result;
}
19
Source : PipelinesHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<Artifact> GetArtifactAsync(
string project,
int pipelineId,
int runId,
string artifactName,
GetArtifactExpandOptions? expand = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("85023071-bd5e-4438-89b0-2a5bf362a19d");
object routeValues = new { project = project, pipelineId = pipelineId, runId = runId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("artifactName", artifactName);
if (expand != null)
{
queryParams.Add("$expand", expand.Value.ToString());
}
return SendAsync<Artifact>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(6.0, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : PipelinesHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<Artifact> GetArtifactAsync(
Guid project,
int pipelineId,
int runId,
string artifactName,
GetArtifactExpandOptions? expand = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("85023071-bd5e-4438-89b0-2a5bf362a19d");
object routeValues = new { project = project, pipelineId = pipelineId, runId = runId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("artifactName", artifactName);
if (expand != null)
{
queryParams.Add("$expand", expand.Value.ToString());
}
return SendAsync<Artifact>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(6.0, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : PipelinesHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<Artifact> GetArtifactAsync(
int pipelineId,
int runId,
string artifactName,
GetArtifactExpandOptions? expand = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("85023071-bd5e-4438-89b0-2a5bf362a19d");
object routeValues = new { pipelineId = pipelineId, runId = runId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("artifactName", artifactName);
if (expand != null)
{
queryParams.Add("$expand", expand.Value.ToString());
}
return SendAsync<Artifact>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(6.0, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual async Task DeleteAgentRequestAsync(
int poolId,
long requestId,
Guid lockToken,
TaskResult? result = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("DELETE");
Guid locationId = new Guid("fc825784-c92a-4299-9221-998a02d1b54f");
object routeValues = new { poolId = poolId, requestId = requestId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("lockToken", lockToken.ToString());
if (result != null)
{
queryParams.Add("result", result.Value.ToString());
}
using (HttpResponseMessage response = await SendAsync(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken).ConfigureAwait(false))
{
return;
}
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<TaskAgentJobRequest> GetAgentRequestAsync(
int poolId,
long requestId,
bool? includeStatus = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("fc825784-c92a-4299-9221-998a02d1b54f");
object routeValues = new { poolId = poolId, requestId = requestId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (includeStatus != null)
{
queryParams.Add("includeStatus", includeStatus.Value.ToString());
}
return SendAsync<TaskAgentJobRequest>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<TaskAgentJobRequest> UpdateAgentRequestAsync(
int poolId,
long requestId,
Guid lockToken,
TaskAgentJobRequest request,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("PATCH");
Guid locationId = new Guid("fc825784-c92a-4299-9221-998a02d1b54f");
object routeValues = new { poolId = poolId, requestId = requestId };
HttpContent content = new ObjectContent<TaskAgentJobRequest>(request, new VssJsonMediaTypeFormatter(true));
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("lockToken", lockToken.ToString());
return SendAsync<TaskAgentJobRequest>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken,
content: content);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual async Task DeleteMessageAsync(
int poolId,
long messageId,
Guid sessionId,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("DELETE");
Guid locationId = new Guid("c3a054f6-7a8a-49c0-944e-3a8e5d7adfd7");
object routeValues = new { poolId = poolId, messageId = messageId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("sessionId", sessionId.ToString());
using (HttpResponseMessage response = await SendAsync(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken).ConfigureAwait(false))
{
return;
}
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<TaskAgentMessage> GetMessageAsync(
int poolId,
Guid sessionId,
long? lastMessageId = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("c3a054f6-7a8a-49c0-944e-3a8e5d7adfd7");
object routeValues = new { poolId = poolId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("sessionId", sessionId.ToString());
if (lastMessageId != null)
{
queryParams.Add("lastMessageId", lastMessageId.Value.ToString(CultureInfo.InvariantCulture));
}
return SendAsync<TaskAgentMessage>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual async Task RefreshAgentAsync(
int poolId,
int agentId,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("POST");
Guid locationId = new Guid("c3a054f6-7a8a-49c0-944e-3a8e5d7adfd7");
object routeValues = new { poolId = poolId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("agentId", agentId.ToString(CultureInfo.InvariantCulture));
using (HttpResponseMessage response = await SendAsync(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken).ConfigureAwait(false))
{
return;
}
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual async Task SendMessageAsync(
int poolId,
long requestId,
TaskAgentMessage message,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("POST");
Guid locationId = new Guid("c3a054f6-7a8a-49c0-944e-3a8e5d7adfd7");
object routeValues = new { poolId = poolId };
HttpContent content = new ObjectContent<TaskAgentMessage>(message, new VssJsonMediaTypeFormatter(true));
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("requestId", requestId.ToString(CultureInfo.InvariantCulture));
using (HttpResponseMessage response = await SendAsync(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken,
content: content).ConfigureAwait(false))
{
return;
}
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<PackageMetadata> GetPackageAsync(
string packageType,
string platform,
string version,
bool? includeToken = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("8ffcd551-079c-493a-9c02-54346299d144");
object routeValues = new { packageType = packageType, platform = platform, version = version };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (includeToken != null)
{
queryParams.Add("includeToken", includeToken.Value.ToString());
}
return SendAsync<PackageMetadata>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 2),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<List<PackageMetadata>> GetPackagesAsync(
string packageType,
string platform = null,
int? top = null,
bool? includeToken = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("8ffcd551-079c-493a-9c02-54346299d144");
object routeValues = new { packageType = packageType, platform = platform };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (top != null)
{
queryParams.Add("$top", top.Value.ToString(CultureInfo.InvariantCulture));
}
if (includeToken != null)
{
queryParams.Add("includeToken", includeToken.Value.ToString());
}
return SendAsync<List<PackageMetadata>>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 2),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<List<TaskAgentPool>> GetAgentPoolsAsync(
string poolName = null,
IEnumerable<string> properties = null,
TaskAgentPoolType? poolType = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("a8c47e17-4d56-4a56-92bb-de7ea7dc65be");
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (poolName != null)
{
queryParams.Add("poolName", poolName);
}
if (properties != null && properties.Any())
{
queryParams.Add("properties", string.Join(",", properties));
}
if (poolType != null)
{
queryParams.Add("poolType", poolType.Value.ToString());
}
return SendAsync<List<TaskAgentPool>>(
httpMethod,
locationId,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskAgentHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual Task<TaskAgent> UpdateAgentUpdateStateAsync(
int poolId,
int agentId,
string currentState,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("PUT");
Guid locationId = new Guid("8cc1b02b-ae49-4516-b5ad-4f9b29967c30");
object routeValues = new { poolId = poolId, agentId = agentId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("currentState", currentState);
return SendAsync<TaskAgent>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : TaskHttpClientBase.cs
with MIT License
from actions
with MIT License
from actions
public virtual Task<Timeline> GetTimelineAsync(
Guid scopeIdentifier,
string hubName,
Guid planId,
Guid timelineId,
int? changeId = null,
bool? includeRecords = null,
object userState = null,
CancellationToken cancellationToken = default)
{
HttpMethod httpMethod = new HttpMethod("GET");
Guid locationId = new Guid("83597576-cc2c-453c-bea6-2882ae6a1653");
object routeValues = new { scopeIdentifier = scopeIdentifier, hubName = hubName, planId = planId, timelineId = timelineId };
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
if (changeId != null)
{
queryParams.Add("changeId", changeId.Value.ToString(CultureInfo.InvariantCulture));
}
if (includeRecords != null)
{
queryParams.Add("includeRecords", includeRecords.Value.ToString());
}
return SendAsync<Timeline>(
httpMethod,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken);
}
19
Source : FileContainerHttpClient.cs
with MIT License
from actions
with MIT License
from actions
private List<KeyValuePair<String, String>> AppendItemQueryString(String itemPath, Guid scopeIdentifier, Boolean includeDownloadTickets = false, Boolean isShallow = false)
{
List<KeyValuePair<String, String>> collection = new List<KeyValuePair<String, String>>();
if (!String.IsNullOrEmpty(itemPath))
{
itemPath = FileContainerItem.EnsurePathFormat(itemPath);
collection.Add(QueryParameters.ItemPath, itemPath);
}
if (includeDownloadTickets)
{
collection.Add(QueryParameters.includeDownloadTickets, "true");
}
if (isShallow)
{
collection.Add(QueryParameters.isShallow, "true");
}
collection.Add(QueryParameters.ScopeIdentifier, scopeIdentifier.ToString());
return collection;
}
19
Source : LocationHttpClient.cs
with MIT License
from actions
with MIT License
from actions
[EditorBrowsable(EditorBrowsableState.Never)]
public async Task<ServiceDefinition> GetServiceDefinitionAsync(String serviceType, Guid identifier, Boolean allowFaultIn, Boolean previewFaultIn, CancellationToken cancellationToken = default(CancellationToken))
{
using (new OperationScope(LocationResourceIds.LocationServiceArea, "GetServiceDefinitions"))
{
List<KeyValuePair<String, String>> query = new List<KeyValuePair<String, String>>();
if (!allowFaultIn)
{
query.Add("allowFaultIn", Boolean.FalseString);
}
if (previewFaultIn)
{
if (!allowFaultIn)
{
throw new InvalidOperationException("Cannot preview a service definition fault in if we do not allow the fault in.");
}
query.Add("previewFaultIn", Boolean.TrueString);
}
return await SendAsync<ServiceDefinition>(HttpMethod.Get, LocationResourceIds.ServiceDefinitions, new { serviceType = serviceType, identifier = identifier }, s_currentApiVersion, queryParameters: query, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
19
Source : TaskAgentHttpClient.cs
with MIT License
from actions
with MIT License
from actions
public Task<TaskAgentJobRequest> RenewAgentRequestAsync(
Int32 poolId,
Int64 requestId,
Guid lockToken,
DateTime? expiresOn = null,
string orchestrationId = null,
Object userState = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var request = new TaskAgentJobRequest
{
RequestId = requestId,
LockedUntil = expiresOn,
};
var additionalHeaders = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(orchestrationId))
{
additionalHeaders["X-VSS-OrchestrationId"] = orchestrationId;
}
HttpMethod httpMethod = new HttpMethod("PATCH");
Guid locationId = new Guid("fc825784-c92a-4299-9221-998a02d1b54f");
object routeValues = new { poolId = poolId, requestId = requestId };
HttpContent content = new ObjectContent<TaskAgentJobRequest>(request, new VssJsonMediaTypeFormatter(true));
List<KeyValuePair<string, string>> queryParams = new List<KeyValuePair<string, string>>();
queryParams.Add("lockToken", lockToken.ToString());
return SendAsync<TaskAgentJobRequest>(
httpMethod,
additionalHeaders,
locationId,
routeValues: routeValues,
version: new ApiResourceVersion(5.1, 1),
queryParameters: queryParams,
userState: userState,
cancellationToken: cancellationToken,
content: content);
}
19
Source : POParser.cs
with MIT License
from adams85
with MIT License
from adams85
private void SeekNextToken()
{
if (_line != null && (_columnIndex = FindNextTokenInLine()) >= 0)
return;
_commentBuffer?.Clear();
while (true)
{
_line = _reader.ReadLine();
_lineIndex++;
_columnIndex = 0;
if (_line == null)
return;
_columnIndex = FindNextTokenInLine();
if (_columnIndex >= 0)
if (_line[_columnIndex] != '#')
return;
else
_commentBuffer?.Add(new KeyValuePair<TextLocation, string>(
new TextLocation(_lineIndex, _columnIndex),
_line.Substring(_columnIndex + 1)));
}
}
19
Source : DBEngine.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
internal List<KeyValuePair<long, string>> GetListKVLongStringCommand(string sql, params KeyValuePair<string, object>[] parameteres)
{
List<KeyValuePair<long, string>> valuesList = new List<KeyValuePair<long, string>>();
try
{
using (var command = new SqliteCommand(sql, _mDbConnection))
{
foreach (var param in parameteres)
command.Parameters.Add(new SqliteParameter(param.Key, param.Value));
using (var reader = command.ExecuteReader())
while (reader.Read())
valuesList.Add(new KeyValuePair<long, string>(reader.GetInt64(0), reader.GetString(1)));
}
return valuesList;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return valuesList;
}
}
19
Source : EntityActivityController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<KeyValuePair<string, object>> FlattenAllPartiesAttribute(KeyValuePair<string, object> attribute)
{
var attributeCollection = new List<KeyValuePair<string, object>> { };
var toRecipients = new List<EnreplacedyReference>();
var ccRecipients = new List<EnreplacedyReference>();
var requiredAttendees = new List<EnreplacedyReference>();
if (attribute.Key.Equals("allparties"))
{
// Iterate through each enreplacedy in allparties and replacedign to Sender, To, or CC
foreach (var enreplacedy in ((EnreplacedyCollection)attribute.Value).Enreplacedies.Where(enreplacedy => enreplacedy.Attributes.ContainsKey("participationtypemask") && enreplacedy.Attributes.ContainsKey("partyid")))
{
switch (enreplacedy.GetAttributeValue<OptionSetValue>("participationtypemask").Value)
{
// Sender or Organizer should be represented as "from"
case (int)Activity.ParticipationTypeMaskOptionSetValue.Sender:
case (int)Activity.ParticipationTypeMaskOptionSetValue.Organizer:
attributeCollection.Add(new KeyValuePair<string, object>("from", enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid")));
break;
case (int)Activity.ParticipationTypeMaskOptionSetValue.ToRecipient:
toRecipients.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
break;
case (int)Activity.ParticipationTypeMaskOptionSetValue.CcRecipient:
ccRecipients.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
break;
case (int)Activity.ParticipationTypeMaskOptionSetValue.RequiredAttendee:
requiredAttendees.Add(enreplacedy.GetAttributeValue<EnreplacedyReference>("partyid"));
break;
}
}
// flatten lists for to and cc recipient
if (toRecipients.Any())
{
attributeCollection.Add(new KeyValuePair<string, object>("to", toRecipients));
}
if (ccRecipients.Any())
{
attributeCollection.Add(new KeyValuePair<string, object>("cc", ccRecipients));
}
if (requiredAttendees.Any())
{
attributeCollection.Add(new KeyValuePair<string, object>("requiredattendees", requiredAttendees));
}
}
else
{
attributeCollection.Add(attribute);
}
return attributeCollection;
}
19
Source : LocationPatches.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void MakeSpouseRoom(FarmHouse fh, HashSet<string> appliedMapOverrides, SpouseRoomData srd, bool first = false)
{
Monitor.Log($"Loading spouse room for {srd.name}. shellStart {srd.startPos}, spouse offset {srd.spousePosOffset}. Type: {srd.shellType}");
var corner = srd.startPos + new Point(1, 1);
var spouse = srd.name;
var shellPath = srd.shellType;
var indexInSpouseMapSheet = srd.templateIndex;
var spouseSpot = srd.startPos + srd.spousePosOffset;
Rectangle shellAreaToRefurbish = new Rectangle(corner.X - 1, corner.Y - 1, 8, 12);
Misc.ExtendMap(fh, shellAreaToRefurbish.X + shellAreaToRefurbish.Width, shellAreaToRefurbish.Y + shellAreaToRefurbish.Height);
// load shell
if (appliedMapOverrides.Contains("spouse_room_" + spouse + "_shell"))
{
appliedMapOverrides.Remove("spouse_room_" + spouse + "_shell");
}
fh.ApplyMapOverride(shellPath, "spouse_room_" + spouse + "_shell", new Rectangle?(new Rectangle(0, 0, shellAreaToRefurbish.Width, shellAreaToRefurbish.Height)), new Rectangle?(shellAreaToRefurbish));
for (int x = 0; x < shellAreaToRefurbish.Width; x++)
{
for (int y = 0; y < shellAreaToRefurbish.Height; y++)
{
if (fh.map.GetLayer("Back").Tiles[shellAreaToRefurbish.X + x, shellAreaToRefurbish.Y + y] != null)
{
fh.map.GetLayer("Back").Tiles[shellAreaToRefurbish.X + x, shellAreaToRefurbish.Y + y].Properties["FloorID"] = "spouse_hall_" + (Config.DecorateHallsIndividually ? spouse : "floor");
}
}
}
Dictionary<string, string> room_data = Game1.content.Load<Dictionary<string, string>>("Data\\SpouseRooms");
string map_path = "spouseRooms";
if (indexInSpouseMapSheet == -1 && room_data != null && srd.templateName != null && room_data.ContainsKey(srd.templateName))
{
try
{
string[] array = room_data[srd.templateName].Split('/', StringSplitOptions.None);
map_path = array[0];
indexInSpouseMapSheet = int.Parse(array[1]);
}
catch (Exception)
{
}
}
if (indexInSpouseMapSheet == -1 && room_data != null && room_data.ContainsKey(spouse))
{
try
{
string[] array = room_data[spouse].Split('/', StringSplitOptions.None);
map_path = array[0];
indexInSpouseMapSheet = int.Parse(array[1]);
}
catch (Exception)
{
}
}
if (indexInSpouseMapSheet == -1)
{
if (srd.templateName != null && ModEntry.roomIndexes.ContainsKey(srd.templateName))
{
indexInSpouseMapSheet = ModEntry.roomIndexes[srd.templateName];
}
else if (ModEntry.roomIndexes.ContainsKey(spouse))
{
indexInSpouseMapSheet = ModEntry.roomIndexes[spouse];
}
else
{
Monitor.Log($"Could not find spouse room map for {spouse}", LogLevel.Debug);
return;
}
}
int width = fh.GetSpouseRoomWidth();
int height = fh.GetSpouseRoomHeight();
Rectangle areaToRefurbish = new Rectangle(corner.X, corner.Y, width, height);
Map refurbishedMap = Game1.game1.xTileContent.Load<Map>("Maps\\" + map_path);
int columns = refurbishedMap.Layers[0].LayerWidth / width;
int num2 = refurbishedMap.Layers[0].LayerHeight / height;
Point mapReader = new Point(indexInSpouseMapSheet % columns * width, indexInSpouseMapSheet / columns * height);
List<KeyValuePair<Point, Tile>> bottom_row_tiles = new List<KeyValuePair<Point, Tile>>();
Layer front_layer = fh.map.GetLayer("Front");
for (int x = areaToRefurbish.Left; x < areaToRefurbish.Right; x++)
{
Point point = new Point(x, areaToRefurbish.Bottom - 1);
Tile tile = front_layer.Tiles[point.X, point.Y];
if (tile != null)
{
bottom_row_tiles.Add(new KeyValuePair<Point, Tile>(point, tile));
}
}
if (appliedMapOverrides.Contains("spouse_room_" + spouse))
{
appliedMapOverrides.Remove("spouse_room_" + spouse);
}
fh.ApplyMapOverride(map_path, "spouse_room_" + spouse, new Rectangle?(new Rectangle(mapReader.X, mapReader.Y, areaToRefurbish.Width, areaToRefurbish.Height)), new Rectangle?(areaToRefurbish));
for (int x = 0; x < areaToRefurbish.Width; x++)
{
for (int y = 0; y < areaToRefurbish.Height; y++)
{
if (refurbishedMap.GetLayer("Buildings").Tiles[mapReader.X + x, mapReader.Y + y] != null)
{
Helper.Reflection.GetMethod(fh, "adjustMapLightPropertiesForLamp").Invoke(refurbishedMap.GetLayer("Buildings").Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Buildings");
}
if (y < areaToRefurbish.Height - 1 && refurbishedMap.GetLayer("Front").Tiles[mapReader.X + x, mapReader.Y + y] != null)
{
Helper.Reflection.GetMethod(fh, "adjustMapLightPropertiesForLamp").Invoke(refurbishedMap.GetLayer("Front").Tiles[mapReader.X + x, mapReader.Y + y].TileIndex, areaToRefurbish.X + x, areaToRefurbish.Y + y, "Front");
}
/*
if (fh.map.GetLayer("Back").Tiles[corner.X + x, corner.Y + y] != null)
{
fh.setTileProperty(corner.X + x, corner.Y + y, "Back", "FloorID", $"spouse_room_{spouse}");
}
*/
}
}
fh.ReadWallpaperAndFloorTileData();
bool spot_found = false;
for (int x3 = areaToRefurbish.Left; x3 < areaToRefurbish.Right; x3++)
{
for (int y2 = areaToRefurbish.Top; y2 < areaToRefurbish.Bottom; y2++)
{
if (fh.getTileIndexAt(new Point(x3, y2), "Paths") == 7)
{
spot_found = true;
if (first)
fh.spouseRoomSpot = new Point(x3, y2);
spouseSpot = new Point(x3, y2);
srd.spousePosOffset = spouseSpot - srd.startPos;
break;
}
}
if (spot_found)
{
break;
}
}
fh.setTileProperty(spouseSpot.X, spouseSpot.Y, "Back", "NoFurniture", "T");
foreach (KeyValuePair<Point, Tile> kvp in bottom_row_tiles)
{
front_layer.Tiles[kvp.Key.X, kvp.Key.Y] = kvp.Value;
}
ModEntry.currentRoomData[srd.name] = srd;
}
19
Source : ReplayResources.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public void AddPrefab(KeyValuePair<string, int> pair)
{
resourceMap.Add(pair);
}
19
Source : CollectionEx.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static string LinkToSql(this IEnumerable<string> em, char lt = '[', char rt = ']')
{
if (em == null)
{
return null;
}
var sb = new StringBuilder();
var first = true; var maxLen = 0;
var ll = new List<KeyValuePair<int, string>>();
foreach (var str in em)
{
if (string.IsNullOrWhiteSpace(str))
{
continue;
}
var len = str.StrLenght();
ll.Add(new KeyValuePair<int, string>(len, str));
if (len > maxLen)
{
maxLen = len;
}
}
foreach (var kv in ll)
{
if (first)
{
first = false;
}
else
{
sb.Append(',');
}
sb.Append($"{lt}{kv.Value}{rt}");
}
return sb.ToString();
}
19
Source : CollectionEx.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static string LinkToSql(this IEnumerable<string> em, string empty = " ", char sp = ',', int maxCol = 5)
{
if (em == null)
{
return null;
}
var sb = new StringBuilder();
var first = true;
if (maxCol > 0)
{
var col = 0;
var maxLen = 0;
var ll = new List<KeyValuePair<int, string>>();
foreach (var str in em)
{
if (string.IsNullOrWhiteSpace(str))
{
continue;
}
var len = str.StrLenght();
ll.Add(new KeyValuePair<int, string>(len, str));
if (len > maxLen)
{
maxLen = len;
}
}
var preLen = 0;
foreach (var kv in ll)
{
var str = kv.Value;
if (first)
{
first = false;
}
else
{
sb.Append(sp);
if (maxCol > 0 && ++col == maxCol)
{
col = 0;
sb.AppendLine();
sb.Append(empty);
}
else
{
var e = maxLen - preLen;
if (e > 0)
{
sb.Append(' ', e);
}
}
}
sb.Append(str);
preLen = kv.Key;
}
}
else
{
foreach (var v in em)
{
if (v == null || string.IsNullOrWhiteSpace(v.ToString(CultureInfo.InvariantCulture)))
{
continue;
}
if (first)
{
first = false;
}
else
{
sb.Append(sp);
}
sb.Append(v);
}
}
return sb.ToString();
}
19
Source : QueryUriBuilder.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public QueryUriBuilder AddParameter(string key, string value)
{
this._queryParams.Add(new KeyValuePair<string, string>(key, value));
return this;
}
19
Source : MissionGeneratorObjectives.cs
with GNU General Public License v3.0
from akaAgar
with GNU General Public License v3.0
from akaAgar
internal Coordinates GenerateObjective(DCSMission mission, MissionTemplate template, DBEntryTheater theaterDB, int objectiveIndex, Coordinates lastCoordinates, DBEntryAirbase playerAirbase, bool useObjectivePreset, out string objectiveName, out UnitFamily objectiveTargetUnitFamily)
{
MissionTemplateObjective objectiveTemplate = template.Objectives[objectiveIndex];
string[] featuresID = objectiveTemplate.Features.ToArray();
DBEntryObjectiveTarget targetDB = Database.Instance.GetEntry<DBEntryObjectiveTarget>(objectiveTemplate.Target);
DBEntryObjectiveTargetBehavior targetBehaviorDB = Database.Instance.GetEntry<DBEntryObjectiveTargetBehavior>(objectiveTemplate.TargetBehavior);
DBEntryObjectiveTask taskDB = Database.Instance.GetEntry<DBEntryObjectiveTask>(objectiveTemplate.Task);
ObjectiveOption[] objectiveOptions = objectiveTemplate.Options.ToArray();
if (useObjectivePreset)
{
DBEntryObjectivePreset presetDB = Database.Instance.GetEntry<DBEntryObjectivePreset>(objectiveTemplate.Preset);
if (presetDB != null)
{
featuresID = presetDB.Features.ToArray();
targetDB = Database.Instance.GetEntry<DBEntryObjectiveTarget>(Toolbox.RandomFrom(presetDB.Targets));
targetBehaviorDB = Database.Instance.GetEntry<DBEntryObjectiveTargetBehavior>(Toolbox.RandomFrom(presetDB.TargetsBehaviors));
taskDB = Database.Instance.GetEntry<DBEntryObjectiveTask>(Toolbox.RandomFrom(presetDB.Tasks));
objectiveOptions = presetDB.Options.ToArray();
}
}
if (targetDB == null) throw new BriefingRoomException($"Target \"{targetDB.UIDisplayName}\" not found for objective #{objectiveIndex + 1}.");
if (targetBehaviorDB == null) throw new BriefingRoomException($"Target behavior \"{targetBehaviorDB.UIDisplayName}\" not found for objective #{objectiveIndex + 1}.");
if (taskDB == null) throw new BriefingRoomException($"Task \"{taskDB.UIDisplayName}\" not found for objective #{objectiveIndex + 1}.");
if (!taskDB.ValidUnitCategories.Contains(targetDB.UnitCategory))
throw new BriefingRoomException($"Task \"{taskDB.UIDisplayName}\" not valid for objective #{objectiveIndex + 1} targets, which belong to category \"{targetDB.UnitCategory}\".");
// Add feature ogg files
foreach (string oggFile in taskDB.IncludeOgg)
mission.AddMediaFile($"l10n/DEFAULT/{oggFile}", $"{BRPaths.INCLUDE_OGG}{oggFile}");
int objectiveDistance = template.FlightPlanObjectiveDistance;
if (objectiveDistance < 1) objectiveDistance = Toolbox.RandomInt(40, 160);
int objectiveSeperation = template.FlightPlanObjectiveSeperation;
if (objectiveSeperation < 1) objectiveSeperation = Toolbox.RandomInt(10, 100);
Coordinates? spawnPoint = UnitMaker.SpawnPointSelector.GetRandomSpawnPoint(
targetDB.ValidSpawnPoints, playerAirbase.Coordinates,
new MinMaxD(
objectiveDistance * OBJECTIVE_DISTANCE_VARIATION_MIN,
objectiveDistance * OBJECTIVE_DISTANCE_VARIATION_MAX),
lastCoordinates,
new MinMaxD(
objectiveSeperation * OBJECTIVE_DISTANCE_VARIATION_MIN,
objectiveSeperation * OBJECTIVE_DISTANCE_VARIATION_MAX),
GeneratorTools.GetSpawnPointCoalition(template, Side.Enemy));
if (!spawnPoint.HasValue)
throw new BriefingRoomException($"Failed to spawn objective unit group. {String.Join(",", targetDB.ValidSpawnPoints.Select(x => x.ToString()).ToList())} Please try again (Consider Adusting Flight Plan)");
Coordinates objectiveCoordinates = spawnPoint.Value;
// Spawn target on airbase
int airbaseID = 0;
var parkingSpotIDsList = new List<int>();
var parkingSpotCoordinatesList = new List<Coordinates>();
var unitCount = targetDB.UnitCount[(int)objectiveTemplate.TargetCount].GetValue();
switch (targetBehaviorDB.Location)
{
case DBEntryObjectiveTargetBehaviorLocation.SpawnOnAirbase:
case DBEntryObjectiveTargetBehaviorLocation.SpawnOnAirbaseParking:
case DBEntryObjectiveTargetBehaviorLocation.SpawnOnAirbaseParkingNoHardenedShelter:
DBEntryAirbase targetAirbase =
(from DBEntryAirbase airbaseDB in theaterDB.GetAirbases()
where airbaseDB.DCSID != playerAirbase.DCSID
select airbaseDB).OrderBy(x => x.Coordinates.GetDistanceFrom(objectiveCoordinates)).FirstOrDefault();
objectiveCoordinates = targetAirbase.Coordinates;
airbaseID = targetAirbase.DCSID;
if ((targetBehaviorDB.Location != DBEntryObjectiveTargetBehaviorLocation.SpawnOnAirbase) && targetDB.UnitCategory.IsAircraft())
{
Coordinates? lastParkingCoordinates = null;
for (int i = 0; i < unitCount; i++)
{
int parkingSpot = UnitMaker.SpawnPointSelector.GetFreeParkingSpot(
targetAirbase.DCSID,
out Coordinates parkingSpotCoordinates,
lastParkingCoordinates,
targetBehaviorDB.Location == DBEntryObjectiveTargetBehaviorLocation.SpawnOnAirbaseParkingNoHardenedShelter);
if (parkingSpot < 0) throw new BriefingRoomException("No parking spot found for aircraft.");
lastParkingCoordinates = parkingSpotCoordinates;
parkingSpotIDsList.Add(parkingSpot);
parkingSpotCoordinatesList.Add(parkingSpotCoordinates);
}
}
break;
}
// Pick a name, then remove it from the list
objectiveName = Toolbox.RandomFrom(ObjectiveNames);
ObjectiveNames.Remove(objectiveName);
UnitMakerGroupFlags groupFlags = 0;
if (objectiveOptions.Contains(ObjectiveOption.ShowTarget)) groupFlags = UnitMakerGroupFlags.NeverHidden;
else if (objectiveOptions.Contains(ObjectiveOption.HideTarget)) groupFlags = UnitMakerGroupFlags.AlwaysHidden;
if (objectiveOptions.Contains(ObjectiveOption.EmbeddedAirDefense)) groupFlags |= UnitMakerGroupFlags.EmbeddedAirDefense;
objectiveTargetUnitFamily = Toolbox.RandomFrom(targetDB.UnitFamilies);
// Set destination point for moving unit groups
Coordinates destinationPoint = objectiveCoordinates;
switch (targetDB.UnitCategory)
{
default:
destinationPoint += Coordinates.CreateRandom(10, 20) * Toolbox.NM_TO_METERS;
break;
case UnitCategory.Plane:
destinationPoint += Coordinates.CreateRandom(30, 60) * Toolbox.NM_TO_METERS;
break;
}
switch (targetBehaviorDB.Location)
{
case DBEntryObjectiveTargetBehaviorLocation.GoToPlayerAirbase:
destinationPoint = playerAirbase.Coordinates;
break;
}
var extraSettings = new List<KeyValuePair<string, object>>{
"GroupX2".ToKeyValuePair(destinationPoint.X),
"GroupY2".ToKeyValuePair(destinationPoint.Y),
"GroupAirbaseID".ToKeyValuePair(airbaseID),
"ParkingID".ToKeyValuePair(parkingSpotIDsList.ToArray())
};
if (parkingSpotCoordinatesList.Count > 1)
{
extraSettings.Add("UnitX".ToKeyValuePair((from Coordinates coordinates in parkingSpotCoordinatesList select coordinates.X).ToArray()));
extraSettings.Add("UnitY".ToKeyValuePair((from Coordinates coordinates in parkingSpotCoordinatesList select coordinates.Y).ToArray()));
}
UnitMakerGroupInfo? targetGroupInfo = UnitMaker.AddUnitGroup(
objectiveTargetUnitFamily, unitCount,
taskDB.TargetSide,
targetBehaviorDB.GroupLua[(int)targetDB.UnitCategory], targetBehaviorDB.UnitLua[(int)targetDB.UnitCategory],
objectiveCoordinates,
null, groupFlags,
"default",
extraSettings.ToArray());
if (!targetGroupInfo.HasValue) // Failed to generate target group
throw new BriefingRoomException($"Failed to generate group for objective {objectiveIndex + 1}");
// Static targets (aka buildings) need to have their "embedded" air defenses spawned in another group
if (objectiveOptions.Contains(ObjectiveOption.EmbeddedAirDefense) && (targetDB.UnitCategory == UnitCategory.Static))
{
string[] airDefenseUnits = GeneratorTools.GetEmbeddedAirDefenseUnits(template, taskDB.TargetSide);
if (airDefenseUnits.Length > 0)
UnitMaker.AddUnitGroup(
airDefenseUnits,
taskDB.TargetSide, UnitFamily.VehicleAAA,
targetBehaviorDB.GroupLua[(int)targetDB.UnitCategory], targetBehaviorDB.UnitLua[(int)targetDB.UnitCategory],
objectiveCoordinates + Coordinates.CreateRandom(100, 500),
null, groupFlags,
"default",
extraSettings.ToArray());
}
// Get tasking string for the briefing
int pluralIndex = targetGroupInfo.Value.UnitsID.Length == 1 ? 0 : 1; // 0 for singular, 1 for plural. Used for task/names arrays.
string taskString = GeneratorTools.ParseRandomString(taskDB.BriefingTask[pluralIndex]).Replace("\"", "''");
if (string.IsNullOrEmpty(taskString)) taskString = "Complete objective $OBJECTIVENAME$";
GeneratorTools.ReplaceKey(ref taskString, "ObjectiveName", objectiveName);
GeneratorTools.ReplaceKey(ref taskString, "UnitFamily", Database.Instance.Common.Names.UnitFamilies[(int)objectiveTargetUnitFamily][pluralIndex]);
mission.Briefing.AddItem(DCSMissionBriefingItemType.Task, taskString);
// Add Lua table for this objective
string objectiveLua = $"briefingRoom.mission.objectives[{objectiveIndex + 1}] = {{ ";
objectiveLua += $"complete = false, ";
objectiveLua += $"groupID = {targetGroupInfo.Value.GroupID}, ";
objectiveLua += $"hideTargetCount = false, ";
objectiveLua += $"name = \"{objectiveName}\", ";
objectiveLua += $"targetCategory = Unit.Category.{targetDB.UnitCategory.ToLuaName()}, ";
objectiveLua += $"task = \"{taskString}\", ";
objectiveLua += $"unitsCount = {targetGroupInfo.Value.UnitsID.Length}, ";
objectiveLua += $"unitsID = {{ {string.Join(", ", targetGroupInfo.Value.UnitsID)} }} ";
objectiveLua += "}\n";
// Add F10 sub-menu for this objective
objectiveLua += $"briefingRoom.f10Menu.objectives[{objectiveIndex + 1}] = missionCommands.addSubMenuForCoalition(coalition.side.{template.ContextPlayerCoalition.ToString().ToUpperInvariant()}, \"Objective {objectiveName}\", nil)\n";
mission.AppendValue("ScriptObjectives", objectiveLua);
// Add objective trigger Lua for this objective
string triggerLua = Toolbox.ReadAllTextIfFileExists($"{BRPaths.INCLUDE_LUA_OBJECTIVETRIGGERS}{taskDB.CompletionTriggerLua}");
GeneratorTools.ReplaceKey(ref triggerLua, "ObjectiveIndex", objectiveIndex + 1);
mission.AppendValue("ScriptObjectivesTriggers", triggerLua);
// Add briefing remarks for this objective task
if (taskDB.BriefingRemarks.Length > 0)
{
string remark = Toolbox.RandomFrom(taskDB.BriefingRemarks);
GeneratorTools.ReplaceKey(ref remark, "ObjectiveName", objectiveName);
GeneratorTools.ReplaceKey(ref remark, "UnitFamily", Database.Instance.Common.Names.UnitFamilies[(int)objectiveTargetUnitFamily][pluralIndex]);
mission.Briefing.AddItem(DCSMissionBriefingItemType.Remark, remark);
}
// Add objective features Lua for this objective
mission.AppendValue("ScriptObjectivesFeatures", ""); // Just in case there's no features
foreach (string featureID in featuresID)
FeaturesGenerator.GenerateMissionFeature(mission, featureID, objectiveName, objectiveIndex, targetGroupInfo.Value.GroupID, objectiveCoordinates, taskDB.TargetSide);
return objectiveCoordinates;
}
See More Examples