public Layer[] LoadObjectLayers(TmxMap tmxMap, ContentManager content) { var layers = new Layer[tmxMap.ObjectGroups.Count]; for (int i = 0; i < tmxMap.ObjectGroups.Count; i++) { OrderedDictionary<string, IGameObject> _gameObjects = new OrderedDictionary<string, IGameObject>(); foreach (var tmxObject in tmxMap.ObjectGroups[i].Objects) { if (tmxObject.Type == "Particle Emitter") { IGameObject gameObject = this.LoadParticleEmitter(tmxObject, content); _gameObjects.Add(tmxObject.Name, gameObject); } else if (tmxObject.Type == "NPC Spawner") { IGameObject gameObject = this.LoadNpcSpawner(tmxObject, _gameObjects, content); _gameObjects.Add(tmxObject.Name, gameObject); } } layers[i] = new Layer(_gameObjects, tmxMap.ObjectGroups[i].ZOrder); } return layers; }
public TokenParser() { _tokens = new OrderedDictionary<Tokens, string>(); _regExMatchCollection = new OrderedDictionary<Tokens, MatchCollection>(); _index = 0; _inputString = string.Empty; _customFunctionIndex = 100; _tokens.Add(Tokens.Whitespace, "[ \\t]+"); _tokens.Add(Tokens.Newline, "[\\r\\n]+"); _tokens.Add(Tokens.Function, "func([a-zA-Z_][a-zA-Z0-9_]*)\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.LogN, "[Ll][Oo][Gg][Nn]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Sqrt, "[Ss][Qq][Rr][Tt]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Sin, "[Ss][Ii][Nn]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Cos, "[Cc][Oo][Ss]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Tan, "[Tt][Aa][Nn]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Abs, "[Aa][Bb][Ss]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Log, "[Ll][Oo][Gg]\\(((?<BR>\\()|(?<-BR>\\))|[^()]*)+\\)"); _tokens.Add(Tokens.Variable, "[a-zA-Z_][a-zA-Z0-9_]*"); _tokens.Add(Tokens.Float, "([0-9]+)?\\.+[0-9]+"); _tokens.Add(Tokens.Integer, "[0-9]+"); _tokens.Add(Tokens.Lparen, "\\("); _tokens.Add(Tokens.Rparen, "\\)"); _tokens.Add(Tokens.Exponent, "\\^"); _tokens.Add(Tokens.Modulus, "\\%"); _tokens.Add(Tokens.Multiply, "\\*"); _tokens.Add(Tokens.Divide, "\\/"); _tokens.Add(Tokens.Add, "\\+"); _tokens.Add(Tokens.Subtract, "\\-"); }
public void AppendItem() { OrderedDictionary<string, string> dictionary = new OrderedDictionary<string, string>(); dictionary.Add("1", "one"); dictionary.Add("2", "two"); Assert.AreEqual(2, dictionary.Count); }
public void Add() { var dict = new OrderedDictionary<string, int>(); dict.Add("1", 2); dict.Add("2", 3); Assert.AreEqual(dict[0], 2); Assert.AreEqual(dict[1], 3); }
public static string RemoveNumbersThatOccurOddNumbers(int[] input) { HashSet<int> whiteList = new HashSet<int>(); var uniqueValuesInList = new OrderedDictionary<int, int>(); foreach (var item in input) { if (uniqueValuesInList.ContainsKey(item)) { uniqueValuesInList[item]++; } else { uniqueValuesInList.Add(item, 1); } } string result = null; foreach (var item in uniqueValuesInList) { if (item.Value >= (uniqueValuesInList.Count / 2) + 1) { result = string.Format("Majorant number is {0}.", item.Key); } } if (result == null) { result = "Does not exist majorant number."; } return result; }
public void Before() { _random = new Random(); _dict = new OrderedDictionary(); for (int i = 0; i < n; i++) { _dict.Add(i, new Entity(CP.NumComponents, null)); } }
static void Main(string[] args) { OrderedDictionary<string, SortedSet<Person>> coursesAndStudents = new OrderedDictionary<string, SortedSet<Person>>(); while (true) { string[] input = Console.ReadLine().Split(new[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries); string course = input[2].Trim(); string firstName = input[0].Trim(); string lastName = input[1].Trim(); if (coursesAndStudents.ContainsKey(course)) { coursesAndStudents[course].Add(new Person(firstName, lastName)); } else { SortedSet<Person> set = new SortedSet<Person>(); set.Add(new Person(firstName, lastName)); coursesAndStudents.Add(course, set); } Output(coursesAndStudents); } }
public void Before() { _dict = new OrderedDictionary(); _lookup = new Entity[n]; for (int i = 0; i < n; i++) { var e = new Entity(CP.NumComponents); _dict.Add(i, e); _lookup[i] = e; } }
public IDictionary<string, double> Tokenize(string line) { OrderedDictionary<string, double> res = new OrderedDictionary<string, double>(); foreach (string elt in line.Split(' ')) if (res.ContainsKey(elt)) res[elt]++; else res.Add(elt, 1); return res; }
// Use this for initialization void Start () { UserProfile user = new UserProfile("MyName", "*****@*****.**", "password"); OrderedDictionary orderedBook = new OrderedDictionary(); orderedBook.Add(user.Name, user); if (orderedBook.Contains("MyName")) { Debug.Log("Found key"); } }
static void Main(string[] args) { const string fileName = "students.txt"; string input = Console.ReadLine(); using (StreamWriter newWriter = File.AppendText(fileName)) { while (input != "end") { newWriter.WriteLine(input); input = Console.ReadLine(); } } var dataStorage = new OrderedDictionary<string, OrderedDictionary<string, Person>>(); using (var streamReader = new StreamReader(fileName)) { string currentLine; while ((currentLine = streamReader.ReadLine()) != null) { string[] parameters = currentLine.Split(new char[] { ' ', '|' }, StringSplitOptions.RemoveEmptyEntries); string firstName = parameters[0]; string lastName = parameters[1]; string course = parameters[2]; if (!dataStorage.ContainsKey(course)) { dataStorage.Add(course, new OrderedDictionary<string, Person>()); } if (!dataStorage[course].ContainsKey(lastName)) { dataStorage[course].Add(lastName, new Person(firstName, lastName)); } } } foreach (var course in dataStorage) { Console.Write($"{course.Key} -> "); string peopleInCourse = ""; foreach (var person in course.Value) { peopleInCourse += ", " + person.Value.ToString(); } peopleInCourse = peopleInCourse.Remove(0, 2); Console.WriteLine(peopleInCourse); } }
protected void FormView1_ItemInserting1(object sender, FormViewInsertEventArgs e) { FormView fv = (FormView)sender; string filename = @"E:\Projects\IGRSS\FINAL\WebApp\Inspection\InspectionCheckList.xml"; OrderedDictionary coll = new OrderedDictionary(); XmlDocument doc = new XmlDocument(); doc.Load(filename); foreach (XmlNode Node in doc.SelectNodes("DocumentElement/Items")) { TextBox txt = (TextBox)fv.FindControl("txt" + Node.Attributes["ItemId"].InnerText); CheckBox chk = (CheckBox)fv.FindControl("chk" + Node.Attributes["ItemId"].Value); coll.Add(txt.ID, txt.Text); coll.Add(chk.ID, chk.Checked); } e.Values.Add("Values", coll); }
public static void Main() { OrderedDictionary<double, Product> products = new OrderedDictionary<double, Product>(); for (int i = 0; i < 500000; i++) { var currPrice = 100 + i; products.Add(currPrice, new Product("Pesho" + i, currPrice)); } // Wait 2-3 seconds. Console.WriteLine(products.Range(120, true, 1040, true)); }
static void Main(string[] args) { OrderedDictionary holder = new OrderedDictionary(); Console.WriteLine("Please enter your name:"); holder.Add("First_Name", Console.ReadLine()); Console.WriteLine("Please enter your middle name:"); holder.Add("Middle_Name", Console.ReadLine()); Console.WriteLine("Please enter your last name:"); holder.Add("Last_Name", Console.ReadLine()); Console.WriteLine("Balance:"); decimal balance = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("IBAN:"); ulong IBAN = Convert.ToUInt64(Console.ReadLine()); Console.WriteLine("Bank name:"); String bankName = Console.ReadLine(); ; OrderedDictionary creditCard = new OrderedDictionary(); Console.WriteLine("First Bank Account:"); creditCard.Add("Account1", Console.ReadLine()); Console.WriteLine("Second Bank Account:"); creditCard.Add("Account2", Console.ReadLine()); Console.WriteLine("Third Bank Account:"); creditCard.Add("Account3", Console.ReadLine()); }
public static OrderedDictionary<String, Object> Quanta(this Object obj) { if (obj == null) return null; var schema = new OrderedDictionary<String, Object>(); var props = obj.GetType().GetProperties(BF.PublicInstance).Where(p => p.HasAttr<QuantumAttribute>()).ToReadOnly(); props.ForEach((p, i) => { var v = p.GetValue(obj, null); var @default = p.PropertyType.Fluent(t => t.IsValueType ? Activator.CreateInstance(t) : null); if (!Equals(v, @default)) schema.Add(p.Attr<QuantumAttribute>().Signature, v); }); return schema; }
public NpcSpawner(Vector2 position, uint updateInterval, OrderedDictionary<string, IGameObject> gameObjects, List<IEntity> spawningEntites) { _position = position; _updateInterval = updateInterval; _gameObjects = gameObjects; _spawningEntities = spawningEntites; // Give the NPC the parent layer's gameobjects. // We'll also perform the initial spawn whilst we're at it. foreach (Npc npc in _spawningEntities) { npc.ParentLayerGameObjects = _gameObjects; gameObjects.Add(npc.UniqueID, npc); } }
public JsonResult Insert() { OrderedDictionary<int, BigList<double>> orderedDic = new OrderedDictionary<int, BigList<double>>(); BigList<double> bigList = new BigList<double>(); Parallel.For(1, 10000, x => { lock(this) { bigList.Add(x * Math.PI * new Random().NextDouble()); } }); orderedDic.Add(Environment.CurrentManagedThreadId, bigList); tree.Insert(orderedDic, DuplicatePolicy.InsertFirst, out orderedDic); return Json(new { OrderedDictionary = orderedDic }, JsonRequestBehavior.AllowGet); }
public static OrderedDictionary<int, int> FindOccursNumbrersInArray(int[] input) { var uniqueValuesInList = new OrderedDictionary<int, int>(); foreach (var item in input) { if (uniqueValuesInList.ContainsKey(item)) { uniqueValuesInList[item]++; } else { uniqueValuesInList.Add(item, 1); } } return uniqueValuesInList; }
static void ParseScores(string json) { Debug.Log("==========PARSING SCOREZ"); int i = 0; IDictionary scores = ((IDictionary)Json.Deserialize(json)); Dictionary<string,long> sort = new Dictionary<string, long>(); foreach(string key in scores.Keys){ if(i++ == scoreLimit) break; sort.Add(key, (long)scores[key]); } OrderedDictionary sort2 = new OrderedDictionary(); foreach (KeyValuePair<string, long> pair in sort.OrderByDescending(key => key.Value)){ sort2.Add(pair.Key, (long)scores[pair.Key]); } Scores = sort2; }
public void Clear() { OrderedDictionary<string, string> dictionary = new OrderedDictionary<string, string>(); List<KeyValuePair<string, string>> tracking = new List<KeyValuePair<string, string>>(); KeyValuePair<string, string> one = new KeyValuePair<string, string>("1", "one"); KeyValuePair<string, string> two = new KeyValuePair<string, string>("2", "two"); dictionary.Add(one); dictionary.Insert(0, two); Assert.IsTrue(2 == dictionary.Count); dictionary.Clear(); Assert.IsTrue(0 == dictionary.Count); }
/* Task 2: * Write a program to read a large collection of products (name + price) I love * and efficiently find the first 20 products in the price range [a…b]. Test for * 500 000 products and 10 000 price searches. * Hint: you may use OrderedBag<T> and sub-ranges. */ static void Main(string[] args) { Random randomGenerator = new Random(); Stopwatch stopWatch = new Stopwatch(); string[] product = { "bread", "butter", "meat", "eggs", "flower", "oil", "soda", "candy" }; var productLenght = product.Length; var orderedDictionary = new OrderedDictionary<int, string>(); stopWatch.Start(); while (orderedDictionary.Count < 500000) { var key = randomGenerator.Next(1, 1000000); var value = product[randomGenerator.Next(0, productLenght)]; if (!orderedDictionary.ContainsKey(key)) { orderedDictionary.Add(key, value); } } stopWatch.Stop(); Console.WriteLine("Time for creating the elements is: {0}", stopWatch.Elapsed); stopWatch.Reset(); stopWatch.Start(); for (int i = 0; i < 10000; i++) { var min = randomGenerator.Next(0, 500000); var max = randomGenerator.Next(500000, 1000000); var products = orderedDictionary.Range(min, true, max, true); } stopWatch.Stop(); Console.WriteLine("Time for performing 10k range searches: {0}", stopWatch.Elapsed); var range = orderedDictionary.Range(1000, true, 100000, true); for (int i = 0; i < 20; i++) { Console.WriteLine(range.ElementAt(i)); } }
public void VarsNeededForDecode(PEREffectiveConstraint cns, int arrayDepth, OrderedDictionary<string, CLocalVariable> existingVars) { PERIntegerEffectiveConstraint cn = cns as PERIntegerEffectiveConstraint; if (cns != null && cn.Extensible) { if (!existingVars.ContainsKey("extBit")) { existingVars.Add("extBit", new CLocalVariable("extBit", "flag", 0, "FALSE")); } } }
public void Decode(byte[] bytes, Iterator it = null, ReferenceTracker refs = null) { var decode = Decoder.GetInstance(); if (it == null) { it = new Iterator(); } if (refs == null) { refs = new ReferenceTracker(); } var totalBytes = bytes.Length; int refId = 0; IRef _ref = this; this.refs = refs; refs.Add(refId, _ref); var changes = new List <DataChange>(); var allChanges = new OrderedDictionary(); // Dictionary<int, List<DataChange>> allChanges.Add(refId, changes); while (it.Offset < totalBytes) { var _byte = bytes[it.Offset++]; if (_byte == (byte)SPEC.SWITCH_TO_STRUCTURE) { refId = Convert.ToInt32(decode.DecodeNumber(bytes, it)); _ref = refs.Get(refId); // // Trying to access a reference that haven't been decoded yet. // if (_ref == null) { throw new Exception("refId not found: " + refId); } // create empty list of changes for this refId. changes = new List <DataChange>(); allChanges[(object)refId] = changes; continue; } bool isSchema = _ref is Schema; var operation = (byte)((isSchema) ? (_byte >> 6) << 6 // "compressed" index + operation : _byte); // "uncompressed" index + operation (array/map items) if (operation == (byte)OPERATION.CLEAR) { ((ISchemaCollection)_ref).Clear(refs); continue; } int fieldIndex; string fieldName = null; string fieldType = null; System.Type childType = null; if (isSchema) { fieldIndex = _byte % ((operation == 0) ? 255 : operation); // FIXME: JS allows (0 || 255) ((Schema)_ref).fieldsByIndex.TryGetValue(fieldIndex, out fieldName); // fieldType = ((Schema)_ref).fieldTypes[fieldName]; ((Schema)_ref).fieldTypes.TryGetValue(fieldName ?? "", out fieldType); ((Schema)_ref).fieldChildTypes.TryGetValue(fieldName ?? "", out childType); } else { fieldName = ""; // FIXME fieldIndex = Convert.ToInt32(decode.DecodeNumber(bytes, it)); if (((ISchemaCollection)_ref).HasSchemaChild) { fieldType = "ref"; childType = ((ISchemaCollection)_ref).GetChildType(); } else { fieldType = ((ISchemaCollection)_ref).ChildPrimitiveType; } } object value = null; object previousValue = null; object dynamicIndex = null; if (!isSchema) { previousValue = _ref.GetByIndex(fieldIndex); if ((operation & (byte)OPERATION.ADD) == (byte)OPERATION.ADD) { // MapSchema dynamic index. dynamicIndex = (((ISchemaCollection)_ref).GetItems() is OrderedDictionary) ? (object)decode.DecodeString(bytes, it) : fieldIndex; ((ISchemaCollection)_ref).SetIndex(fieldIndex, dynamicIndex); } else { dynamicIndex = ((ISchemaCollection)_ref).GetIndex(fieldIndex); } } else if (fieldName != null) // FIXME: duplicate check { previousValue = ((Schema)_ref)[fieldName]; } // // Delete operations // if ((operation & (byte)OPERATION.DELETE) == (byte)OPERATION.DELETE) { if (operation != (byte)OPERATION.DELETE_AND_ADD) { _ref.DeleteByIndex(fieldIndex); } // Flag `refId` for garbage collection. if (previousValue != null && previousValue is IRef) { refs.Remove(((IRef)previousValue).__refId); } value = null; } if (fieldName == null) { // // keep skipping next bytes until reaches a known structure // by local decoder. // Iterator nextIterator = new Iterator() { Offset = it.Offset }; while (it.Offset < totalBytes) { if (decode.SwitchStructureCheck(bytes, it)) { nextIterator.Offset = it.Offset + 1; if (refs.Has(Convert.ToInt32(decode.DecodeNumber(bytes, nextIterator)))) { break; } } it.Offset++; } continue; } else if (operation == (byte)OPERATION.DELETE) { // // FIXME: refactor me. // Don't do anything. // } else if (fieldType == "ref") { refId = Convert.ToInt32(decode.DecodeNumber(bytes, it)); value = refs.Get(refId); if (operation != (byte)OPERATION.REPLACE) { var concreteChildType = GetSchemaType(bytes, it, childType); if (value == null) { value = CreateTypeInstance(concreteChildType); if (previousValue != null) { ((Schema)value).MoveEventHandlers((Schema)previousValue); if ( ((IRef)previousValue).__refId > 0 && refId != ((IRef)previousValue).__refId ) { refs.Remove(((IRef)previousValue).__refId); } } } refs.Add(refId, (IRef)value, (value != previousValue)); } } else if (childType == null) { // primitive values value = decode.DecodePrimitiveType(fieldType, bytes, it); } else { refId = Convert.ToInt32(decode.DecodeNumber(bytes, it)); value = refs.Get(refId); ISchemaCollection valueRef = (refs.Has(refId)) ? (ISchemaCollection)previousValue : (ISchemaCollection)Activator.CreateInstance(childType); value = valueRef.Clone(); // keep reference to nested childPrimitiveType. string childPrimitiveType; ((Schema)_ref).fieldChildPrimitiveTypes.TryGetValue(fieldName, out childPrimitiveType); ((ISchemaCollection)value).ChildPrimitiveType = childPrimitiveType; if (previousValue != null) { ((ISchemaCollection)value).MoveEventHandlers(((ISchemaCollection)previousValue)); if ( ((IRef)previousValue).__refId > 0 && refId != ((IRef)previousValue).__refId ) { refs.Remove(((IRef)previousValue).__refId); var deletes = new List <DataChange>(); var items = ((ISchemaCollection)previousValue).GetItems(); foreach (var key in items.Keys) { deletes.Add(new DataChange() { DynamicIndex = key, Op = (byte)OPERATION.DELETE, Value = null, PreviousValue = items[key] }); } allChanges[(object)((IRef)previousValue).__refId] = deletes; } } refs.Add(refId, (IRef)value, (valueRef != previousValue)); } bool hasChange = (previousValue != value); if (value != null) { if (value is IRef) { ((IRef)value).__refId = refId; } if (_ref is Schema) { ((Schema)_ref)[fieldName] = value; } else if (_ref is ISchemaCollection) { ((ISchemaCollection)_ref).SetByIndex(fieldIndex, dynamicIndex, value); } } if (hasChange) { changes.Add(new DataChange { Op = operation, Field = fieldName, DynamicIndex = dynamicIndex, Value = value, PreviousValue = previousValue }); } } TriggerChanges(ref allChanges); refs.GarbageCollection(); }
private OrderedDictionary <string, OpenApiPath> ParseOperations(List <RestPath> restPaths, Dictionary <string, OpenApiSchema> schemas, Dictionary <string, OpenApiTag> tags) { var apiPaths = new OrderedDictionary <string, OpenApiPath>(); foreach (var restPath in restPaths) { var verbs = new List <string>(); var summary = restPath.Summary ?? restPath.RequestType.GetDescription(); verbs.AddRange(restPath.AllowsAllVerbs ? AnyRouteVerbs : restPath.Verbs); var routePath = restPath.Path.Replace("*", ""); var requestType = restPath.RequestType; OpenApiPath curPath; if (!apiPaths.TryGetValue(restPath.Path, out curPath)) { curPath = new OpenApiPath() { Parameters = new List <OpenApiParameter> { new OpenApiParameter { Ref = "#/parameters/Accept" } } }; apiPaths.Add(restPath.Path, curPath); } var op = HostContext.Metadata.OperationsMap[requestType]; var actions = HostContext.Metadata.GetImplementedActions(op.ServiceType, op.RequestType); var authAttrs = new[] { op.ServiceType, op.RequestType } .SelectMany(x => x.AllAttributes().OfType <AuthenticateAttribute>()).ToList(); authAttrs.AddRange( actions.Where(x => x.Name.ToUpperInvariant() == "ANY") .SelectMany(x => x.AllAttributes <AuthenticateAttribute>()) ); var annotatingTagAttributes = requestType.AllAttributes <TagAttribute>(); foreach (var verb in verbs) { var needAuth = authAttrs.Count > 0 || actions.Where(x => x.Name.ToUpperInvariant() == verb) .SelectMany(x => x.AllAttributes <AuthenticateAttribute>()) .Count() > 0; var userTags = new List <string>(); ApplyTo applyToVerb; if (ApplyToUtils.VerbsApplyTo.TryGetValue(verb, out applyToVerb)) { userTags = annotatingTagAttributes.Where(x => x.ApplyTo.HasFlag(applyToVerb)).Select(x => x.Name).ToList(); } var operation = new OpenApiOperation { RequestType = requestType.Name, Summary = summary, Description = restPath.Notes ?? summary, OperationId = GetOperationName(requestType.Name, routePath, verb), Parameters = ParseParameters(schemas, requestType, routePath, verb), Responses = GetMethodResponseCodes(restPath, schemas, requestType), Consumes = new List <string> { "application/json" }, Produces = new List <string> { "application/json" }, Tags = userTags.Count > 0 ? userTags : GetTags(restPath.Path), Deprecated = requestType.HasAttribute <ObsoleteAttribute>(), Security = needAuth ? new List <Dictionary <string, List <string> > > { new Dictionary <string, List <string> > { { "basic", new List <string>() } } } : null }; if (HasFormData(verb, operation.Parameters)) { operation.Consumes = new List <string> { "application/x-www-form-urlencoded" } } ; foreach (var tag in operation.Tags) { if (!tags.ContainsKey(tag)) { tags.Add(tag, new OpenApiTag { Name = tag }); } } switch (verb) { case HttpMethods.Get: curPath.Get = operation; break; case HttpMethods.Post: curPath.Post = operation; break; case HttpMethods.Put: curPath.Put = operation; break; case HttpMethods.Delete: curPath.Delete = operation; break; case HttpMethods.Patch: curPath.Patch = operation; break; case HttpMethods.Head: curPath.Head = operation; break; case HttpMethods.Options: curPath.Options = operation; break; } } } return(apiPaths); }
private OrderedDictionary <string, OpenApiPath> ParseOperations(List <RestPath> restPaths, Dictionary <string, OpenApiSchema> schemas, List <OpenApiTag> tags) { var apiPaths = new OrderedDictionary <string, OpenApiPath>(); foreach (var restPath in restPaths) { var verbs = new List <string>(); var summary = restPath.Summary ?? restPath.RequestType.GetDescription(); verbs.AddRange(restPath.AllowsAllVerbs ? AnyRouteVerbs : restPath.Verbs); var routePath = restPath.Path.Replace("*", ""); var requestType = restPath.RequestType; OpenApiPath curPath; if (!apiPaths.TryGetValue(restPath.Path, out curPath)) { curPath = new OpenApiPath() { Parameters = new List <OpenApiParameter> { new OpenApiParameter { Ref = "#/parameters/Accept" } } }; apiPaths.Add(restPath.Path, curPath); tags.Add(new OpenApiTag { Name = restPath.Path, Description = summary }); } var op = HostContext.Metadata.OperationsMap[requestType]; var actions = HostContext.Metadata.GetImplementedActions(op.ServiceType, op.RequestType); var authAttrs = new[] { op.ServiceType, op.RequestType } .SelectMany(x => x.AllAttributes().OfType <AuthenticateAttribute>()).ToList(); authAttrs.AddRange( actions.Where(x => x.Name.ToUpperInvariant() == "ANY") .SelectMany(x => x.AllAttributes <AuthenticateAttribute>()) ); foreach (var verb in verbs) { var needAuth = authAttrs.Count > 0 || actions.Where(x => x.Name.ToUpperInvariant() == verb) .SelectMany(x => x.AllAttributes <AuthenticateAttribute>()) .Count() > 0; var operation = new OpenApiOperation { Summary = summary, Description = restPath.Notes ?? summary, OperationId = GetOperationName(requestType.Name, routePath, verb), Parameters = ParseParameters(schemas, requestType, routePath, verb), Responses = GetMethodResponseCodes(restPath, schemas, requestType), Consumes = new List <string> { "application/json" }, Produces = new List <string> { "application/json" }, Tags = new List <string> { restPath.Path }, Deprecated = requestType.HasAttribute <ObsoleteAttribute>(), Security = needAuth ? new List <Dictionary <string, List <string> > > { new Dictionary <string, List <string> > { { "basic", new List <string>() } } } : null }; switch (verb) { case "GET": curPath.Get = operation; break; case "POST": curPath.Post = operation; break; case "PUT": curPath.Put = operation; break; case "DELETE": curPath.Delete = operation; break; case "PATCH": curPath.Patch = operation; break; case "HEAD": curPath.Head = operation; break; case "OPTIONS": curPath.Options = operation; break; } } } return(apiPaths); }
public void Add(string name, string description, Action commandAction) { var command = new Command(name, description, commandAction); _dictionary.Add(name, command); }
/// <summary> /// Finds all the references of a symbol /// </summary> /// <param name="foundSymbol">The symbol to find all references for</param> /// <param name="referencedFiles">An array of scriptFiles too search for references in</param> /// <param name="workspace">The workspace that will be searched for symbols</param> /// <returns>FindReferencesResult</returns> public async Task <FindReferencesResult> FindReferencesOfSymbol( SymbolReference foundSymbol, ScriptFile[] referencedFiles, Workspace workspace) { if (foundSymbol != null) { int symbolOffset = referencedFiles[0].GetOffsetAtPosition( foundSymbol.ScriptRegion.StartLineNumber, foundSymbol.ScriptRegion.StartColumnNumber); // Make sure aliases have been loaded await GetAliases(); // We want to look for references first in referenced files, hence we use ordered dictionary var fileMap = new OrderedDictionary(StringComparer.OrdinalIgnoreCase); foreach (ScriptFile file in referencedFiles) { fileMap.Add(file.FilePath, file); } var allFiles = workspace.EnumeratePSFiles(); foreach (var file in allFiles) { if (!fileMap.Contains(file)) { fileMap.Add(file, new ScriptFile(file, null, this.powerShellContext.LocalPowerShellVersion.Version)); } } List <SymbolReference> symbolReferences = new List <SymbolReference>(); foreach (var fileName in fileMap.Keys) { var file = (ScriptFile)fileMap[fileName]; IEnumerable <SymbolReference> symbolReferencesinFile = AstOperations .FindReferencesOfSymbol( file.ScriptAst, foundSymbol, CmdletToAliasDictionary, AliasToCmdletDictionary) .Select( reference => { reference.SourceLine = file.GetLine(reference.ScriptRegion.StartLineNumber); reference.FilePath = file.FilePath; return(reference); }); symbolReferences.AddRange(symbolReferencesinFile); } return (new FindReferencesResult { SymbolFileOffset = symbolOffset, SymbolName = foundSymbol.SymbolName, FoundReferences = symbolReferences }); } else { return(null); } }
public void RegisterObject(FieldObject obj) { _objects.Add(obj.Id, obj); }
protected override void FillNode(XmlNode node, object target, params IDOMWriterParam[] options) { var sceneElement = node as XmlElement; var scene = target as Scene; if (scene != null) { TrajectoryFixer.fixTrajectory(scene); } // Create the necessary elements to create the DOM XmlDocument doc = Writer.GetDoc(); // Create the root node sceneElement.SetAttribute("id", scene.getId()); sceneElement.SetAttribute("hideInventory", scene.HideInventory ? "yes" : "no"); sceneElement.SetAttribute("allowsSavingGame", scene.allowsSavingGame() ? "yes" : "no"); if (options.Any(o => o is CIP && (o as CIP).TargetId.Equals(scene.getId()))) { sceneElement.SetAttribute("start", "yes"); } else { sceneElement.SetAttribute("start", "no"); } sceneElement.SetAttribute("playerLayer", scene.getPlayerLayer().ToString()); sceneElement.SetAttribute("playerScale", scene.getPlayerScale().ToString(CultureInfo.InvariantCulture)); sceneElement.SetAttribute("class", scene.getXApiClass()); sceneElement.SetAttribute("type", scene.getXApiType()); // Append the documentation (if avalaible) if (scene.getDocumentation() != null) { XmlNode sceneDocumentationNode = doc.CreateElement("documentation"); sceneDocumentationNode.AppendChild(doc.CreateTextNode(scene.getDocumentation())); sceneElement.AppendChild(sceneDocumentationNode); } // Append the resources foreach (ResourcesUni resources in scene.getResources()) { XmlNode resourcesNode = ResourcesDOMWriter.buildDOM(resources, ResourcesDOMWriter.RESOURCES_SCENE); doc.ImportNode(resourcesNode, true); sceneElement.AppendChild(resourcesNode); } // Append the name XmlNode nameNode = doc.CreateElement("name"); nameNode.AppendChild(doc.CreateTextNode(scene.getName())); sceneElement.AppendChild(nameNode); // Append the default inital position (if avalaible) if (scene.hasDefaultPosition()) { XmlElement initialPositionElement = doc.CreateElement("default-initial-position"); initialPositionElement.SetAttribute("x", scene.getPositionX().ToString()); initialPositionElement.SetAttribute("y", scene.getPositionY().ToString()); sceneElement.AppendChild(initialPositionElement); } // Append the exits (if there is at least one) if (scene.getExits().Count > 0) { XmlNode exitsElement = doc.CreateElement("exits"); // Append every single exit foreach (Exit exit in scene.getExits()) { // Create the exit element XmlElement exitElement = doc.CreateElement("exit"); exitElement.SetAttribute("rectangular", (exit.isRectangular() ? "yes" : "no")); exitElement.SetAttribute("x", exit.getX().ToString()); exitElement.SetAttribute("y", exit.getY().ToString()); exitElement.SetAttribute("width", exit.getWidth().ToString()); exitElement.SetAttribute("height", exit.getHeight().ToString()); exitElement.SetAttribute("hasInfluenceArea", (exit.getInfluenceArea().isExists() ? "yes" : "no")); exitElement.SetAttribute("idTarget", exit.getNextSceneId()); exitElement.SetAttribute("destinyY", exit.getDestinyY().ToString()); exitElement.SetAttribute("destinyX", exit.getDestinyX().ToString()); if (exit.getDestinyScale() >= 0) { exitElement.SetAttribute("destinyScale", exit.getDestinyScale().ToString(CultureInfo.InvariantCulture)); } exitElement.SetAttribute("transitionType", exit.getTransitionType().ToString()); exitElement.SetAttribute("transitionTime", exit.getTransitionTime().ToString()); exitElement.SetAttribute("not-effects", (exit.isHasNotEffects() ? "yes" : "no")); if (exit.getInfluenceArea().isExists()) { exitElement.SetAttribute("influenceX", exit.getInfluenceArea().getX().ToString()); exitElement.SetAttribute("influenceY", exit.getInfluenceArea().getY().ToString()); exitElement.SetAttribute("influenceWidth", exit.getInfluenceArea().getWidth().ToString()); exitElement.SetAttribute("influenceHeight", exit.getInfluenceArea().getHeight().ToString()); } // Append the documentation (if avalaible) if (exit.getDocumentation() != null) { XmlNode exitDocumentationNode = doc.CreateElement("documentation"); exitDocumentationNode.AppendChild(doc.CreateTextNode(exit.getDocumentation())); exitElement.AppendChild(exitDocumentationNode); } //Append the default exit look (if available) ExitLook defaultLook = exit.getDefaultExitLook(); if (defaultLook != null) { XmlElement exitLook = doc.CreateElement("exit-look"); if (defaultLook.getExitText() != null) { exitLook.SetAttribute("text", defaultLook.getExitText()); } if (defaultLook.getCursorPath() != null) { exitLook.SetAttribute("cursor-path", defaultLook.getCursorPath()); } if (defaultLook.getSoundPath() != null) { exitLook.SetAttribute("sound-path", defaultLook.getSoundPath()); } if (defaultLook.getExitText() != null || defaultLook.getCursorPath() != null) { exitElement.AppendChild(exitLook); } } // Append the next-scene structures foreach (NextScene nextScene in exit.getNextScenes()) { // Create the next-scene element XmlElement nextSceneElement = doc.CreateElement("next-scene"); nextSceneElement.SetAttribute("idTarget", nextScene.getTargetId()); // Append the destination position (if avalaible) if (nextScene.hasPlayerPosition()) { nextSceneElement.SetAttribute("x", nextScene.getPositionX().ToString()); nextSceneElement.SetAttribute("y", nextScene.getPositionY().ToString()); } nextSceneElement.SetAttribute("transitionTime", nextScene.getTransitionTime().ToString()); nextSceneElement.SetAttribute("transitionType", nextScene.getTransitionType().ToString()); // Append the conditions (if avalaible) if (!nextScene.getConditions().IsEmpty()) { DOMWriterUtility.DOMWrite(nextSceneElement, nextScene.getConditions()); } //Append the default exit look (if available) ExitLook look = nextScene.getExitLook(); if (look != null) { Debug.Log("SAVE 154: " + look.getExitText()); XmlElement exitLook = doc.CreateElement("exit-look"); if (look.getExitText() != null) { exitLook.SetAttribute("text", look.getExitText()); } if (look.getCursorPath() != null) { exitLook.SetAttribute("cursor-path", look.getCursorPath()); } if (look.getSoundPath() != null) { exitLook.SetAttribute("sound-path", look.getSoundPath()); } if (look.getExitText() != null || look.getCursorPath() != null) { nextSceneElement.AppendChild(exitLook); } } OrderedDictionary nextSceneEffects = new OrderedDictionary(); if (nextScene.getEffects() != null && !nextScene.getEffects().IsEmpty()) { nextSceneEffects.Add(EffectsDOMWriter.EFFECTS, nextScene.getEffects()); } if (nextScene.getPostEffects() != null && !nextScene.getPostEffects().IsEmpty()) { nextSceneEffects.Add(EffectsDOMWriter.POST_EFFECTS, nextScene.getPostEffects()); } // Append the next scene DOMWriterUtility.DOMWrite(nextSceneElement, nextSceneEffects, DOMWriterUtility.DontCreateElement()); exitElement.AppendChild(nextSceneElement); } if (!exit.isRectangular()) { foreach (Vector2 point in exit.getPoints()) { XmlElement pointNode = doc.CreateElement("point"); pointNode.SetAttribute("x", ((int)point.x).ToString()); pointNode.SetAttribute("y", ((int)point.y).ToString()); exitElement.AppendChild(pointNode); } } if (exit.getConditions() != null && !exit.getConditions().IsEmpty()) { DOMWriterUtility.DOMWrite(exitElement, exit.getConditions()); } OrderedDictionary effectsTypes = new OrderedDictionary(); if (exit.getEffects() != null && !exit.getEffects().IsEmpty()) { effectsTypes.Add(EffectsDOMWriter.EFFECTS, exit.getEffects()); } if (exit.getPostEffects() != null && !exit.getPostEffects().IsEmpty()) { effectsTypes.Add(EffectsDOMWriter.POST_EFFECTS, exit.getPostEffects()); } if (exit.getNotEffects() != null && !exit.getNotEffects().IsEmpty()) { effectsTypes.Add(EffectsDOMWriter.NOT_EFFECTS, exit.getNotEffects()); } DOMWriterUtility.DOMWrite(exitElement, effectsTypes, DOMWriterUtility.DontCreateElement()); // Append the exit exitsElement.AppendChild(exitElement); } // Append the list of exits sceneElement.AppendChild(exitsElement); } // Add the item references (if there is at least one) if (scene.getItemReferences().Count > 0) { XmlNode itemsNode = doc.CreateElement("objects"); // Append every single item reference foreach (ElementReference itemReference in scene.getItemReferences()) { // Create the item reference element XmlElement itemReferenceElement = doc.CreateElement("object-ref"); itemReferenceElement.SetAttribute("idTarget", itemReference.getTargetId()); itemReferenceElement.SetAttribute("x", itemReference.getX().ToString()); itemReferenceElement.SetAttribute("y", itemReference.getY().ToString()); itemReferenceElement.SetAttribute("scale", itemReference.Scale.ToString(CultureInfo.InvariantCulture)); if (itemReference.getLayer() != -1) { itemReferenceElement.SetAttribute("layer", itemReference.getLayer().ToString()); } if (itemReference.getInfluenceArea().isExists()) { itemReferenceElement.SetAttribute("hasInfluenceArea", "yes"); InfluenceArea ia = itemReference.getInfluenceArea(); itemReferenceElement.SetAttribute("influenceX", ia.getX().ToString()); itemReferenceElement.SetAttribute("influenceY", ia.getY().ToString()); itemReferenceElement.SetAttribute("influenceWidth", ia.getWidth().ToString()); itemReferenceElement.SetAttribute("influenceHeight", ia.getHeight().ToString()); } else { itemReferenceElement.SetAttribute("hasInfluenceArea", "no"); } // Append the documentation (if avalaible) if (itemReference.getDocumentation() != null) { XmlNode itemDocumentationNode = doc.CreateElement("documentation"); itemDocumentationNode.AppendChild(doc.CreateTextNode(itemReference.getDocumentation())); itemReferenceElement.AppendChild(itemDocumentationNode); } // Append the conditions (if avalaible) if (!itemReference.Conditions.IsEmpty()) { DOMWriterUtility.DOMWrite(itemReferenceElement, itemReference.Conditions); } // Append the exit itemsNode.AppendChild(itemReferenceElement); } // Append the list of exits sceneElement.AppendChild(itemsNode); } // Add the character references (if there is at least one) if (scene.getCharacterReferences().Count > 0) { XmlNode charactersNode = doc.CreateElement("characters"); // Append every single character reference foreach (ElementReference characterReference in scene.getCharacterReferences()) { // Create the character reference element XmlElement npcReferenceElement = doc.CreateElement("character-ref"); npcReferenceElement.SetAttribute("idTarget", characterReference.getTargetId()); npcReferenceElement.SetAttribute("x", characterReference.getX().ToString()); npcReferenceElement.SetAttribute("y", characterReference.getY().ToString()); npcReferenceElement.SetAttribute("scale", characterReference.Scale.ToString(CultureInfo.InvariantCulture)); npcReferenceElement.SetAttribute("orientation", ((int)characterReference.Orientation).ToString()); if (characterReference.getLayer() != -1) { npcReferenceElement.SetAttribute("layer", characterReference.getLayer().ToString()); } if (characterReference.getInfluenceArea().isExists()) { npcReferenceElement.SetAttribute("hasInfluenceArea", "yes"); InfluenceArea ia = characterReference.getInfluenceArea(); npcReferenceElement.SetAttribute("influenceX", ia.getX().ToString()); npcReferenceElement.SetAttribute("influenceY", ia.getY().ToString()); npcReferenceElement.SetAttribute("influenceWidth", ia.getWidth().ToString()); npcReferenceElement.SetAttribute("influenceHeight", ia.getHeight().ToString()); } else { npcReferenceElement.SetAttribute("hasInfluenceArea", "no"); } // Append the documentation (if avalaible) if (characterReference.getDocumentation() != null) { XmlNode itemDocumentationNode = doc.CreateElement("documentation"); itemDocumentationNode.AppendChild(doc.CreateTextNode(characterReference.getDocumentation())); npcReferenceElement.AppendChild(itemDocumentationNode); } // Append the conditions (if avalaible) if (!characterReference.Conditions.IsEmpty()) { DOMWriterUtility.DOMWrite(npcReferenceElement, characterReference.Conditions); } // Append the exit charactersNode.AppendChild(npcReferenceElement); } // Append the list of exits sceneElement.AppendChild(charactersNode); } // Append the exits (if there is at least one) if (scene.getActiveAreas().Count > 0) { XmlNode aasElement = doc.CreateElement("active-areas"); // Append every single exit foreach (ActiveArea activeArea in scene.getActiveAreas()) { // Create the active area element XmlElement aaElement = doc.CreateElement("active-area"); if (activeArea.getId() != null) { aaElement.SetAttribute("id", activeArea.getId()); } aaElement.SetAttribute("rectangular", (activeArea.isRectangular() ? "yes" : "no")); aaElement.SetAttribute("x", activeArea.getX().ToString()); aaElement.SetAttribute("y", activeArea.getY().ToString()); aaElement.SetAttribute("width", activeArea.getWidth().ToString()); aaElement.SetAttribute("height", activeArea.getHeight().ToString()); if (activeArea.getInfluenceArea().isExists()) { aaElement.SetAttribute("hasInfluenceArea", "yes"); InfluenceArea ia = activeArea.getInfluenceArea(); aaElement.SetAttribute("influenceX", ia.getX().ToString()); aaElement.SetAttribute("influenceY", ia.getY().ToString()); aaElement.SetAttribute("influenceWidth", ia.getWidth().ToString()); aaElement.SetAttribute("influenceHeight", ia.getHeight().ToString()); } else { aaElement.SetAttribute("hasInfluenceArea", "no"); } // Behavior if (activeArea.getBehaviour() == Item.BehaviourType.NORMAL) { aaElement.SetAttribute("behaviour", "normal"); } if (activeArea.getBehaviour() == Item.BehaviourType.ATREZZO) { aaElement.SetAttribute("behaviour", "atrezzo"); } if (activeArea.getBehaviour() == Item.BehaviourType.FIRST_ACTION) { aaElement.SetAttribute("behaviour", "first-action"); } // Append the documentation (if avalaible) if (activeArea.getDocumentation() != null) { XmlNode exitDocumentationNode = doc.CreateElement("documentation"); exitDocumentationNode.AppendChild(doc.CreateTextNode(activeArea.getDocumentation())); aaElement.AppendChild(exitDocumentationNode); } // Append the conditions (if avalaible) if (!activeArea.getConditions().IsEmpty()) { DOMWriterUtility.DOMWrite(aaElement, activeArea.getConditions()); } foreach (Description description in activeArea.getDescriptions()) { // Create the description XmlNode descriptionNode = doc.CreateElement("description"); // Append the conditions (if available) if (description.getConditions() != null && !description.getConditions().IsEmpty()) { DOMWriterUtility.DOMWrite(descriptionNode, description.getConditions()); } // Create and append the name, brief description and detailed description XmlElement aaNameNode = doc.CreateElement("name"); if (description.getNameSoundPath() != null && !description.getNameSoundPath().Equals("")) { aaNameNode.SetAttribute("soundPath", description.getNameSoundPath()); } aaNameNode.AppendChild(doc.CreateTextNode(description.getName())); descriptionNode.AppendChild(aaNameNode); XmlElement aaBriefNode = doc.CreateElement("brief"); if (description.getDescriptionSoundPath() != null && !description.getDescriptionSoundPath().Equals("")) { aaBriefNode.SetAttribute("soundPath", description.getDescriptionSoundPath()); } aaBriefNode.AppendChild(doc.CreateTextNode(description.getDescription())); descriptionNode.AppendChild(aaBriefNode); XmlElement aaDetailedNode = doc.CreateElement("detailed"); if (description.getDetailedDescriptionSoundPath() != null && !description.getDetailedDescriptionSoundPath().Equals("")) { aaDetailedNode.SetAttribute("soundPath", description.getDetailedDescriptionSoundPath()); } aaDetailedNode.AppendChild(doc.CreateTextNode(description.getDetailedDescription())); descriptionNode.AppendChild(aaDetailedNode); // Append the description aaElement.AppendChild(descriptionNode); } // Append the actions (if there is at least one) if (activeArea.getActions().Count > 0) { DOMWriterUtility.DOMWrite(aaElement, activeArea.getActions()); } if (!activeArea.isRectangular()) { foreach (Vector2 point in activeArea.getPoints()) { XmlElement pointNode = doc.CreateElement("point"); pointNode.SetAttribute("x", ((int)point.x).ToString()); pointNode.SetAttribute("y", ((int)point.y).ToString()); aaElement.AppendChild(pointNode); } } // Append the exit aasElement.AppendChild(aaElement); } // Append the list of exits sceneElement.AppendChild(aasElement); } // Append the barriers (if there is at least one) if (scene.getBarriers().Count > 0) { XmlNode barriersElement = doc.CreateElement("barriers"); // Append every single barrier foreach (Barrier barrier in scene.getBarriers()) { // Create the active area element XmlElement barrierElement = doc.CreateElement("barrier"); barrierElement.SetAttribute("x", barrier.getX().ToString()); barrierElement.SetAttribute("y", barrier.getY().ToString()); barrierElement.SetAttribute("width", barrier.getWidth().ToString()); barrierElement.SetAttribute("height", barrier.getHeight().ToString()); // Append the documentation (if avalaible) if (barrier.getDocumentation() != null) { XmlNode exitDocumentationNode = doc.CreateElement("documentation"); exitDocumentationNode.AppendChild(doc.CreateTextNode(barrier.getDocumentation())); barrierElement.AppendChild(exitDocumentationNode); } // Append the conditions (if avalaible) if (!barrier.getConditions().IsEmpty()) { DOMWriterUtility.DOMWrite(barrierElement, barrier.getConditions()); } // Append the barrier barriersElement.AppendChild(barrierElement); } // Append the list of exits sceneElement.AppendChild(barriersElement); } // Add the atrezzo item references (if there is at least one) if (scene.getAtrezzoReferences().Count > 0) { XmlNode atrezzoNode = doc.CreateElement("atrezzo"); // Append every single atrezzo reference foreach (ElementReference atrezzoReference in scene.getAtrezzoReferences()) { // Create the atrezzo reference element XmlElement atrezzoReferenceElement = doc.CreateElement("atrezzo-ref"); atrezzoReferenceElement.SetAttribute("idTarget", atrezzoReference.getTargetId()); atrezzoReferenceElement.SetAttribute("x", atrezzoReference.getX().ToString()); atrezzoReferenceElement.SetAttribute("y", atrezzoReference.getY().ToString()); atrezzoReferenceElement.SetAttribute("scale", atrezzoReference.Scale.ToString(CultureInfo.InvariantCulture)); if (atrezzoReference.getLayer() != -1) { atrezzoReferenceElement.SetAttribute("layer", atrezzoReference.getLayer().ToString()); } // Append the documentation (if avalaible) if (atrezzoReference.getDocumentation() != null) { XmlNode itemDocumentationNode = doc.CreateElement("documentation"); itemDocumentationNode.AppendChild(doc.CreateTextNode(atrezzoReference.getDocumentation())); atrezzoReferenceElement.AppendChild(itemDocumentationNode); } // Append the conditions (if avalaible) if (!atrezzoReference.Conditions.IsEmpty()) { DOMWriterUtility.DOMWrite(atrezzoReferenceElement, atrezzoReference.Conditions); } // Append the atrezzo reference atrezzoNode.AppendChild(atrezzoReferenceElement); } // Append the list of atrezzo references sceneElement.AppendChild(atrezzoNode); } if (scene.getTrajectory() != null) { DOMWriterUtility.DOMWrite(sceneElement, scene.getTrajectory()); } }
private static async Task <RetObject> SendHttp(string uri, HttpMethod method = null, OrderedDictionary headers = null, CookieCollection cookies = null, string contentType = null, string body = null) { byte[] reStream; RetObject retObj = new RetObject(); HttpResponseMessage res; OrderedDictionary httpResponseHeaders = new OrderedDictionary(); CookieCollection responseCookies; CookieCollection rCookies = new CookieCollection(); List <string> setCookieValue = new List <string>(); CookieContainer coo = new CookieContainer(); dynamic dom; string htmlString = String.Empty; if (method == null) { method = HttpMethod.Get; } HttpClientHandler handle = new HttpClientHandler() { AutomaticDecompression = (DecompressionMethods)1 & (DecompressionMethods)2, UseProxy = false, AllowAutoRedirect = true, MaxAutomaticRedirections = 500 }; HttpClient client = new HttpClient(handle); if (!client.DefaultRequestHeaders.Contains("User-Agent")) { client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"); } if (client.DefaultRequestHeaders.Contains("Path")) { client.DefaultRequestHeaders.Remove("Path"); } client.DefaultRequestHeaders.Add("Path", (new Uri(uri).PathAndQuery)); List <string> headersToSkip = new List <string>(); headersToSkip.Add("Accept"); headersToSkip.Add("pragma"); headersToSkip.Add("Cache-Control"); headersToSkip.Add("Date"); headersToSkip.Add("Content-Length"); headersToSkip.Add("Content-Type"); headersToSkip.Add("Expires"); headersToSkip.Add("Last-Modified"); if (headers != null) { headersToSkip.ForEach((i) => { headers.Remove(i); }); IEnumerator enume = headers.Keys.GetEnumerator(); while (enume.MoveNext()) { string key = enume.Current.ToString(); string value = String.Join("\n", headers[key]); if (client.DefaultRequestHeaders.Contains(key)) { client.DefaultRequestHeaders.Remove(key); } try { client.DefaultRequestHeaders.Add(key, value); } catch { client.DefaultRequestHeaders.TryAddWithoutValidation(key, value); } } } //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); if (cookies != null) { IEnumerator cnume = cookies.GetEnumerator(); while (cnume.MoveNext()) { Cookie cook = (Cookie)cnume.Current; coo.Add(cook); } handle.CookieContainer = coo; } switch (method.ToString()) { case "DELETE": res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "GET": res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "HEAD": res = await client.SendAsync((new HttpRequestMessage(method, uri))); try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "OPTIONS": res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "POST": if (String.IsNullOrEmpty(contentType)) { contentType = "application/x-www-form-urlencoded"; } if (!String.IsNullOrEmpty(body)) { res = await client.SendAsync( (new HttpRequestMessage(method, uri) { Content = (new StringContent(body, Encoding.UTF8, contentType)) }) ); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); } else { res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); } responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "PUT": if (String.IsNullOrEmpty(contentType)) { contentType = "application/x-www-form-urlencoded"; } if (!String.IsNullOrEmpty(body)) { res = await client.SendAsync( (new HttpRequestMessage(method, uri) { Content = (new StringContent(body, Encoding.UTF8, contentType)) }) ); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); } else { res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); } responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; case "TRACE": res = await client.SendAsync((new HttpRequestMessage(method, uri))); if (res.Content.Headers.ContentEncoding.ToString().ToLower().Equals("gzip")) { reStream = res.Content.ReadAsByteArrayAsync().Result; htmlString = Unzip(reStream); } else { htmlString = res.Content.ReadAsStringAsync().Result; } try { setCookieValue = res.Headers.GetValues("Set-Cookie").ToList(); } catch { } res.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); res.Content.Headers.ToList().ForEach((i) => { httpResponseHeaders.Add(i.Key, i.Value); }); responseCookies = handle.CookieContainer.GetCookies(new Uri(uri)); rCookies = SetCookieParser(setCookieValue, responseCookies, cookies); dom = DOMParser(htmlString); retObj.HtmlDocument = dom; retObj.HttpResponseHeaders = httpResponseHeaders; retObj.HttpResponseMessage = res; break; } if (!String.IsNullOrEmpty(htmlString)) { retObj.ResponseText = htmlString; } retObj.CookieCollection = rCookies; return(retObj); }
private void ScheduleAppointment(int id, string subject, DateTime start, DateTime end) { IDataSource dataSource = SchedulerDataSource; DataSourceView view = dataSource.GetView("DefaultView"); IOrderedDictionary data = new OrderedDictionary(); data.Add("Subject", subject); data.Add("Start", start); data.Add("End", end); IDictionary keys = new OrderedDictionary(); keys.Add("AppointmentID", id); view.Update(keys, data, new OrderedDictionary(), OnDataSourceOperationComplete); }
//Thread initially requests identification from Client; once the connection is accepted, it waits for the Lobby List to be requested private void Receive() { TcpClient clientTcp = clientList[clientList.Count - 1]; NetworkStream networkStream = clientTcp.GetStream(); bool terminating = false; byte[] initial_BytesToRead = new byte[clientTcp.ReceiveBufferSize]; string clientName = ""; try { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("ID"); networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); } catch { tbActivity.AppendText("New client attempted to connect, failure in requesting identification.", Color.Purple); clientTcp.Close(); clientList.Remove(clientTcp); terminating = true; } if (terminating == false) { tbActivity.AppendText("New client attempting to connect, requested identification.", Color.Black); try { int byteCount = networkStream.Read(initial_BytesToRead, 0, clientTcp.ReceiveBufferSize); if (byteCount <= 0) { throw new SocketException(); } } catch { tbActivity.AppendText("Client disconnected prior to identification response.", Color.Purple); clientTcp.Close(); clientList.Remove(clientTcp); terminating = true; } } if (terminating == false) { string newmessage = Encoding.ASCII.GetString(initial_BytesToRead); newmessage = newmessage.Substring(0, newmessage.IndexOf("\0")); //NUL is always the final character of the newest message tbActivity.AppendText("Client response to identification request: " + newmessage, Color.Black); if (newmessage.Length <= 2 || newmessage.Substring(0, 2) != "ID") //Identification response must begin with "ID" and the name must be at least 1 character long { tbActivity.AppendText("Client identification response not in correct format, connection refused.", Color.Purple); try { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("FM"); //Incorrect format code networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText("Successfully responded to incorrectly formatted identification.", Color.Purple); } catch { tbActivity.AppendText("Failed to respond to incorrectly formatted identification.", Color.Purple); } terminating = true; } else { string name_substring = newmessage.Substring(2, newmessage.Length - 2); bool uniqueName = true; lock (clientLock) { if (listClients.FindStringExact(name_substring) != ListBox.NoMatches) //Check if name is already in use { uniqueName = false; } } if (!uniqueName) { tbActivity.AppendText("Client name \"" + name_substring + "\" not unique, connection refused.", Color.Purple); try { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("UN"); //Non-unique name code networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText("Successfully responded to non-unique identification.", Color.Purple); } catch { tbActivity.AppendText("Failed to respond to non-unique identification.", Color.Purple); } terminating = true; } else { try { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("OK"); networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText("Successfully responded to unique identification.", Color.Black); clientName = name_substring; //Name is unique, add to list lock (clientLock) { clientDatabase.Add(clientName, networkStream); listClients.BeginInvoke((MethodInvoker) delegate() { listClients.Items.Add(clientName); }); } } catch { tbActivity.AppendText("Failed to respond to unique identification.", Color.Purple); terminating = true; } } } } //If name is unique, establish connection while (!terminating) { try { byte[] bytesToRead = new byte[clientTcp.ReceiveBufferSize]; int byteCount = networkStream.Read(bytesToRead, 0, clientTcp.ReceiveBufferSize); if (byteCount <= 0) { throw new SocketException(); } string newmessage = Encoding.ASCII.GetString(bytesToRead); newmessage = newmessage.Substring(0, newmessage.IndexOf("\0")); tbActivity.AppendText("\"" + clientName + "\": " + newmessage, Color.Black); if (newmessage == "LS") //List request code { //Client requested Lobby List tbActivity.AppendText("Client \"" + clientName + "\" has requested the Lobby List.", Color.Blue); try { string textList; lock (clientLock) { int databaseSize = clientDatabase.Count; ////tbActivity.AppendText("List Size: " + databaseSize.ToString(), Color.YellowGreen); //Copy Client names from database to string array, then form the Lobby List String[] clientNames = new String[databaseSize]; clientDatabase.Keys.CopyTo(clientNames, 0); textList = "LS" + clientNames[0]; int listSize = clientNames.Length; for (int ctr = 1; ctr < listSize; ctr++) { textList = textList + "\n" + clientNames[ctr]; //Seperate names using newline as it cannot be a character in a client's name } textList = textList + "\0"; //NUL is always the final character of the newest message ////tbActivity.AppendText("List: " + textList, Color.YellowGreen); } byte[] bufferList = ASCIIEncoding.ASCII.GetBytes(textList); networkStream.Write(bufferList, 0, bufferList.Length); tbActivity.AppendText("Sent Lobby List to Client \"" + clientName + "\".", Color.Blue); } catch { tbActivity.AppendText("Client \"" + clientName + "\" disconnected before lobby list was sent.", Color.Purple); terminating = true; } } else if (newmessage.Length > 2) { if (newmessage.Substring(0, 2) == "CH") { unavailableClients.Add(clientName); string challenged_Name = newmessage.Substring(2); if (unavailableClients.Contains(challenged_Name)) //Challenged client is unavailable/busy { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("DE" + challenged_Name + "\0"); try { networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Client \"{challenged_Name}\" currently unavailable, automatically declined \"{clientName}\"'s challenge.", Color.Black); unavailableClients.Remove(clientName); } catch { tbActivity.AppendText("Client \"" + clientName + "\" disconnected before challenge could be automatically declined.", Color.Purple); terminating = true; } } else if (!clientDatabase.Contains(challenged_Name)) //Challenged client is no longer connected to server { byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("DX" + challenged_Name + "\0"); try { networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Client \"{challenged_Name}\" does not exist, notified \"{clientName}\".", Color.Black); unavailableClients.Remove(clientName); } catch { tbActivity.AppendText($"Client \"{challenged_Name}\" does not exist, failed to notify \"{clientName}\".", Color.Purple); terminating = true; } } else //Challenged client is available { unavailableClients.Add(challenged_Name); byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("CH" + clientName + "\0"); NetworkStream challenged_networkStream = (NetworkStream)clientDatabase[challenged_Name]; try { challenged_networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Sent challenge from \"{clientName}\" to \"{challenged_Name}\".", Color.Black); } catch { tbActivity.AppendText($"Failed to send challenge from \"{clientName}\" to \"{challenged_Name}\".", Color.Purple); bytesToWrite = ASCIIEncoding.ASCII.GetBytes("DE" + challenged_Name + "\0"); try { networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Client \"{challenged_Name}\" currently unavailable, automatically declined {clientName}'s challenge.", Color.Black); } catch { tbActivity.AppendText("Client \"" + clientName + "\" disconnected before challenge could be automatically declined.", Color.Purple); terminating = true; } unavailableClients.Remove(clientName); unavailableClients.Remove(challenged_Name); } } } else if (newmessage.Substring(0, 2) == "AC") { string accepted_Name = newmessage.Substring(2); byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("AC" + clientName + "\0"); NetworkStream accepted_networkStream = (NetworkStream)clientDatabase[accepted_Name]; try { accepted_networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Accepted challenge from \"{accepted_Name}\" to \"{clientName}\".", Color.Black); gameClientPairs.Add(accepted_Name, clientName); } catch { tbActivity.AppendText($"Failed to accept challenge from \"{accepted_Name}\" to \"{clientName}\".", Color.Purple); bytesToWrite = ASCIIEncoding.ASCII.GetBytes("GMch\0"); try { networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Client \"{accepted_Name}\" disconnected after sending invite, sent notice to \"{clientName}\".", Color.Black); } catch { tbActivity.AppendText($"Client \"{accepted_Name}\" disconnected after sending invite, failed to send notice to \"{clientName}\".", Color.Purple); terminating = true; } unavailableClients.Remove(clientName); unavailableClients.Remove(accepted_Name); } } else if (newmessage.Substring(0, 2) == "DE") { unavailableClients.Remove(clientName); string declined_Name = newmessage.Substring(2); byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("DE" + clientName + "\0"); NetworkStream declined_networkStream = (NetworkStream)clientDatabase[declined_Name]; try { declined_networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"Declined challenge from \"{declined_Name}\" to \"{clientName}\".", Color.Black); } catch { tbActivity.AppendText($"Failed to decline challenge from \"{declined_Name}\" to \"{clientName}\".", Color.Purple); } unavailableClients.Remove(declined_Name); } else if (newmessage.Substring(0, 2) == "GM") { if (newmessage.Length > 4 && newmessage.Substring(2, 2) == "ed") { string winner_Name = newmessage.Substring(4); byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("GMed\0"); NetworkStream winner_networkStream = (NetworkStream)clientDatabase[winner_Name]; try { winner_networkStream.Write(bytesToWrite, 0, bytesToWrite.Length); tbActivity.AppendText($"\"{clientName}\" has surrendered, \"{winner_Name}\" is the winner!", Color.Black); } catch { tbActivity.AppendText($"\"{clientName}\" has surrendered, but failed to notify \"{winner_Name}\" that they won.", Color.Purple); } removeFrom_clientListPairs(clientName); unavailableClients.Remove(clientName); unavailableClients.Remove(winner_Name); } } } } catch { tbActivity.AppendText("Client \"" + clientName + "\" has disconnected.", Color.Purple); terminating = true; } } //Post-disconnect cleanup lock (clientLock) { /*var itemsToRemove = clientDatabase.Where(kvp => kvp.Key.Equals(clientName)); * foreach (var item in itemsToRemove) * { * NetworkStream val = item.Value; * clientDatabase.TryRemove(clientName, out val); * }*/ clientDatabase.Remove(clientName); listClients.BeginInvoke((MethodInvoker) delegate() { listClients.Items.Remove(clientName); }); } removeFrom_clientListPairs_DC(clientName); unavailableClients.Remove(clientName); clientList.Remove(clientTcp); clientTcp.Close(); }
public void AddTests() { var d = new OrderedDictionary(); d.Add((int)5, "foo1"); Assert.Equal("foo1", d[(object)((int)5)]); d.Add((double)5, "foo2"); Assert.Equal("foo2", d[(object)((double)5)]); d.Add((long)5, "foo3"); Assert.Equal("foo3", d[(object)((long)5)]); d.Add((short)5, "foo4"); Assert.Equal("foo4", d[(object)((short)5)]); d.Add((uint)5, "foo5"); Assert.Equal("foo5", d[(object)((uint)5)]); d.Add("5", "foo6"); Assert.Equal("foo6", d["5"]); Assert.Throws <ArgumentException>(() => d.Add((int)5, "foo")); Assert.Throws <ArgumentException>(() => d.Add((double)5, "foo")); Assert.Throws <ArgumentException>(() => d.Add((long)5, "foo")); Assert.Throws <ArgumentException>(() => d.Add((short)5, "foo")); Assert.Throws <ArgumentException>(() => d.Add((uint)5, "foo")); Assert.Throws <ArgumentException>(() => d.Add("5", "foo")); Assert.Throws <ArgumentNullException>(() => d.Add(null, "foobar")); }
static void Main(string[] args) { Dictionary <string, OrderedBag <Order> > consumerToMap = new Dictionary <string, OrderedBag <Order> >(); OrderedDictionary <double, List <Order> > priceToMap = new OrderedDictionary <double, List <Order> >(); int numberOfTurns = int.Parse(Console.ReadLine()); for (int i = 0; i < numberOfTurns; i++) { string[] commandLine = Console.ReadLine().Split(new[] { ' ' }, 2).ToArray(); switch (commandLine[0]) { case "AddOrder": string[] addDetails = commandLine[1].Split(';'); string name = addDetails[0]; double price = double.Parse(addDetails[1]); string consumer = addDetails[2]; Order order = new Order(name, consumer, price); if (!priceToMap.ContainsKey(price)) { priceToMap.Add(price, new List <Order>()); } priceToMap[price].Add(order); if (!consumerToMap.ContainsKey(consumer)) { consumerToMap.Add(consumer, new OrderedBag <Order>()); } consumerToMap[consumer].Add(order); Console.WriteLine("Order added"); break; case "DeleteOrders": if (consumerToMap.ContainsKey(commandLine[1])) { OrderedBag <Order> subset = consumerToMap[commandLine[1]]; foreach (Order set in subset) { priceToMap[set.Price].Remove(set); } consumerToMap.Remove(commandLine[1]); Console.WriteLine(subset.Count + " orders deleted"); } else { Console.WriteLine("No orders found"); } break; case "FindOrdersByPriceRange": string[] priceDetails = commandLine[1].Split(';'); double min = double.Parse(priceDetails[0]); double max = double.Parse(priceDetails[1]); OrderedBag <Order> priceBetweenMinMax = new OrderedBag <Order>(); foreach (var items in priceToMap.Range(min, true, max, true).Values) { foreach (var item in items) { priceBetweenMinMax.Add(item); } } if (priceBetweenMinMax.Any()) { foreach (Order item in priceBetweenMinMax) { Console.WriteLine(item); } } else { Console.WriteLine("No orders found"); } break; case "FindOrdersByConsumer": if (consumerToMap.ContainsKey(commandLine[1])) { foreach (Order purchase in consumerToMap[commandLine[1]]) { Console.WriteLine(purchase); } } else { Console.WriteLine("No orders found"); } break; } } }
private void PurgeFiles(string dirPath) { try { DateTime today = DateTime.Now.Date; TimeSpan keepBuffer = new TimeSpan(_daysToKeep, 0, 0, 0); if (!_dailyTotals.Contains(today)) { _dailyTotals[today] = (long)0; } string[] folders = Directory.GetDirectories(dirPath, "*", SearchOption.AllDirectories); foreach (string folder in folders) { string[] files = Directory.GetFiles(folder, "*", SearchOption.TopDirectoryOnly); if (files.Length == 0) { // don't process empty folders continue; } _log.Info(String.Format("Purging folder {0} -> {1} files", folder, files.Length)); CleanupStats stats = new CleanupStats() { totalBytes = 0, totalFiles = 0 }; foreach (string file in files) { try { FileInfo fi = new FileInfo(file); stats.totalBytes += fi.Length; stats.totalFiles++; stats.folder = folder; try { if (fi.LastWriteTime > today - keepBuffer) { // recently created archive, so don't delete _log.Debug("Not deleting recent file " + file); continue; } if (_simulate == true) { _log.Debug("Would have deleted " + file); } else { File.Delete(file); _dailyTotals[today] = (object)((long)_dailyTotals[today] + stats.totalBytes); } } catch (Exception ex) { _log.Error("File.Delete try PurgeFiles: " + ex.Message); } } catch (Exception ex) { _log.Error("Inner try PurgeFiles: " + ex.Message); } } _stats.Add(DateTime.Now, stats); } } catch (Exception ex) { _log.Error("Outer try PurgeFiles: " + ex.Message); } }
public NewMediumLevelRecordEditor(Plugin p, Record r, SubRecord sr, SubrecordStructure ss) { InitializeComponent(); Icon = Resources.tesv_ico; SuspendLayout(); this.sr = sr; this.ss = ss; this.p = p; this.r = r; // walk each element in standard fashion int panelOffset = 0; try { foreach (var elem in ss.elements) { Control c = null; if (elem.options != null && elem.options.Length > 1) { c = new OptionsElement(); } else if (elem.flags != null && elem.flags.Length > 1) { c = new FlagsElement(); } else { switch (elem.type) { case ElementValueType.LString: c = new LStringElement(); break; case ElementValueType.FormID: c = new FormIDElement(); break; case ElementValueType.Blob: c = new HexElement(); break; default: c = new TextElement(); break; } } if (c is IElementControl) { var ec = c as IElementControl; ec.formIDLookup = p.GetRecordByID; ec.formIDScan = p.EnumerateRecords; ec.strIDLookup = p.LookupFormStrings; ec.Element = elem; if (elem.repeat > 0) { var ge = new RepeatingElement(); c = ge; c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; ge.InnerControl = ec; ge.Element = elem; ec = ge; } else if (elem.optional) { var re = new OptionalElement(); c = re; c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; re.InnerControl = ec; re.Element = elem; ec = re; c = re; } else { c.Left = 8; c.Width = fpanel1.Width - 16; c.Top = panelOffset; c.Anchor = c.Anchor | AnchorStyles.Left | AnchorStyles.Right; } c.MinimumSize = c.Size; controlMap.Add(elem, ec); fpanel1.Controls.Add(c); panelOffset = c.Bottom; } } foreach (Element elem in r.EnumerateElements(sr, true)) { var es = elem.Structure; IElementControl c; if (controlMap.TryGetValue(es, out c)) { if (c is IGroupedElementControl) { var gc = c as IGroupedElementControl; gc.Elements.Add(elem.Data); } else { c.Data = elem.Data; } } } } catch { strWarnOnSave = "The subrecord doesn't appear to conform to the expected structure.\nThe formatted information may be incorrect."; Error.SetError(bSave, strWarnOnSave); Error.SetIconAlignment(bSave, ErrorIconAlignment.MiddleLeft); AcceptButton = bCancel; // remove save as default button when exception occurs CancelButton = bCancel; UpdateDefaultButton(); } ResumeLayout(); }
static void Main(string[] args) { OrderedDictionary FamilyRoots = new OrderedDictionary(); List <Tuple <string, string, Storage> > bucket = new List <Tuple <string, string, Storage> >(); object _sync = new object(); //if there are no directories on the command line just die if (args.Length < 1) { Console.WriteLine("Please provide a folder to process."); return; } //go through all the familes in the tree Console.WriteLine("Searching for Revit Families..."); string[] FilesInPath = Directory.GetFiles(args[0], "*.rfa", SearchOption.AllDirectories); string rootCRC = ""; Console.WriteLine("Found {0} Revit families to process", FilesInPath.Length); Parallel.ForEach(FilesInPath, (file) => { //Console.WriteLine("\nProcessing {0}...", file); Storage storage = new Storage(file); //is this a valid revit (family) file? If not then just skip and move on to the next one if (storage.IsInitialized == false) { Console.WriteLine("[ERROR] {0} doesn't seem to be a valid Family", file); } else { //get the CRC of the root partition of the family rootCRC = (string)storage.PartitionsInfo.Partitions[0]; //Console.WriteLine("CRC of partition 0: {0}", rootCRC); } bucket.Add(Tuple.Create(rootCRC, file, storage)); }); //find the root of the family tree, if there is no tree for this root, start a new tree //and send the family in for generating the tree foreach (Tuple <string, string, Storage> fam in bucket) { FamilyNode f = null; try { f = (FamilyNode)FamilyRoots[fam.Item1]; f.AddChild(fam.Item1, fam.Item2, fam.Item3); //this will trace the tree internaly } catch { //no tree exists for this CRC f = new FamilyNode(fam.Item1, fam.Item2, fam.Item3); FamilyRoots.Add(fam.Item1, f); } } //display the tree of results int uniqueCount = 0; foreach (FamilyNode f in FamilyRoots.Values) { Console.WriteLine("CRC: {0}\t{1}", f.rootCRC, f.files.First <string>()); uniqueCount++; if (f.files.Count > 1) { foreach (string same in f.files.Skip(1)) { Console.WriteLine("\t\t{0}", same); } } } Console.WriteLine("\nFrom the {0} families, {1} are UNIQUE.", FilesInPath.Length, uniqueCount); timer.Stop(); Console.WriteLine("Processed in {0} ms.", timer.ElapsedMilliseconds); }
public void Add(TKey key, TValue value) { _backing.Add(key, value); }
public static void Main() { //<Snippet01> // Creates and initializes a OrderedDictionary. OrderedDictionary myOrderedDictionary = new OrderedDictionary(); myOrderedDictionary.Add("testKey1", "testValue1"); myOrderedDictionary.Add("testKey2", "testValue2"); myOrderedDictionary.Add("keyToDelete", "valueToDelete"); myOrderedDictionary.Add("testKey3", "testValue3"); ICollection keyCollection = myOrderedDictionary.Keys; ICollection valueCollection = myOrderedDictionary.Values; // Display the contents using the key and value collections DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count); //</Snippet01> //<Snippet02> // Modifying the OrderedDictionary if (!myOrderedDictionary.IsReadOnly) { // Insert a new key to the beginning of the OrderedDictionary myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1"); // Modify the value of the entry with the key "testKey2" myOrderedDictionary["testKey2"] = "modifiedValue"; // Remove the last entry from the OrderedDictionary: "testKey3" myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1); // Remove the "keyToDelete" entry, if it exists if (myOrderedDictionary.Contains("keyToDelete")) { myOrderedDictionary.Remove("keyToDelete"); } } //</Snippet02> Console.WriteLine( "{0}Displaying the entries of a modified OrderedDictionary.", Environment.NewLine); DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count); //<Snippet03> // Clear the OrderedDictionary and add new values myOrderedDictionary.Clear(); myOrderedDictionary.Add("newKey1", "newValue1"); myOrderedDictionary.Add("newKey2", "newValue2"); myOrderedDictionary.Add("newKey3", "newValue3"); // Display the contents of the "new" Dictionary using an enumerator IDictionaryEnumerator myEnumerator = myOrderedDictionary.GetEnumerator(); Console.WriteLine( "{0}Displaying the entries of a \"new\" OrderedDictionary.", Environment.NewLine); DisplayEnumerator(myEnumerator); //</Snippet03> Console.ReadLine(); }
public void Add(string key, T value) { Items.Add(key, value); }
/// <summary> /// Deletes all the connections and saves their data (the start and end port) /// so that they can be recreated if needed. /// </summary> /// <param name="portConnections">A list of connections that will be destroyed</param> private void SaveAndDeleteConnectors(OrderedDictionary inportConnections, OrderedDictionary outportConnections) { //----------------------------Inputs--------------------------------- for (int i = 0; i < InPorts.Count; i++) { PortModel portModel = InPorts[i]; string portName = portModel.ToolTipContent; if (portModel.Connectors.Count != 0) { inportConnections.Add(portName, new List <PortModel>()); foreach (ConnectorModel connector in portModel.Connectors) { (inportConnections[portName] as List <PortModel>).Add(connector.Start); Workspace.UndoRecorder.RecordDeletionForUndo(connector); } } else { inportConnections.Add(portName, null); } } //Delete the connectors foreach (PortModel inport in InPorts) { inport.DestroyConnectors(); } //Clear out all the port models for (int i = InPorts.Count - 1; i >= 0; i--) { InPorts.RemoveAt(i); } //----------------------------Outputs--------------------------------- for (int i = 0; i < OutPorts.Count; i++) { PortModel portModel = OutPorts[i]; string portName = portModel.ToolTipContent; if (portModel.ToolTipContent.Equals(Formatting.ToolTipForTempVariable)) { portName += i.ToString(CultureInfo.InvariantCulture); } if (portModel.Connectors.Count != 0) { outportConnections.Add(portName, new List <PortModel>()); foreach (ConnectorModel connector in portModel.Connectors) { (outportConnections[portName] as List <PortModel>).Add(connector.End); Workspace.UndoRecorder.RecordDeletionForUndo(connector); } } else { outportConnections.Add(portName, null); } } //Delete the connectors foreach (PortModel outport in OutPorts) { outport.DestroyConnectors(); } //Clear out all the port models for (int i = OutPorts.Count - 1; i >= 0; i--) { OutPorts.RemoveAt(i); } }
public void SaveProfileToDatabase(string usr) { if (ew_Empty(usr) || usr == EW_ADMIN_USER_NAME) // Ignore hard code admin return; string sFilter = EW_USER_NAME_FILTER.Replace("%u", ew_AdjustSql(usr)); OrderedDictionary RsProfile = new OrderedDictionary(); RsProfile.Add(EW_USER_PROFILE_FIELD_NAME, ProfileToString()); // Update Profile UserTable.CurrentFilter = sFilter; // ASPX81 UserTable.Update(ref RsProfile); // ASPX81 //ew_Execute("UPDATE " + EW_USER_TABLE + " SET " + EW_USER_PROFILE_FIELD_NAME + "='" + ew_AdjustSql(ProfileToString()) + "' WHERE " + sFilter); ew_Session[EW_SESSION_USER_PROFILE] = ProfileToString(); }
private OrderedDictionary CreatePayeTable(string YearSelected, out decimal personalAllowance, out string taxCodeLetter) { OrderedDictionary payetable = new OrderedDictionary(); personalAllowance = 0m; taxCodeLetter = ""; decimal numericAmount = 0m; List <string> TaxCodes = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandCodes//@letter"); List <string> TaxCodesEndLetters = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandEndLetters/Letter"); List <string> TaxCodesStartLetters = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandStartLetters/Letter"); //If no Tax code was enter, use default and call method again. if (TaxCode.Text == "") { TaxCode.Text = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Default").First(); payetable = CreatePayeTable(YearSelected, out personalAllowance, out taxCodeLetter); } else if (TaxCodes.Contains(TaxCode.Text)) //Checks for single rate NT, BR, D0 etc. { payetable = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/BandCodes/code[@letter='" + TaxCode.Text + "']"); } //The case for the L (and related) codes is complex. We need to take into consideration that the personal Allowance //reduces by 2 after the salary goes past £100,000 (the adjusted level). //To do this, the rate will be increased by 1.5 post £100,000 until the personal allowance reaches 0. //This threshold will be 100,000 + 2 * personal allowance. else if (TaxCodesEndLetters.Contains(TaxCode.Text.Substring(TaxCode.Text.Length - 1, 1))) { if (decimal.TryParse(TaxCode.Text.Substring(0, TaxCode.Text.Length - 1), out numericAmount)) { personalAllowance = numericAmount * 10 + 9; OrderedDictionary payetableRate = new OrderedDictionary(); payetableRate = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Bands", personalAllowance); decimal Adjusted = 0; if (ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Adjusted").Count == 1) { Adjusted = Convert.ToDecimal(ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Adjusted").First()); } if (Adjusted != 0) { decimal AdjustedUpper = Adjusted + 2 * (personalAllowance - 9); int i = 0; decimal Bound = 0; decimal Rate = 0; decimal RateAdjusted = 0; int NumberOfEntries = payetableRate.Count; payetable.Add(Bound, Rate); //3 stages here //i. Add thresholds below the Adjusted level //ii. Add thresholds between Adjusted level and Adjusted level + 2 * personal allowance //iii. Add thresholds post Adjusted level + 2 * personal allowance //Stage i while (true) //infinite loop but breaking when either of two conditions are met { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); if (Bound < Adjusted) { payetable.Add(Bound, Rate); } else //break when Adjusted level is reached { RateAdjusted = Convert.ToDecimal(payetableRate[i - 1]) * 1.5m; payetable.Add(Adjusted, RateAdjusted); break; } if (i < NumberOfEntries - 1) { i++; } else //break also when end of table is reached { RateAdjusted = Convert.ToDecimal(payetableRate[i]) * 1.5m; payetable.Add(Adjusted, RateAdjusted); break; } } //Stage ii decimal BoundAdjusted = 0; while (AdjustedUpper > Bound - personalAllowance) { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); if (Bound < Adjusted) { Rate = Convert.ToDecimal(payetableRate[i]); payetable.Add(AdjustedUpper, Rate); break; } if (Bound - personalAllowance < AdjustedUpper) { BoundAdjusted = AdjustedUpper / 3 + 2 * (Bound - personalAllowance) / 3; RateAdjusted = Convert.ToDecimal(payetableRate[i]) * 1.5m; payetable.Add(BoundAdjusted, RateAdjusted); } else { Rate = Convert.ToDecimal(payetableRate[i - 1]); payetable.Add(AdjustedUpper, Rate); break; } if (i < NumberOfEntries - 1) { i++; } else { Rate = Convert.ToDecimal(payetableRate[i]); payetable.Add(AdjustedUpper, Rate); break; } } //Stage iii while (true)//infinite loop but breaking when either of two conditions are met { Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); if (Bound - personalAllowance > AdjustedUpper) { payetable.Add(Bound - personalAllowance, Rate); } else { break; } //breaks if this threshold is last in table if (i < NumberOfEntries - 1) { i++; } //breaks when end of table is reached else { break; } } } else //Case when there is no adjusted level { int i = 0; decimal Bound = 0; decimal Rate = 0; int NumberOfEntries = payetableRate.Count; while (i < NumberOfEntries) { payetable.Add(Bound, Rate); Bound = Convert.ToDecimal(payetableRate.Cast <DictionaryEntry>().ElementAt(i).Key); Rate = Convert.ToDecimal(payetableRate[i]); i++; } } taxCodeLetter = TaxCode.Text.Substring(TaxCode.Text.Length - 1, 1); } } else if (TaxCodesStartLetters.Contains(TaxCode.Text.Substring(0, 1))) //Case for K codes { if (decimal.TryParse(TaxCode.Text.Substring(1, TaxCode.Text.Length - 1), out numericAmount)) { personalAllowance = -numericAmount * 10; payetable = ReadRatesXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Bands", personalAllowance); taxCodeLetter = TaxCode.Text.Substring(0, 1); } } else //Case for invalid tax code enter. Then use default and call method again { TaxCode.Text = ReadXML("//YearEnd[@Year='" + YearSelected + "']/PAYE/Default").First(); payetable = CreatePayeTable(YearSelected, out personalAllowance, out taxCodeLetter); } return(payetable); }
private void CollectFromStateList(RegistryObjectVariantGroup variantGroup, RegistryObjectVariantGroup[] variantgroups, OrderedDictionary <string, VariantEntry[]> variantsMul, List <ResolvedVariant> blockvariantsFinal, AssetLocation filename) { if (variantGroup.Code == null) { api.Server.LogError( "Error in itemtype {0}, a variantgroup using a state list must have a code. Ignoring.", filename ); return; } string[] states = variantGroup.States; string type = variantGroup.Code; // Additive state list if (variantGroup.Combine == EnumCombination.Add) { for (int j = 0; j < states.Length; j++) { ResolvedVariant resolved = new ResolvedVariant(); resolved.CodeParts.Add(type, states[j]); blockvariantsFinal.Add(resolved); } } // Multiplicative state list if (variantGroup.Combine == EnumCombination.Multiply) { List <VariantEntry> stateList = new List <VariantEntry>(); for (int j = 0; j < states.Length; j++) { stateList.Add(new VariantEntry() { Code = states[j] }); } for (int i = 0; i < variantgroups.Length; i++) { RegistryObjectVariantGroup cvg = variantgroups[i]; if (cvg.Combine == EnumCombination.SelectiveMultiply && cvg.OnVariant == variantGroup.Code) { for (int k = 0; k < stateList.Count; k++) { if (cvg.Code != stateList[k].Code) { continue; } VariantEntry old = stateList[k]; stateList.RemoveAt(k); for (int j = 0; j < cvg.States.Length; j++) { List <string> codes = old.Codes == null ? new List <string>() { old.Code } : old.Codes; List <string> types = old.Types == null ? new List <string>() { variantGroup.Code } : old.Types; codes.Add(cvg.States[j]); types.Add(cvg.Code); stateList.Insert(k, new VariantEntry() { Code = old.Code + "-" + cvg.States[j], Codes = codes, Types = types }); } } } } if (variantsMul.ContainsKey(type)) { stateList.AddRange(variantsMul[type]); variantsMul[type] = stateList.ToArray(); } else { variantsMul.Add(type, stateList.ToArray()); } } }
/// <summary> /// Handles when the player selects a new class. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance containing the event data.</param> private void ClassComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { //Update hit point related text boxes HitDiceTextBox.Text = hitDiceList[ClassListBox.SelectedIndex].ToString(); HitPoints1stLevelTextBox.Text = hitPoints1stLevelList[ClassListBox.SelectedIndex].ToString(); HitPointsHigherLevelTextBox.Text = hitPointsHigherLevelList[ClassListBox.SelectedIndex].ToString(); //Update proficiency related text boxes ArmorProficiencyTextBox.Text = armorProficiencyList[ClassListBox.SelectedIndex].ToString(); WeaponsProficiencyTextBox.Text = weaponsProficiencyList[ClassListBox.SelectedIndex].ToString(); ToolsProficiencyTextBox.Text = toolsProficiencyList[ClassListBox.SelectedIndex].ToString(); ThrowsProficiencyTextBox.Text = throwsProficiencyList[ClassListBox.SelectedIndex].ToString(); //Enable the equipment combo box EquipmentComboBox.IsEnabled = true; //Initialize the class skills list List <string> classSkillsList = new List <string>(); //The skills list will be cleared, so enable the buttons AddButton.IsEnabled = true; RemoveButton.IsEnabled = true; SkillsComboBox.IsEnabled = true; FeaturesTextBox.Text = featuresList[ClassListBox.SelectedIndex].ToString(); //Take a look at the selected item ListBoxItem item = ClassListBox.SelectedValue as ListBoxItem; switch (item.Content as string) { case "Barbarian": //Set the skills classSkillsList.Add("Animal Handling"); classSkillsList.Add("Athletics"); classSkillsList.Add("Intimidation"); classSkillsList.Add("Nature"); classSkillsList.Add("Perception"); classSkillsList.Add("Survival"); //Set the equipment equipmentList.Clear(); equipmentList.Add("Pack A", "A greataxe\nTwo handaxes\nAn explorer's pack and four javelins"); equipmentList.Add("Pack B", "Any martial melee weapon\nTwo handaxes\nAn explorer's pack and four javelins"); equipmentList.Add("Pack C", "A greataxe\nAny simple weapon\nAn explorer's pack and four javelins"); equipmentList.Add("Pack D", "Any martial melee weapon\nAny simple weapon\nAn explorer's pack and four javelins"); //Set the number of skills that a player can choose numberOfSkills = 2; break; case "Cleric": //Set the skills classSkillsList.Add("History"); classSkillsList.Add("Insight"); classSkillsList.Add("Medicine"); classSkillsList.Add("Persuasion"); classSkillsList.Add("Religion"); //Set the equipment equipmentList.Clear(); equipmentList.Add("Pack A", "A mace\nScale mail\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack B", "A warhammer\nScale mail\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack C", "A mace\nLeather armor\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack D", "A warhammer\nLeather armor\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack E", "A mace\nChain mail\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack F", "A warhammer\nChain mail\nA light crossbow and 20 bolts\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack G", "A mace\nScale mail\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack H", "A warhammer\nScale mail\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack I", "A mace\nLeather armor\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack J", "A warhammer\nLeather armor\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack K", "A mace\nChain mail\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack L", "A warhammer\nChain mail\nAny simple weapon\nA priest's pack\nA shield and a holy symbol"); equipmentList.Add("Pack M", "A mace\nScale mail\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack N", "A warhammer\nScale mail\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack O", "A mace\nLeather armor\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack P", "A warhammer\nLeather armor\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack Q", "A mace\nChain mail\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack R", "A warhammer\nChain mail\nA light crossbow and 20 bolts\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack S", "A mace\nScale mail\nAny simple weapon\nAn explorer's pack\nA shield and a holy symbol"); equipmentList.Add("Pack T", "A warhammer\nScale mail\nAny simple weapon\nAn explorer's pack\nA shield and a holy symbol"); //Set the number of skills that a player can choose numberOfSkills = 2; break; case "Rogue": //Set the skills classSkillsList.Add("Acrobatics"); classSkillsList.Add("Athletics"); classSkillsList.Add("Deception"); classSkillsList.Add("Insight"); classSkillsList.Add("Intimidation"); classSkillsList.Add("Investigation"); classSkillsList.Add("Perception"); classSkillsList.Add("Performance"); classSkillsList.Add("Persuasion"); classSkillsList.Add("Sleight of Hand"); classSkillsList.Add("Stealth"); //Set the equipment equipmentList.Clear(); equipmentList.Add("Pack A", "A rapier\nA shortbow and quiver of 20 arrows\nA burglar's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack B", "A shortsword\nA shortbow and quiver of 20 arrows\nA burglar's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack C", "A rapier\nA shortsword\nA burglar's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack D", "A rapier\nA shortbow and quiver of 20 arrows\nA dungeoneer's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack E", "A shortsword\nA shortbow and quiver of 20 arrows\nA dungeoneer's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack F", "A rapier\nA shortsword\nA dungeoneer's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack G", "A rapier\nA shortbow and quiver of 20 arrows\nA explorer's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack H", "A shortsword\nA shortbow and quiver of 20 arrows\nA explorer's pack\nLeather armor, two daggers, and thieves' tools"); equipmentList.Add("Pack I", "A rapier\nA shortsword\nA explorer's pack\nLeather armor, two daggers, and thieves' tools"); //Set the number of skills that a player can choose numberOfSkills = 4; break; case "Wizard": //Set the skills classSkillsList.Add("Arcana"); classSkillsList.Add("History"); classSkillsList.Add("Insight"); classSkillsList.Add("Investigation"); classSkillsList.Add("Medicine"); classSkillsList.Add("Religion"); //Set the equipment equipmentList.Clear(); equipmentList.Add("Pack A", "A quarterstaff\nA component pouch\nA scholar's pack\nA spellbook"); equipmentList.Add("Pack B", "A dagger\nA component pouch\nA scholar's pack\nA spellbook"); equipmentList.Add("Pack C", "A quarterstaff\nAn arcane focus\nA scholar's pack\nA spellbook"); equipmentList.Add("Pack D", "A dagger\nAn arcane focus\nA scholar's pack\nA spellbook"); equipmentList.Add("Pack E", "A quarterstaff\nA component pouch\nA explorer's pack\nA spellbook"); equipmentList.Add("Pack F", "A dagger\nA component pouch\nA explorer's pack\nA spellbook"); equipmentList.Add("Pack G", "A quarterstaff\nAn arcane focus\nA explorer's pack\nA spellbook"); equipmentList.Add("Pack H", "A dagger\nAn arcane focus\nA explorer's pack\nA spellbook"); //Set the number of skills that a player can choose numberOfSkills = 2; break; } //Update equipment related fields EquipmentComboBox.ItemsSource = equipmentList.Keys; EquipmentComboBox.SelectedIndex = 0; EquipmentTextBox.Text = equipmentList[EquipmentComboBox.SelectedIndex].ToString(); //Update skills related fields SkillsComboBox.ItemsSource = classSkillsList; SkillsListBox.ItemsSource = new List <string>(); SkillsComboBox.SelectedIndex = 0; }
public void TestCount() { od.Count.Should().Be(3); od.Add("d", 4); od.Count.Should().Be(4); }
private DispatchResult DispatchUnaryOperation(UnaryOperationBinder binder, Object arg1) { var old_value = Value; Value = arg1; try { try { try { var result = UnaryOperation(binder); if (result is FallbackException) throw (FallbackException)result; return Succeed(result); } catch (FallbackException) { var dynamic_object = Value as IDynamicObject; if (dynamic_object != null) return Succeed(dynamic_object.UnaryOperation(binder)); else throw; } } catch (FallbackException) { return Fail(); } catch (Exception ex) { if (WrapExceptions) { var bind_args = new OrderedDictionary<String, Object>(); bind_args.Add("arg1", arg1); throw new BindException(binder, bind_args, ex); } else { throw; } } } finally { Value = old_value; } }
private static EntitySet CreateEntitySet(XElement element, string containerAlias) { DateTime updateDate; DateTime.TryParse((element.Element("lastupdatedate") ?? new XElement("Dumb")).Value, out updateDate); DateTime releaseDate; if (!DateTime.TryParse((element.Element("releaseddate") ?? new XElement("Dumb")).Value, out releaseDate)) { releaseDate = updateDate; } DateTime expiredDate; DateTime.TryParse((element.Element("expireddate") ?? new XElement("Dumb")).Value, out expiredDate); List <OrderedDictionary> downloadlinks = new List <OrderedDictionary>(); foreach (XElement link in element.Element("downloadlinks").Elements()) { OrderedDictionary dod = new OrderedDictionary(); dod.Add("Name", link.Element("downloadlinkname").Value.ToString()); dod.Add("Type", link.Element("downloadlinktype").Value.ToString()); dod.Add("Link", link.Element("downloadlinkurl").Value.ToString()); dod.Add("IconLink", link.Element("downloadlinkiconurl").Value.ToString()); dod.Add("Description", link.Element("downloadlinkdescription").Value.ToString()); dod.Add("DownloadCount", link.Element("downloadcount").Value.ToString()); dod.Add("ID", link.Element("downloadid").Value.ToString()); downloadlinks.Add(dod); } return(new EntitySet( new Guid(element.Element("entityid").Value), element.Element("datasetname") != null ? element.Element("datasetname").Value : null, //element.Element("description") != null ? element.Element("description").Value : null, element.Element("entitykind") != null ? element.Element("entitykind").Value : null, element.Element("category") != null ? element.Element("category").Value : null, element.Element("description") != null ? element.Element("description").Value : null, element.Element("datasource") != null ? element.Element("datasource").Value : null, element.Element("datasourcedescription") != null ? element.Element("datasourcedescription").Value : null, element.Element("metadataurl") != null ? element.Element("metadataurl").Value : null, element.Element("entityset") != null ? element.Element("entityset").Value : null, element.Element("downloadlink") != null ? element.Element("downloadlink").Value : null, //element.Element("longlatcolumns") != null ? element.Element("longlatcolumns").Value : null, //element.Element("kmlcolumn") != null ? element.Element("kmlcolumn").Value : null, element.Element("datasvclink") != null ? element.Element("datasvclink").Value : null, element.Element("datasvckmllink") != null ? element.Element("datasvckmllink").Value : null, element.Element("datasvckmltype") != null ? element.Element("datasvckmltype").Value : null, containerAlias, element.Element("datasetimage") != null ? element.Element("datasetimage").Value : null, downloadlinks ) { LastUpdateDate = updateDate, ReleasedDate = releaseDate, ExpiredDate = expiredDate, UpdateFrequency = element.Element("updatefrequency") != null?element.Element("updatefrequency").Value : null, Keywords = element.Element("keywords") != null?element.Element("keywords").Value : null, Links = element.Element("links") != null?element.Element("links").Value : null, PeriodCovered = element.Element("periodcovered") != null?element.Element("periodcovered").Value : null, GeographicCoverage = element.Element("geographiccoverage") != null?element.Element("geographiccoverage").Value : null, AdditionalInformation = element.Element("additionalinfo") != null?element.Element("additionalinfo").Value : null, IsEmpty = element.Element("isempty") != null && element.Element("isempty").Value.Length == 4, CollectionMode = element.Element("collectionmode") != null?element.Element("collectionmode").Value : null, CollectionInstruments = element.Element("collectioninstruments") != null?element.Element("collectioninstruments").Value : null, DataDictionaryVariables = element.Element("datadictionary_variables") != null?element.Element("datadictionary_variables").Value : null, TechnicalInfo = element.Element("technicalinfo") != null?element.Element("technicalinfo").Value : null }); }
/// <summary> /// OrderedDictionary<TKey,TValue> (NO DUPLICATES) /// A dictionary based on balanced search tree /// Add / Find / Remove work in time O(log(N)) /// Provides fast .Range(from,to) operation /// </summary> private static void TestOrderedDictionary() { OrderedDictionary<int, Student> students = new OrderedDictionary<int, Student>(); var student1 = new Student("First", 21); var student2 = new Student("Second", 21); students.Add(5, student1); students.Add(2, student2); var student3 = new Student("Third", 22); var student4 = new Student("Forth", 23); var student5 = new Student("Fifth", 24); students.Add(3, student3); students.Add(4, student4); students.Add(1, student5); foreach (var item in students) { Console.WriteLine(item); } Console.WriteLine("========== Range Key >= 2 && <= 4 ============= "); var inRangeStudents = students.Range(2, true, 4, true); foreach (var item in inRangeStudents) { Console.WriteLine(item); } Console.WriteLine("==========ForEach(x => { x.Value.Age += 1; Console.WriteLine(x); })============= "); students.ForEach(x => { x.Value.Age += 1; Console.WriteLine(x); }); }
private void finishClick(object sender, RoutedEventArgs e) { if (izmena) { izmeniSoftver(); return; } if (validacijaNovogSoftvera() && !dodavanjeSoftveraIzborStarogUnosa) { // pamtimo stanje alikacije pre nego sto uradimo dodavanje novog staroStanje = new StanjeAplikacije(); staroStanje.RacunarskiCentar = DeepClone(racunarskiCentar); staroStanje.TipPodataka = "softver"; staroStanje.Kolicina = 1; staroStanje.TipPromene = "brisanje"; staroStanje.Oznake.Add(oznakaSoftver.Text.Trim()); noviSoftver.Oznaka = oznakaSoftver.Text.Trim(); noviSoftver.Naziv = nazivSoftver.Text.Trim(); noviSoftver.Opis = opisSoftver.Text.Trim(); noviSoftver.GodIzdavanja = int.Parse(godinaSoftver.Text.Trim()); noviSoftver.Cena = double.Parse(cenaSoftver.Text.Trim()); if ((bool)WindowsOSSoftver.IsChecked) { noviSoftver.OperativniSistem = "Windows"; } else if ((bool)LinuxOSSoftver.IsChecked) { noviSoftver.OperativniSistem = "Linux"; } else { noviSoftver.OperativniSistem = "Windows i Linux"; } noviSoftver.Proizvodjac = proizvodjacSoftver.Text.Trim(); noviSoftver.Sajt = sajtSoftver.Text.Trim(); tabelaSoftvera.Add(noviSoftver); racunarskiCentar.DodajSoftver(noviSoftver); Application.Current.Dispatcher.Invoke(() => { notifierMainWindow.ShowSuccess("Uspešno ste dodali novi softver!"); }); // na undo stek treba da upisemo staro stanje aplikacije // generisemo neki novi kljuc pod kojim cemo cuvati prethodno stanje na steku string kljuc = Guid.NewGuid().ToString(); // proveravamo da li vec ima 10 koraka za undo operaciju, ako ima, izbacujemo prvi koji je ubacen kako bismo // i dalje imali 10 mogucih koraka, ali ukljucujuci i ovaj novi if (prethodnaStanjaAplikacije.Count >= 3) { prethodnaStanjaAplikacije.RemoveAt(0); } prethodnaStanjaAplikacije.Add(kljuc, staroStanje); stekStanja.GetUndo().Push(kljuc); // postavljamo flag na true, da bismo mogli da omogucimo klik na dugme za undo operaciju potvrdio = true; this.Close(); } else if (dodavanjeSoftveraIzborStarogUnosa) { // ukoliko postoji softver (logicki neaktivan) sa istom oznakom // kao sto je uneta, ponovo aktiviramo taj softver (postaje logicki aktivan) tabelaSoftvera.Add(racunarskiCentar.Softveri[oznakaSoftver.Text.Trim()]); Application.Current.Dispatcher.Invoke(() => { notifierMainWindow.ShowSuccess("Uspešno ste aktivirali postojeći softver!"); }); // na undo stek treba da upisemo staro stanje aplikacije // generisemo neki novi kljuc pod kojim cemo cuvati prethodno stanje na steku string kljuc = Guid.NewGuid().ToString(); // proveravamo da li vec ima 10 koraka za undo operaciju, ako ima, izbacujemo prvi koji je ubacen kako bismo // i dalje imali 10 mogucih koraka, ali ukljucujuci i ovaj novi if (prethodnaStanjaAplikacije.Count >= 3) { prethodnaStanjaAplikacije.RemoveAt(0); } prethodnaStanjaAplikacije.Add(kljuc, staroStanje); stekStanja.GetUndo().Push(kljuc); // postavljamo flag na true, da bismo mogli da omogucimo klik na dugme za undo operaciju potvrdio = true; this.Close(); } }
public void VarsNeededForDecode(PEREffectiveConstraint cns, int arrayDepth, OrderedDictionary<string, CLocalVariable> existingVars) { if (!existingVars.ContainsKey("enumIndex")) { existingVars.Add("enumIndex", new CLocalVariable("enumIndex", "asn1SccSint", 0, "0")); } }
/// <summary> /// Renders only a subset of all available slots filtered by searching given text on the item name/description /// </summary> /// <param name="text"></param> /// <param name="searchCache">Can be set to increase search performance, otherwise a slow search is performed</param> public void FilterItemsBySearchText(string text, Dictionary <int, string> searchCache = null, Dictionary <int, string> searchCacheNames = null) { searchText = text.ToLowerInvariant(); renderedSlots.Clear(); OrderedDictionary <int, WeightedSlot> wSlots = new OrderedDictionary <int, WeightedSlot>(); foreach (var val in availableSlots) { ItemSlot slot = inventory[val.Key]; if (slot.Itemstack == null) { continue; } if (searchText == null || searchText.Length == 0) { renderedSlots.Add(val.Key, slot); continue; } string cachedtext = ""; var name = searchCacheNames[val.Key]; if (searchCache != null && searchCache.TryGetValue(val.Key, out cachedtext)) { int index = name.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase); // First prio: Exact match on name if (index == 0 && name.Length == searchText.Length) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 0 }); continue; } // 1.5th prio: Starts with word if (index == 0 && name.Length > searchText.Length && name[searchText.Length] == ' ') { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 0.125f }); continue; } // 2nd prio: ends with this word if (index > 0 && name[index - 1] == ' ' && index + searchText.Length == name.Length) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 0.25f }); continue; } // 3rd prio: exact mach of a word if (index > 0 && name[index - 1] == ' ') { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 0.5f }); continue; } // 4th prio: Starts with if (index == 0) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 0.75f }); continue; } // 5th prio: cotained in the word if (index > 0) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 1f }); continue; } // 6th prio: Starts with in the description if (cachedtext.StartsWith(searchText, StringComparison.InvariantCultureIgnoreCase)) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 2 }); continue; } // 7th prio: Contained anywhere in the description if (cachedtext.CaseInsensitiveContains(searchText)) { wSlots.Add(val.Key, new WeightedSlot() { slot = slot, weight = 3 }); continue; } } else { if (slot.Itemstack.MatchesSearchText(api.World, searchText)) { renderedSlots.Add(val.Key, slot); } } } foreach (var pair in wSlots.OrderBy(pair => pair.Value.weight)) { renderedSlots.Add(pair.Key, pair.Value.slot); } rows = (int)Math.Ceiling(1f * renderedSlots.Count / cols); ComposeInteractiveElements(); }
public void Add(int ignored) // adding separators to pretty print { data.Add((++separators).ToString(), null); }
/** * Execute an API call against the gateway. * * @param string method Method being called * @param OrderedDictionary parameters Associated list of parameters in API call order. * @param OrderedDictionary call_details Additional call details, including: * 'method' => 'GET' | 'POST' * 'headers' => Array of HTTP headers to send. * 'postdata' => If 'method' == POST then this is the data to send. * 'token' => User authenticating token as retrieved by a call to * Latakoo::authenticate('email','password'); * 'email' => Email address of the signing user used in 'token' * 'password' => Password of the signing user used in 'token' * * @param string endpoint The Endpoint to direct the query. */ public JObject execute(string method, OrderedDictionary parameters, OrderedDictionary call_details, string endpoint) { if (endpoint == null) { endpoint = this.endpoint; } if (method == null) { return(null); } if (call_details == null) { call_details = new OrderedDictionary(); } if (parameters == null) { parameters = new OrderedDictionary(); } if (!call_details.Contains("method")) { call_details.Add("method", "GET"); } if (!call_details.Contains("headers")) { call_details.Add("headers", new OrderedDictionary()); } // Construct query string List <string> queryparams = new List <string>(); queryparams.Add("method=" + HttpUtility.UrlEncode(method)); foreach (DictionaryEntry de in parameters) { if (de.Value is OrderedDictionary) { OrderedDictionary val = (OrderedDictionary)de.Value; foreach (DictionaryEntry de2 in val) { queryparams.Add(HttpUtility.UrlEncode(de.Key.ToString()) + "[" + HttpUtility.UrlEncode(de2.Key.ToString()) + "]=" + HttpUtility.UrlEncode(de2.Value.ToString())); } } else { queryparams.Add(HttpUtility.UrlEncode(de.Key.ToString()) + "=" + HttpUtility.UrlEncode(de.Value.ToString())); } } string[] queryparamsarray = queryparams.ToArray(); string query = string.Join("&", queryparamsarray); endpoint = "https://" + endpoint + "/-/api/?" + query; // Authenticate command if (call_details.Contains("email") && call_details.Contains("password") && call_details.Contains("token")) { string token = this.sign(query, (string)call_details["email"], (string)call_details["password"], (string)call_details["token"]); OrderedDictionary headers = (OrderedDictionary)call_details["headers"]; headers.Add("X_PFTP_API_TOKEN", token); call_details.Remove("headers"); call_details.Add("headers", headers); } // Make request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(endpoint); request.UserAgent = "Mono Bindings v1"; request.Method = (string)call_details["method"]; request.Credentials = CredentialCache.DefaultCredentials; OrderedDictionary httpheaders = (OrderedDictionary)call_details["headers"]; WebHeaderCollection webheaders = new WebHeaderCollection(); foreach (DictionaryEntry de in httpheaders) { webheaders.Add(de.Key + ": " + de.Value); } request.Headers = webheaders; ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); if (call_details.Contains("postdata")) { // Send post data byte[] postBytes = System.Text.Encoding.ASCII.GetBytes((string)call_details["postdata"]); request.ContentLength = postBytes.Length; System.IO.Stream str = request.GetRequestStream(); str.Write(postBytes, 0, postBytes.Length); str.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); string raw_json = new StreamReader(stream).ReadToEnd(); return(JObject.Parse(raw_json)); }
private void UnscheduleAppointment(int id, string title) { IDataSource dataSource = GridDataSource; DataSourceView view = dataSource.GetView("DefaultView"); IOrderedDictionary data = new OrderedDictionary(); data.Add("Start", null); data.Add("End", null); data.Add("Subject", title); IDictionary keys = new OrderedDictionary(); keys.Add("AppointmentID", id); view.Update(keys, data, new OrderedDictionary(), OnDataSourceOperationComplete); }
public void ProcessInput(string input) { /* * Creates new queue. * Adds each new word to a list to be searched for, removing duplicates. */ // Initialise queue to hold calls to dictionary, thesaurus and conjugator queue = new Queue(); if (words == null) { words = GetWordsFromInput(input); } // Queue words we haven't seen before foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { // Check whether the word is in the definitions table Definition def = RitchardDataHelper.GetDefinitionCaseSensitive(word); // Full def needed for 'else' if (def == null) { // If not, see if we have previously seen a misspelling of this word CorrectedSpelling cs = _db.CorrectedSpellings.SingleOrDefault(crs => crs.OriginalSpelling == word); Guid correctedDefGuid = Guid.Empty; if (cs != null) { correctedDefGuid = cs.ResultingDefinition; } // If not... if (correctedDefGuid == Guid.Empty) { // ...check whether search has already been requested for that word if (!odWords.Contains(word)) { // If not, queue it odWords.Add(word, Strings.WordLookupReady); queue.AddDictionaryEntry(word); } } } // If it IS in the definitions table, see if we have part of speech and verb info. else { if (!_db.PartsOfSpeeches.Any(pos => pos.DefinitionID == def.DefinitionID)) { // If not, queue it odWords.Add(word, Strings.WordLookupReady); queue.AddDictionaryEntry(word); } } } } ProcessQueue(); CorrectSpellings(); GetPartsOfSpeech(); //ParseSentences(); }
/// <summary> /// @see IJobOperator#GetStepExecutionSummaries . /// </summary> /// <param name="executionId"></param> /// <returns></returns> /// <exception cref="NoSuchJobExecutionException"> </exception> public IDictionary<long?, string> GetStepExecutionSummaries(long executionId) { JobExecution jobExecution = FindExecutionById(executionId); ICollection<StepExecution> stepExecutions = jobExecution.StepExecutions; IDictionary<long?, string> map = new OrderedDictionary<long?, string>(stepExecutions.Count); foreach (StepExecution stepExecution in stepExecutions) { map.Add(stepExecution.Id, stepExecution.ToString()); } return map; }
/// <summary> /// Gets the paramters from the template XML metadata and returns them in the correct order as they are used in the event message. /// </summary> /// <param name="template">The template XML string.</param> /// <returns>The ordered parameter list.</returns> private static OrderedDictionary GetEventParametersFromXmlTemplate(string template) { /** * Example * * Message: * "The time provider '%1' logged the following error: %2" * * Template: * <template xmlns="http://schemas.microsoft.com/win/2004/08/events"> * <data name="TimeProvider" inType="win:UnicodeString" outType="xs:string"/> * <data name="ErrorMessage" inType="win:UnicodeString" outType="xs:string"/> * </template> * * The order of the data elements in the XML match up EXACTLY with %1, %2, %3 in the message. * Because of that reason, we can't use any LINQ and dictionary conversion: * * parameters = parameterXml.Root.Elements("{http://schemas.microsoft.com/win/2004/08/events}data").Select( * p => new * { * Name = p.Attributes("name").Single().Value, * DataType = p.Attributes("inType").Single().Value * }).ToDictionary(p => p.Name, p => p.DataType); * * * Dictionary<string,string> is NOT ordered so the above code resulted in parameters not matching up to their substitution number **/ OrderedDictionary parameters = new OrderedDictionary(); if (!string.IsNullOrEmpty(template)) { int nameCount = 0; XDocument parameterXml = XDocument.Parse(template, LoadOptions.None); if (parameterXml.Root != null) { // must specify the namespace when selecting elements otherwise no elements will be returned foreach (XElement element in parameterXml.Root.Elements(string.Format(CultureInfo.CurrentCulture, "{{{0}}}{1}", EventSchema, DataElement))) { string name = element.Attributes(NameAttribute).Single().Value; string type = element.Attributes(TypeAttribute).Single().Value; // some developers re-used the same parameter name in the same message so we need to give it a unique name to avoid duplicates in the dictionary // key = original parameter name + "-" + count // value = original paramter name,data type if (parameters.Contains(name)) { nameCount++; parameters.Add(name + "-" + nameCount, name + "," + type); } else { parameters.Add(name, name + "," + type); } } } } return(parameters); }
// // Render row values based on field settings // public void RenderRow() { // Initialize urls // Row Rendering event Personas.Row_Rendering(); // // Common render codes for all row types // // IdPersona // IdArea // IdCargo // Documento // Persona // Activa // // View Row // if (Personas.RowType == EW_ROWTYPE_VIEW) { // View row // IdPersona Personas.IdPersona.ViewValue = Personas.IdPersona.CurrentValue; Personas.IdPersona.ViewCustomAttributes = ""; // IdArea if (ew_NotEmpty(Personas.IdArea.CurrentValue)) { sFilterWrk = "[IdArea] = " + ew_AdjustSql(Personas.IdArea.CurrentValue) + ""; sSqlWrk = "SELECT [Area], [Codigo] FROM [dbo].[Areas]"; sWhereWrk = ""; if (sFilterWrk != "") { if (sWhereWrk != "") sWhereWrk += " AND "; sWhereWrk += "(" + sFilterWrk + ")"; } if (sWhereWrk != "") sSqlWrk += " WHERE " + sWhereWrk; sSqlWrk += " ORDER BY [Area]"; drWrk = Conn.GetTempDataReader(sSqlWrk); if (drWrk.Read()) { Personas.IdArea.ViewValue = drWrk["Area"]; Personas.IdArea.ViewValue = String.Concat(Personas.IdArea.ViewValue, ew_ValueSeparator(0, 1, Personas.IdArea), drWrk["Codigo"]); } else { Personas.IdArea.ViewValue = Personas.IdArea.CurrentValue; } Conn.CloseTempDataReader(); } else { Personas.IdArea.ViewValue = System.DBNull.Value; } Personas.IdArea.ViewCustomAttributes = ""; // IdCargo if (ew_NotEmpty(Personas.IdCargo.CurrentValue)) { sFilterWrk = "[IdCargo] = " + ew_AdjustSql(Personas.IdCargo.CurrentValue) + ""; sSqlWrk = "SELECT [Cargo] FROM [dbo].[Cargos]"; sWhereWrk = ""; if (sFilterWrk != "") { if (sWhereWrk != "") sWhereWrk += " AND "; sWhereWrk += "(" + sFilterWrk + ")"; } if (sWhereWrk != "") sSqlWrk += " WHERE " + sWhereWrk; sSqlWrk += " ORDER BY [Cargo]"; drWrk = Conn.GetTempDataReader(sSqlWrk); if (drWrk.Read()) { Personas.IdCargo.ViewValue = drWrk["Cargo"]; } else { Personas.IdCargo.ViewValue = Personas.IdCargo.CurrentValue; } Conn.CloseTempDataReader(); } else { Personas.IdCargo.ViewValue = System.DBNull.Value; } Personas.IdCargo.ViewCustomAttributes = ""; // Documento Personas.Documento.ViewValue = Personas.Documento.CurrentValue; Personas.Documento.ViewCustomAttributes = ""; // Persona Personas.Persona.ViewValue = Personas.Persona.CurrentValue; Personas.Persona.ViewCustomAttributes = ""; // Activa if (Convert.ToString(Personas.Activa.CurrentValue) == "1") { Personas.Activa.ViewValue = (Personas.Activa.FldTagCaption(1) != "") ? Personas.Activa.FldTagCaption(1) : "Y"; } else { Personas.Activa.ViewValue = (Personas.Activa.FldTagCaption(2) != "") ? Personas.Activa.FldTagCaption(2) : "N"; } Personas.Activa.ViewCustomAttributes = ""; // View refer script // IdArea Personas.IdArea.LinkCustomAttributes = ""; Personas.IdArea.HrefValue = ""; Personas.IdArea.TooltipValue = ""; // IdCargo Personas.IdCargo.LinkCustomAttributes = ""; Personas.IdCargo.HrefValue = ""; Personas.IdCargo.TooltipValue = ""; // Documento Personas.Documento.LinkCustomAttributes = ""; Personas.Documento.HrefValue = ""; Personas.Documento.TooltipValue = ""; // Persona Personas.Persona.LinkCustomAttributes = ""; Personas.Persona.HrefValue = ""; Personas.Persona.TooltipValue = ""; // Activa Personas.Activa.LinkCustomAttributes = ""; Personas.Activa.HrefValue = ""; Personas.Activa.TooltipValue = ""; // // Add Row // } else if (Personas.RowType == EW_ROWTYPE_ADD) { // Add row // IdArea Personas.IdArea.EditCustomAttributes = ""; if (ew_NotEmpty(Personas.IdArea.SessionValue)) { Personas.IdArea.CurrentValue = Personas.IdArea.SessionValue; if (ew_NotEmpty(Personas.IdArea.CurrentValue)) { sFilterWrk = "[IdArea] = " + ew_AdjustSql(Personas.IdArea.CurrentValue) + ""; sSqlWrk = "SELECT [Area], [Codigo] FROM [dbo].[Areas]"; sWhereWrk = ""; if (sFilterWrk != "") { if (sWhereWrk != "") sWhereWrk += " AND "; sWhereWrk += "(" + sFilterWrk + ")"; } if (sWhereWrk != "") sSqlWrk += " WHERE " + sWhereWrk; sSqlWrk += " ORDER BY [Area]"; drWrk = Conn.GetTempDataReader(sSqlWrk); if (drWrk.Read()) { Personas.IdArea.ViewValue = drWrk["Area"]; Personas.IdArea.ViewValue = String.Concat(Personas.IdArea.ViewValue, ew_ValueSeparator(0, 1, Personas.IdArea), drWrk["Codigo"]); } else { Personas.IdArea.ViewValue = Personas.IdArea.CurrentValue; } Conn.CloseTempDataReader(); } else { Personas.IdArea.ViewValue = System.DBNull.Value; } Personas.IdArea.ViewCustomAttributes = ""; } else { sFilterWrk = ""; sSqlWrk = "SELECT [IdArea], [Area] AS [DispFld], [Codigo] AS [Disp2Fld], '' AS [Disp3Fld], '' AS [Disp4Fld], '' AS [SelectFilterFld] FROM [dbo].[Areas]"; sWhereWrk = ""; if (sFilterWrk != "") { if (sWhereWrk != "") sWhereWrk += " AND "; sWhereWrk += "(" + sFilterWrk + ")"; } if (sWhereWrk != "") sSqlWrk += " WHERE " + sWhereWrk; sSqlWrk += " ORDER BY [Area]"; alwrk = Conn.GetRows(sSqlWrk); alwrk.Insert(0, new OrderedDictionary()); ((OrderedDictionary)alwrk[0]).Add("0", ""); ((OrderedDictionary)alwrk[0]).Add("1", Language.Phrase("PleaseSelect")); ((OrderedDictionary)alwrk[0]).Add("2", ""); Personas.IdArea.EditValue = alwrk; } // IdCargo Personas.IdCargo.EditCustomAttributes = ""; sFilterWrk = ""; sSqlWrk = "SELECT [IdCargo], [Cargo] AS [DispFld], '' AS [Disp2Fld], '' AS [Disp3Fld], '' AS [Disp4Fld], '' AS [SelectFilterFld] FROM [dbo].[Cargos]"; sWhereWrk = ""; if (sFilterWrk != "") { if (sWhereWrk != "") sWhereWrk += " AND "; sWhereWrk += "(" + sFilterWrk + ")"; } if (sWhereWrk != "") sSqlWrk += " WHERE " + sWhereWrk; sSqlWrk += " ORDER BY [Cargo]"; alwrk = Conn.GetRows(sSqlWrk); alwrk.Insert(0, new OrderedDictionary()); ((OrderedDictionary)alwrk[0]).Add("0", ""); ((OrderedDictionary)alwrk[0]).Add("1", Language.Phrase("PleaseSelect")); Personas.IdCargo.EditValue = alwrk; // Documento Personas.Documento.EditCustomAttributes = ""; Personas.Documento.EditValue = ew_HtmlEncode(Personas.Documento.CurrentValue); // Persona Personas.Persona.EditCustomAttributes = ""; Personas.Persona.EditValue = ew_HtmlEncode(Personas.Persona.CurrentValue); // Activa Personas.Activa.EditCustomAttributes = ""; alwrk = new ArrayList(); odwrk = new OrderedDictionary(); odwrk.Add("0", "1"); odwrk.Add("1", (ew_NotEmpty(Personas.Activa.FldTagCaption(1))) ? Personas.Activa.FldTagCaption(1) : "Si"); alwrk.Add(odwrk); odwrk = new OrderedDictionary(); odwrk.Add("0", "0"); odwrk.Add("1", (ew_NotEmpty(Personas.Activa.FldTagCaption(2))) ? Personas.Activa.FldTagCaption(2) : "No"); alwrk.Add(odwrk); Personas.Activa.EditValue = alwrk; // Edit refer script // IdArea Personas.IdArea.HrefValue = ""; // IdCargo Personas.IdCargo.HrefValue = ""; // Documento Personas.Documento.HrefValue = ""; // Persona Personas.Persona.HrefValue = ""; // Activa Personas.Activa.HrefValue = ""; } if (Personas.RowType == EW_ROWTYPE_ADD || Personas.RowType == EW_ROWTYPE_EDIT || Personas.RowType == EW_ROWTYPE_SEARCH) { // Add / Edit / Search row Personas.SetupFieldTitles(); } // Row Rendered event if (Personas.RowType != EW_ROWTYPE_AGGREGATEINIT) Personas.Row_Rendered(); }
internal void AddArgument(string i_ArgumentKeyString, ArgumentWrapper i_Argument) { r_argumentOrderedDictionaryDictionary.Add(i_ArgumentKeyString, i_Argument); }