Exemplo n.º 1
0
        public static void HandleDups(MethodDefinition coroutine, OrderedDictionary<Instruction, List<Instruction>> coroutineInstructions, Instruction instruction, List<Instruction> current, TypeReference expectedType, ref VariableDefinition dupLoc)
        {
            // FIXME: This is kindof a kludge... think on it
            if (instruction.Previous.OpCode != OpCodes.Dup)
                return;

            var action = current.ToArray ();
            current.Clear ();

            if (dupLoc == null) {
                dupLoc = new VariableDefinition (coroutine.Module.Import (typeof (object)));
                coroutine.Body.Variables.Add (dupLoc);
            }

            if (expectedType.IsValueType)
                current.Add (Instruction.Create (OpCodes.Box, expectedType));

            current.Add (Instruction.Create (OpCodes.Stloc, dupLoc));

            current.AddRange  (action);

            current.Add (Instruction.Create (OpCodes.Ldloc, dupLoc));
            if (expectedType.IsValueType) {
                current.Add (Instruction.Create (OpCodes.Unbox, expectedType));
                current.Add (Instruction.Create (OpCodes.Ldobj, expectedType));
            }
        }
Exemplo n.º 2
0
        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;
        }
Exemplo n.º 3
0
        public HalResource(string rel, string href)
        {
            Contents = new OrderedDictionary<string, HalNode>();

            Rel = rel;
            Href = href;
        }
Exemplo n.º 4
0
        public static void Print(StreamWriterLevel c, OrderedDictionary<string, CLocalVariable> vars)
        {
            foreach (CLocalVariable v in vars.Values)
            {
                c.P(1);
                if (v.staticDeclaration)
                    c.Write("static ");

                c.Write("{0} {1}", v.type, v.varName);

                if (v.arrayLen > 0)
                    c.Write("[{0}]",v.arrayLen);

                if (v.initVal != "")
                    c.Write(" = {0}", v.initVal);
                c.WriteLine(";");

                //if (v.arrayLen == 0)
                //{
                //    c.WriteLine("{0} {1} = {2};", v.type, v.varName, v.initVal);
                //}
                //else
                //{
                //    c.WriteLine("{0} {1}[{2}];", v.type, v.varName, v.arrayLen);
                //}

            }
            if (vars.Count > 0)
                c.WriteLine();
        }
Exemplo n.º 5
0
 public ShoppingCenter2()
 {
     this.productsByName = new Dictionary<string, OrderedBag<Product>>();
     this.productsByProducer = new Dictionary<string, OrderedBag<Product>>();
     this.productsByPrice = new OrderedDictionary<decimal, OrderedBag<Product>>();
     this.productsByNameAndProducer = new Dictionary<string, OrderedBag<Product>>();
 }
 public void Before() {
     _random = new Random();
     _dict = new OrderedDictionary();
     for (int i = 0; i < n; i++) {
         _dict.Add(i, new Entity(CP.NumComponents, null));
     }
 }
Exemplo n.º 7
0
        private static OrderedDictionary<string, SortedSet<Student>> SaveInput()
        {
            OrderedDictionary<string, SortedSet<Student>> input = new OrderedDictionary<string, SortedSet<Student>>();
            // just link the txt file from the project ->
            string path = @"C:\users\student\documents\visual studio 2012\Projects\[DSA] Data-Structures-Efficiency\1. PrintingOrderedStudents\students.txt";
            StreamReader reader = new StreamReader(path);

            using (reader)
            {
                string line = reader.ReadLine();
                while (line != null && line != string.Empty)
                {
                    string[] attribs = ParseLine(line);
                    Student newStud =  new Student(attribs[0], attribs[1]);
                    if (input.ContainsKey(attribs[2]))
                    {
                        input[attribs[2]].Add(newStud);
                    }
                    else
                    {
                        input[attribs[2]] = new SortedSet<Student>();
                        input[attribs[2]].Add(newStud);
                    }

                    line = reader.ReadLine();
                }
            }

            return input;
        }
Exemplo n.º 8
0
        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);
            }
        }
Exemplo n.º 9
0
 public static void SaveHeader(string szFileName, OrderedDictionary<string, int> apps, OrderedDictionary<string, int> ctrls)
 {
     StreamWriter stream = new StreamWriter(szFileName);
     stream.WriteLine("#ifndef __RESOURCE_H");
     stream.WriteLine("#define __RESORUCE_H");
     stream.WriteLine("// Resource Script generated by Rose Interface Designer");
     stream.WriteLine("// Developed by Pain and xLethal");
     stream.WriteLine("// Copyright XorNet");
     stream.WriteLine();
     stream.WriteLine();
     stream.WriteLine("// Applet Id");
     foreach (KeyValuePair<string, int> xPair in apps)
     {
         stream.WriteLine("#define {0}{1}", xPair.Key.PadRight(64, ' '), xPair.Value);
     }
     stream.WriteLine();
     stream.WriteLine("// Control Id");
     foreach (KeyValuePair<string, int> xPair in ctrls)
     {
         stream.WriteLine("#define {0}{1}", xPair.Key.PadRight(64, ' '), xPair.Value);
     }
     stream.WriteLine();
     stream.Write("#endif");
     stream.Close();
 }
        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;
        }
Exemplo n.º 11
0
 public BunnyWarsStructure()
 {
     this.rooms = new OrderedSet<int>();
     this.roomsById = new OrderedDictionary<int, Dictionary<int, List<Bunny>>>();
     this.bunniesByTeam = new Dictionary<int, SortedSet<Bunny>>();
     this.bunniesByName = new OrderedDictionary<string, Bunny>(new SuffixBunnyComparator());
 }
        private NpcSpawner LoadNpcSpawner(TmxObjectGroup.TmxObject tmxObject, OrderedDictionary<string, IGameObject> gameObjects, ContentManager content)
        {
            OrderedDictionary<string, Npc> _npcs = new OrderedDictionary<string, Npc>();

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(tmxObject.Properties["SpawnerFile"]);

            XmlNodeList nodes = xmlDoc.SelectNodes("NPCS/NPC");

            var spawningEntities = new List<IEntity>();

            for (int i = 0; i < nodes.Count; i++)
            {
                // Load the npcs for the spawner.
                string uniqueID = nodes[i].Attributes["UniqueID"].Value;
                string npcDataFilePath = nodes[i].Attributes["filepath"].Value;

                spawningEntities.Add(Npc.Load(npcDataFilePath, uniqueID, content));
            }

            var spawnerPosition = new Vector2(tmxObject.X, tmxObject.Y);
            var updateInterval = uint.Parse(tmxObject.Properties["UpdateInterval"]);

            return new NpcSpawner(spawnerPosition, updateInterval, gameObjects, spawningEntities);
        }
Exemplo n.º 13
0
        public void OrderedDictionary()
        {
            OrderedDictionary<string, int> dict = new OrderedDictionary<string, int>();
            DoTests(dict);
            Assert.AreEqual(3, dict. Count, "Has 3 records left");
            Assert.AreEqual(2, dict.IndexOf("test4"), "IndexOf works");
            Assert.AreEqual(dict[1], 30, "Access by numeric index appears to work");
            Assert.AreEqual(dict.Values[1], 30, "Access to values by index is good");
            Assert.AreEqual(dict.Keys[1], "test3", "Access to values by index is good");

            Assert.Throws<NotSupportedException>(Del(()=>{dict.Values[1]=333;}),"Can't set value when accessing it from the Values list");

            dict.Insert(0, 100);

            // indicies should have moved
            Assert.AreEqual(4, dict.Count, "Has 3 records left");
            Assert.AreEqual(3, dict.IndexOf("test4"), "IndexOf works");
            Assert.AreEqual(dict[2], 30, "Access by numeric index appears to work");
            Assert.AreEqual(dict[0], 100);
            // check for autocreated key
            Assert.AreEqual(dict.Keys[0],"0", "Autogenerated a key.");
            dict.Insert(0, 100);
            Assert.AreEqual(dict.Keys[0], "1", "Autogenerated another key.");

        }
Exemplo n.º 14
0
        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, "\\-");
        }
Exemplo n.º 15
0
 public ProductsCollection()
 {
     this.productsById = new Dictionary<int, Product>();
     this.productsByPrice = new OrderedDictionary<decimal, SortedSet<Product>>();
     this.productsByTitle = new Dictionary<string, SortedSet<Product>>();
     this.productsByTitleAndPrice = new Dictionary<string, OrderedDictionary<decimal, SortedSet<Product>>>();
     this.productsBySuplierAndPrice = new Dictionary<string, OrderedDictionary<decimal, SortedSet<Product>>>();
 }
Exemplo n.º 16
0
 public PersonCollection()
 {
     mailDict = new Dictionary<string, Person>();
     mailDomainDict = new Dictionary<string,SortedSet<Person>>();
     nameTownDict = new Dictionary<string,SortedSet<Person>>();
     ageRangeDict = new OrderedDictionary<int,SortedSet<Person>>();
     townAgeRangeDict = new Dictionary<string, OrderedDictionary<int, SortedSet<Person>>>();
 }
Exemplo n.º 17
0
 public ClepsClassBuilder(string name)
 {
     FullyQualifiedName = name;
     MemberVariables = new OrderedDictionary<string, ClepsType>();
     MemberMethods = new Dictionary<string, ClepsType>();
     StaticMemberVariables = new Dictionary<string, ClepsType>();
     StaticMemberMethods = new Dictionary<string, ClepsType>();
 }
Exemplo n.º 18
0
 public PersonCollection()
 {
     this.peopleByEmail = new Dictionary<string, Person>();
     this.peopleByDomain = new Dictionary<string, SortedDictionary<string, Person>>();
     this.peopleByNameAndTown = new Dictionary<string, SortedDictionary<string, Person>>();
     this.peopleByAge = new OrderedDictionary<int, SortedDictionary<string, Person>>();
     this.peopleByTownThenByAge = new Dictionary<string, OrderedDictionary<int, SortedDictionary<string, Person>>>();
 }
Exemplo n.º 19
0
 public PersonCollection()
 {
     this.personsByEmail = new Dictionary<string, Person>();
     this.personsByDomain = new Dictionary<string, SortedSet<Person>>();
     this.personsByNameAndTown = new Dictionary<Tuple<string, string>, SortedSet<Person>>();
     this.personsByAge = new OrderedDictionary<int, SortedSet<Person>>();
     this.personsByTownAndAge = new Dictionary<string, OrderedDictionary<int, SortedSet<Person>>>();
 }
Exemplo n.º 20
0
 private static void Output(OrderedDictionary<string, SortedSet<Person>> coursesAndStudents)
 {
     foreach (var course in coursesAndStudents)
     {
         Console.Write(course.Key + ": ");
         Console.WriteLine(string.Join(", ", course.Value));
     }
 }
Exemplo n.º 21
0
 public PersonCollection()
 {
     this.personDatabase = new Dictionary<string, Person>();
     this.databaseOrderedByDomain = new Dictionary<string, SortedSet<Person>>();
     this.databaseOrderedByNameAndTown = new Dictionary<string, SortedSet<Person>>();
     this.databaseOrderedByAgeAndEmail = new OrderedDictionary<int, SortedSet<Person>>();
     this.databaseOrderedByAgeTownAndEmail = new Dictionary<string, OrderedDictionary<int, SortedSet<Person>>>();
 }
        public void AppendItem()
        {
            OrderedDictionary<string, string> dictionary = new OrderedDictionary<string, string>();

            dictionary.Add("1", "one");
            dictionary.Add("2", "two");
            Assert.AreEqual(2, dictionary.Count);
        }
Exemplo n.º 23
0
 // id - product
 // prod by price range
 // prod by title
 // prod by title + price
 // prod by title + price range
 // prod by supplier + price
 // prod by supplier + price range
 // remove by id - true/false
 // products are always sorted by id
 public Database()
 {
     productsById = new Dictionary<string, Product>();
     productsByTitle = new Dictionary<string, OrderedBag<Product>>();
     productsByPriceRange = new OrderedDictionary<double, OrderedBag<Product>>();
     productsByTitleAndPriceRange = new OrderedDictionary<string, OrderedDictionary<double, OrderedBag<Product>>>();
     productsBySupplierAndPriceRange = new OrderedDictionary<string, OrderedDictionary<double, OrderedBag<Product>>>();
 }
 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;
     }
 }
Exemplo n.º 25
0
        public BunnyWarsStructure()
        {
            this.bunniesInTeamsByRoom = new OrderedDictionary<int, Dictionary<int, HashSet<Bunny>>>();
            this.roomsById = new OrderedSet<int>();
            this.bunniesByName = new Dictionary<string, Bunny>();
            this.teamsBunnies = new Dictionary<int, OrderedSet<Bunny>>();

            this.bunniesOrderedReversedNames = new OrderedDictionary<string, Bunny>(StringComparer.Ordinal);
        }
Exemplo n.º 26
0
		public HalResource(string rel, string href)
		{
    		Contents = new OrderedDictionary<string, HalNode>();
            _Resources = new ResourcesFinder(this);
            _Properties = new PropertyFinder(this);

			Rel = rel;
			Href = href;
		}
Exemplo n.º 27
0
    public bool AddPerson(string email, string name, int age, string town)
    {
        if (this.FindPerson(email) != null)
        {
            // Person already exists
            return false;
        }

        var person = new Person()
        {
            Email = email,
            Name = name,
            Age = age,
            Town = town
        };

        // Add by email
        this.personsByEmail.Add(email, person);

        // Add by email domain
        var emailDomain = this.ExtractEmailDomain(email);
        if (! this.personsByEmailDomain.ContainsKey(emailDomain))
        {
            this.personsByEmailDomain.Add(emailDomain, new SortedSet<Person>());
        }
        this.personsByEmailDomain[emailDomain].Add(person);

        // Add by {name + town}
        var nameAndTown = this.CombineNameAndTown(name, town);
        if (!this.personsByNameAndTown.ContainsKey(nameAndTown))
        {
            this.personsByNameAndTown.Add(nameAndTown, new SortedSet<Person>());
        }
        this.personsByNameAndTown[nameAndTown].Add(person);

        // Add by age
        if (!this.personsByAge.ContainsKey(age))
        {
            this.personsByAge.Add(age, new SortedSet<Person>());
        }
        this.personsByAge[age].Add(person);

        // Add by {age + town}
        OrderedDictionary<int, SortedSet<Person>> personsByTown;
        if (! this.personsByAgeAndTown.TryGetValue(town, out personsByTown))
        {
            personsByTown = new OrderedDictionary<int, SortedSet<Person>>();
            personsByAgeAndTown.Add(town, personsByTown);
        }
        if (!personsByTown.ContainsKey(age))
        {
            personsByTown.Add(age, new SortedSet<Person>());
        }
        personsByTown[age].Add(person);

        return true;
    }
Exemplo n.º 28
0
 public CategorizedDeclarations(IEnumerable<string> aDeclarationsToIgnore)
 {
     FunctionTable = new OrderedDictionary<string, FunctionCType>();
     StructTable = new OrderedDictionary<string, StructCType>();
     EnumTable = new OrderedDictionary<string, EnumCType>();
     FunctionTypedefTable = new OrderedDictionary<string, FunctionCType>();
     HandleTable = new HashSet<string>();
     DeclarationsToIgnore = new HashSet<string>(aDeclarationsToIgnore);
 }
Exemplo n.º 29
0
        internal static object Create(Type tInterface, OrderedDictionary<Type, List<MethodInfo, MethodInfo>> instanceMethods, List<Delegate, MethodInfo> delegateMethods, List<MethodInfo> stubMethods, List<Type, object> usedInstances) {
            // now we can calculate the key based on the content of the *Methods collections
            var key = tInterface.GetTypeInfo().Assembly.FullName + "::" + tInterface.Name + ":::" + instanceMethods.Keys.Select(each => each.GetTypeInfo().Assembly.FullName + "." + each.FullName + "." + instanceMethods[each].Select(mi => mi.Value.ToSignatureString()).JoinWithComma()).JoinWith(";\r\n") +
                      "::" + delegateMethods.Select(each => each.GetType().FullName).JoinWith(";\r\n") +
                      "::" + stubMethods.Select(mi => mi.ToSignatureString()).JoinWithComma();
            // + "!->" + (onUnhandledExceptionMethod == null ? (onUnhandledExceptionDelegate == null ? "GenerateOnUnhandledException" : onUnhandledExceptionDelegate.ToString()) : onUnhandledExceptionMethod.ToSignatureString());

            return _proxyClassDefinitions.GetOrAdd(key, () => new DynamicType(tInterface, instanceMethods, delegateMethods, stubMethods)).CreateInstance(usedInstances, delegateMethods);
        }
Exemplo n.º 30
0
 public static void SaveStrings(string szFileName, OrderedDictionary<string, string> strings)
 {
     StreamWriter stream = new StreamWriter(szFileName);
     foreach (KeyValuePair<string, string> xPair in strings)
     {
         stream.WriteLine("{0}\t{1}", xPair.Key, xPair.Value);
     }
     stream.Close();
 }
Exemplo n.º 31
0
 public WDetailsViewViewModel()
 {
     m_Categories = new OrderedDictionary();
 }
Exemplo n.º 32
0
        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
                    {
                        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> {
                            IsFormData(verb) ? "application/x-www-form-urlencoded" : "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
                    };

                    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);
        }
Exemplo n.º 33
0
        private void menuItem_ToolCount_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolder = new FolderBrowserDialog();

            if (openFolder.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            List <string> files = new List <string>();

            files.AddRange(Directory.GetFiles(openFolder.SelectedPath, "*.pcap", SearchOption.AllDirectories));
            files.AddRange(Directory.GetFiles(openFolder.SelectedPath, "*.pcapng", SearchOption.AllDirectories));

            OrderedDictionary opcodeOccurrences = new OrderedDictionary();

            foreach (PacketOpcode opcode in Enum.GetValues(typeof(PacketOpcode)))
            {
                opcodeOccurrences[opcode] = 0;
            }

            foreach (string file in files)
            {
                loadPcap(file, true);

                foreach (PacketRecord record in records)
                {
                    foreach (PacketOpcode opcode in record.opcodes)
                    {
                        if (opcodeOccurrences.Contains(opcode))
                        {
                            opcodeOccurrences[opcode] = (Int32)opcodeOccurrences[opcode] + 1;
                        }
                        else
                        {
                            opcodeOccurrences[opcode] = 1;
                        }
                    }
                }
            }

            long          totalCount       = 0;
            StringBuilder occurencesString = new StringBuilder();

            foreach (DictionaryEntry entry in opcodeOccurrences)
            {
                occurencesString.Append(entry.Key);
                occurencesString.Append(" = ");
                occurencesString.Append(entry.Value);
                occurencesString.Append("\r\n");

                totalCount += (Int32)entry.Value;
            }

            occurencesString.Append("\r\n\r\nTotal Count = ");
            occurencesString.Append(totalCount);
            occurencesString.Append("\r\n");

            TextPopup popup = new TextPopup();

            popup.setText(occurencesString.ToString());
            popup.setText(occurencesString.ToString() + "\r\n\r\n" + String.Join("\r\n", files));
            popup.ShowDialog();
        }
        /// <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 <List <SymbolReference> > FindReferencesOfSymbol(
            SymbolReference foundSymbol,
            ScriptFile[] referencedFiles,
            WorkspaceService workspace)
        {
            if (foundSymbol == null)
            {
                return(null);
            }

            (Dictionary <string, List <string> > cmdletToAliases, Dictionary <string, string> aliasToCmdlets) = await CommandHelpers.GetAliasesAsync(_executionService).ConfigureAwait(false);

            // We want to look for references first in referenced files, hence we use ordered dictionary
            // TODO: File system case-sensitivity is based on filesystem not OS, but OS is a much cheaper heuristic
            OrderedDictionary fileMap = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                ? new OrderedDictionary()
                : new OrderedDictionary(StringComparer.OrdinalIgnoreCase);

            foreach (ScriptFile scriptFile in referencedFiles)
            {
                fileMap[scriptFile.FilePath] = scriptFile;
            }

            foreach (string filePath in workspace.EnumeratePSFiles())
            {
                if (!fileMap.Contains(filePath))
                {
                    if (!workspace.TryGetFile(filePath, out ScriptFile scriptFile))
                    {
                        // If we can't access the file for some reason, just ignore it
                        continue;
                    }

                    fileMap[filePath] = scriptFile;
                }
            }

            List <SymbolReference> symbolReferences = new();

            foreach (object fileName in fileMap.Keys)
            {
                ScriptFile file = (ScriptFile)fileMap[fileName];

                IEnumerable <SymbolReference> references = AstOperations.FindReferencesOfSymbol(
                    file.ScriptAst,
                    foundSymbol,
                    cmdletToAliases,
                    aliasToCmdlets);

                foreach (SymbolReference reference in references)
                {
                    try
                    {
                        reference.SourceLine = file.GetLine(reference.ScriptRegion.StartLineNumber);
                    }
                    catch (ArgumentOutOfRangeException e)
                    {
                        reference.SourceLine = string.Empty;
                        _logger.LogException("Found reference is out of range in script file", e);
                    }
                    reference.FilePath = file.FilePath;
                    symbolReferences.Add(reference);
                }
            }

            return(symbolReferences);
        }
Exemplo n.º 35
0
 internal static void StorePortalAliasesRegexesInCache(OrderedDictionary regexList, FriendlyUrlSettings settings)
 {
     SetPortalCache(PortalAliasRegexesKey, regexList, settings);
 }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            var c_n       = Console.ReadLine();
            var c_n_array = c_n.Split(' ').Select(int.Parse).ToArray();
            var c         = c_n_array[0];
            var n         = c_n_array[1];
            var c_string  = Console.ReadLine();
            //var c_string = "3 5 11 0 0 0 12 12 0 0 0 12 12 70 71 0 90 123 140 150 166 190 0";
            var n_string = Console.ReadLine();

            //var n_string = "5 13 90 1 70 75 7 188 12";
            int[] array   = c_string.Split(' ').Select(int.Parse).ToArray();
            int[] needles = n_string.Split(' ').Select(int.Parse).ToArray();
            OrderedDictionary <int, int> foundPlaces = new OrderedDictionary <int, int>();
            List <int> result = new List <int>();

            for (int i = 0; i < n; i++)
            {
                var needle             = needles[i];
                var lastNotZeroElement = -1;
                if (foundPlaces.ContainsKey(needle))
                {
                    result.Add(foundPlaces[needle]);
                    continue;
                }

                var startRange = foundPlaces.RangeTo(needle, false);
                var start      = 0;
                if (startRange.Any())
                {
                    start = startRange.Last().Value - 1;
                    lastNotZeroElement = start;
                }

                for (int j = start; j < c; j++)
                {
                    var element = array[j];

                    if (element >= needle)
                    {
                        if (lastNotZeroElement == -1)
                        {
                            result.Add(0);
                            foundPlaces[needle] = 0;
                        }
                        else
                        {
                            result.Add(lastNotZeroElement + 1);
                            foundPlaces[needle] = lastNotZeroElement + 1;
                        }

                        break;
                    }

                    if (element != 0)
                    {
                        lastNotZeroElement = j;
                    }

                    if (j == array.Count() - 1)
                    {
                        result.Add(lastNotZeroElement + 1);
                        foundPlaces[needle] = lastNotZeroElement + 1;
                    }
                }
            }

            Console.WriteLine(string.Join(" ", result));
        }
        //public OrderedDictionary<int, List<StatusInfo>> StatusInfosPerTeam = new Dictionary<int, List<StatusInfo>>();

        public void Fill(List <TournamentAssignment> taList)
        {
            // Get the teams
            Teams       = new List <Team>();
            Assignments = new List <Assignment>();

            OrderedDictionary tempStatusInfosPerTeam = new OrderedDictionary();
            //Dictionary<int, List<StatusInfo>> tempStatusInfosPerTeam = new Dictionary<int, List<StatusInfo>>();

            OrderedDictionary submitsPerTournamentAssignment = new OrderedDictionary();

            //Dictionary<TournamentAssignment, List<Submit>> submitsPerTournamentAssignment = new Dictionary<TournamentAssignment, List<Submit>>();

            foreach (TournamentAssignment ta in taList)
            {
                submitsPerTournamentAssignment.Add(ta.Id.ToString(), new List <Submit>());

                Assignments.Add(ta.Assignment);

                foreach (AssignmentEnrollment ae in ta.AssignmentEnrollmentList)
                {
                    // Add the team for this enrollment to the list
                    if (!Teams.Exists(t => t.Id == ae.Team.Id))
                    {
                        Teams.Add(ae.Team);
                        tempStatusInfosPerTeam.Add(ae.Team.Id.ToString(), new List <StatusInfo>());
                    }
                }
            }

            foreach (Team team in Teams)
            {
                foreach (TournamentAssignment ta in taList)
                {
                    // check if the team has an enrollment for this tournamentassignment
                    AssignmentEnrollment ae = ta.AssignmentEnrollmentList.Find(tae => tae.Team.Id == team.Id);
                    if (ae != null)
                    {
                        //If there's a submit, add it to the dictionary
                        if (ae.SubmitList.Count > 0)
                        {
                            ((List <Submit>)submitsPerTournamentAssignment[ta.Id.ToString()]).Add(ae.SubmitList[0]);
                        }
                        else
                        {
                            //add an empty submit placeholder for this enrollment
                            ((List <Submit>)submitsPerTournamentAssignment[ta.Id.ToString()]).Add(new Submit()
                            {
                                Status = "NullSubmit",
                                Team   = ae.Team,
                                SecondsSinceEnrollment = 0
                            });
                        }
                    }
                    else
                    {
                        //add an empty submit placeholder for this enrollment
                        ((List <Submit>)submitsPerTournamentAssignment[ta.Id.ToString()]).Add(new Submit()
                        {
                            Status = "NullSubmit",
                            Team   = team,
                            SecondsSinceEnrollment = 0
                        });
                    }
                }
            }

            foreach (TournamentAssignment ta in taList)
            {
                // sort the submits descending
                ((List <Submit>)submitsPerTournamentAssignment[ta.Id.ToString()]).Sort(new DescendingSubmitComparer());
            }


            foreach (string taId in submitsPerTournamentAssignment.Keys)
            {
                int finishOrder = 1;
                foreach (Submit s in ((List <Submit>)submitsPerTournamentAssignment[taId]))
                {
                    StatusEnum convertedStatus;
                    convertedStatus = ConvertSubmitStatus(s.ConvertStatus(s.Status));

                    StatusInfo statusInfo = new StatusInfo();
                    statusInfo.SecondsSinceEnrollment = s.SecondsSinceEnrollment;
                    statusInfo.Status      = convertedStatus;
                    statusInfo.FinishOrder = 0;

                    // If status is finished (successfull submit) add the seconds since enrollment
                    // to the score of the team
                    if (convertedStatus == StatusEnum.Finished)
                    {
                        Teams.Find(t => t.Id == s.Team.Id).Score += s.SecondsSinceEnrollment;
                        statusInfo.FinishOrder = finishOrder;
                        finishOrder++;
                    }

                    ((List <StatusInfo>)tempStatusInfosPerTeam[s.Team.Id.ToString()]).Add(statusInfo);
                }
            }

            Dictionary <int, List <Team> > FinishedPerTeam = new Dictionary <int, List <Team> >();
            List <int> finishedCounts = new List <int>();

            foreach (string teamId in tempStatusInfosPerTeam.Keys)
            {
                // determine how many assignments the team has finished
                int nrOfFinished = ((List <StatusInfo>)tempStatusInfosPerTeam[teamId]).FindAll(st => st.Status == StatusEnum.Finished).Count;

                if (!finishedCounts.Exists(f => f == nrOfFinished))
                {
                    finishedCounts.Add(nrOfFinished);
                    FinishedPerTeam.Add(nrOfFinished, new List <Team>());
                }
                if (nrOfFinished > 1)
                {
                    long totalScore = Teams.Find(t => t.Id == int.Parse(teamId)).Score;
                    // calculate mean score
                    long meanScore = (long)Math.Round((double)totalScore / (double)nrOfFinished);
                    Teams.Find(t => t.Id == int.Parse(teamId)).Score = meanScore;
                }
                FinishedPerTeam[nrOfFinished].Add(Teams.Find(t => t.Id == int.Parse(teamId)));
            }

            finishedCounts.Sort();
            finishedCounts.Reverse();

            List <Team> sortedTeamList = new List <Team>();

            foreach (int finishedCount in finishedCounts)
            {
                List <Team> teams = FinishedPerTeam[finishedCount];
                teams.Sort(new ScoreComparer());
                teams.Reverse();
                sortedTeamList.AddRange(teams);
            }


            //// Sort the teams by score (total seconds taken), zero scores are last.
            //Teams.Sort(new ScoreComparer());
            ////Teams.Sort((t1, t2) => t1.Score.CompareTo(t2.Score));
            ////Teams.Reverse();

            Teams = sortedTeamList;

            //build definite statusInfosPerTeam dictionary, sorting by team
            foreach (Team t in Teams)
            {
                StatusInfosPerTeam.Add(t.Id.ToString(), tempStatusInfosPerTeam[t.Id.ToString()]);
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// A wrapper method for Google Translate that translates multiple texts from source language to target language
        /// </summary>
        /// <param name="sourceLanguage">Source language of the texts for translation</param>
        /// <param name="targetLanguage">Target language for translation</param>
        /// <param name="textDict">A dictionary containing texts for translation</param>
        /// <returns>Returns a dictionary of the translated texts
        /// The dictionary keys are the keys from textDict, to help in tracking each translation to its original text</returns>
        public IOrderedDictionary <string, string> TranslateTexts(string sourceLanguage, string targetLanguage, IOrderedDictionary <string, string> textDict)
        {
            TranslateTextResponseList response;

            foreach (var textDictItem in textDict)
            {
                var key  = textDictItem.Key;
                var text = textDictItem.Value;
                var isWithinRequestLimit = text.Length + _currentRequestCharacterCount <= _maxCharactersPerRequest ? true : false;
                if (isWithinRequestLimit)
                {
                    _currentRequestCharacterCount += text.Length;
                    _request.Add(text);
                }
                else
                {
                    if (_currentRequestCharacterCount + _totalRequestsCharacterCount >= _maxCharactersPer100Seconds)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(100));
                        _totalRequestsCharacterCount = 0; // Reset the count of requests
                    }

                    response = _googleTranslateMock.TranslateText(sourceLanguage, targetLanguage, _request);
                    _translateResponses.Add(response);
                    _totalRequestsCharacterCount += _currentRequestCharacterCount;

                    // Initiate a new request
                    _currentRequestCharacterCount = text.Length;
                    _request.Clear();
                    _request.Add(text);
                }
            }

            // Handle any leftover request
            if (_request.Any())
            {
                response = _googleTranslateMock.TranslateText(sourceLanguage, targetLanguage, _request);
                _translateResponses.Add(response);
            }

            var lastIndex = 0;
            IOrderedDictionary <string, string> translatedTextDict = new OrderedDictionary <string, string>();

            foreach (var translateResponse in _translateResponses)
            {
                var translations = translateResponse.Translations;
                for (int translationIdx = 0; translationIdx < translations.Count; translationIdx++)
                {
                    var translation = translations[translationIdx];
                    if (lastIndex > textDict.Count)
                    {
                        return(translatedTextDict);
                    }

                    var textDictItem = textDict.ElementAt(lastIndex);
                    translatedTextDict.Add(textDictItem.Key, translation.TranslatedText);
                    lastIndex += 1;
                }
            }

            return(translatedTextDict);
        }
Exemplo n.º 39
0
 public ContextPartitionVisitorState()
 {
     States = new OrderedDictionary <ContextStatePathKey, ContextStatePathValue>();
     ContextPartitionInfo = new Dictionary <int, ContextPartitionDescriptor>();
 }
Exemplo n.º 40
0
        public void ReflectObject(object obj)
        {
            OrderedDictionary new_details = new OrderedDictionary();

            if (obj == null)
            {
                Categories = new_details;
                return;
            }

            HideCategoriesAttribute hidden_categories = (HideCategoriesAttribute)obj.GetType().GetCustomAttribute(typeof(HideCategoriesAttribute));

            PropertyInfo[] obj_properties = obj.GetType().GetProperties();

            foreach (PropertyInfo p in obj_properties)
            {
                // We want to ignore all properties that are not marked with the WProperty attribute.
                CustomAttributeData[] custom_attributes   = p.CustomAttributes.ToArray();
                CustomAttributeData   wproperty_attribute = custom_attributes.FirstOrDefault(x => x.AttributeType.Name == "WProperty");
                if (wproperty_attribute == null)
                {
                    continue;
                }

                // Grab our custom attribute data for use
                string      category_name = (string)wproperty_attribute.ConstructorArguments[0].Value;
                string      property_name = (string)wproperty_attribute.ConstructorArguments[1].Value;
                bool        is_editable   = (bool)wproperty_attribute.ConstructorArguments[2].Value;
                string      tool_tip      = (string)wproperty_attribute.ConstructorArguments[3].Value;
                SourceScene source_scene  = (SourceScene)wproperty_attribute.ConstructorArguments[4].Value;

                // Get the base type for possible use later
                Type base_type = p.PropertyType;
                while (base_type.BaseType != typeof(object))
                {
                    base_type = base_type.BaseType;
                }

                // Only add the category to the view if it's not blacklisted by the HideCategories attribute.
                if (!new_details.Contains(category_name) && (hidden_categories == null || !hidden_categories.CategoryHidden(category_name)))
                {
                    new_details.Add(category_name, new WDetailsCategoryRowViewModel(category_name));
                }

                WDetailsCategoryRowViewModel current_category = null;

                if (new_details.Contains(category_name))
                {
                    current_category = (WDetailsCategoryRowViewModel)new_details[category_name];
                }
                else
                {
                    continue;
                }

                /* This is where we generate the control for the details view. */

                List <WDetailSingleRowViewModel> property_rows = new List <WDetailSingleRowViewModel>();

                // We first check if the type of the property has a customization registered.
                // If it is, we just grab the customization and generate a control with it.
                if (m_TypeCustomizations.ContainsKey(p.PropertyType.Name))
                {
                    property_rows = m_TypeCustomizations[p.PropertyType.Name].CustomizeHeader(p, property_name, is_editable, obj);
                }
                // If there is no customization registered, and the type is an enum, we
                // use EnumTypeCustomization to generate a control.
                else if (p.PropertyType.IsEnum)
                {
                    EnumTypeCustomization enu = new EnumTypeCustomization();
                    property_rows = enu.CustomizeHeader(p, property_name, is_editable, obj);
                }
                // Check if the type is an AndvancedBindingList.
                else if (p.PropertyType.Name == typeof(AdvancedBindingList <object>).Name)
                {
                    Type underlying_type   = p.PropertyType.GetGenericArguments().Single();
                    Type type_from_generic = typeof(AdvancedBindingListTypeCustomization <>).MakeGenericType(underlying_type);

                    IPropertyTypeCustomization adv_cus = Activator.CreateInstance(type_from_generic) as IPropertyTypeCustomization;
                    property_rows = adv_cus.CustomizeHeader(p, property_name, is_editable, obj);

                    WAdvancedBindingListControl base_ctrl = property_rows[0].PropertyControl as WAdvancedBindingListControl;
                    base_ctrl.entry_combo.SelectedIndex = 0;
                    property_rows.AddRange(base_ctrl.GenerateBoundFields());
                    base_ctrl.OnEntryComboSelectionChanged();
                }
                // Failing the prior checks, we see if the base type of the property is WDOMNode,
                // in which case we just use the WDOMNode customization to generate a control.
                else if (base_type.Name == typeof(WDOMNode).Name)
                {
                    property_rows = m_TypeCustomizations[typeof(WDOMNode).Name].CustomizeHeader(p, property_name, is_editable, obj);

                    WActorReferenceControl c = (WActorReferenceControl)property_rows[0].PropertyControl;
                    c.Source = source_scene;
                    c.FillComboBox();
                }
                // If the property type is completely unknown or unsupported, we create an empty row with
                // just the property's name.
                else
                {
                    property_rows.Add(new WDetailSingleRowViewModel(property_name));
                }

                // Saw online that adding multiple things to a binding list can be slow,
                // so I'll do what that guy suggested. Disable raising changed events, then re-enable when we're done.
                current_category.PropertyRows.RaiseListChangedEvents = false;

                foreach (var row in property_rows)
                {
                    current_category.PropertyRows.Add(row);

                    if (tool_tip != "")
                    {
                        row.PropertyToolTip = tool_tip;
                    }
                }

                current_category.PropertyRows.RaiseListChangedEvents = true;
                current_category.PropertyRows.ResetBindings();
            }

            // We want to force certain categories to the top of the list, so reorder it at the end.
            foreach (var cat_name in new string[] { "Actor", "Transform", "Entity" })
            {
                if (new_details.Contains(cat_name))
                {
                    var row = new_details[cat_name];
                    new_details.Remove(cat_name);
                    new_details.Insert(0, cat_name, row);
                }
            }

            Categories = new_details;

            if (obj is VisibleDOMNode)
            {
                var entity = (VisibleDOMNode)obj;
                entity.HideTypeSpecificCategories();
            }
        }
Exemplo n.º 41
0
        private void menuItem_ToolBad_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolder = new FolderBrowserDialog();

            if (openFolder.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            List <string> files = new List <string>();

            files.AddRange(Directory.GetFiles(openFolder.SelectedPath, "*.pcap", SearchOption.AllDirectories));
            files.AddRange(Directory.GetFiles(openFolder.SelectedPath, "*.pcapng", SearchOption.AllDirectories));

            OrderedDictionary opcodeOccurrences = new OrderedDictionary();

            foreach (PacketOpcode opcode in Enum.GetValues(typeof(PacketOpcode)))
            {
                opcodeOccurrences[opcode] = 0;
            }

            foreach (string file in files)
            {
                loadPcap(file);

                int curPacket   = 0;
                int curFragment = 0;
                try
                {
                    for (curPacket = 0; curPacket < records.Count; ++curPacket)
                    {
                        PacketRecord record = records[curPacket];
                        for (curFragment = 0; curFragment < record.netPacket.fragList_.Count; ++curFragment)
                        {
                            BlobFrag frag = record.netPacket.fragList_[curFragment];
                            if (frag.memberHeader_.numFrags > 0)
                            {
                                continue;
                            }

                            BinaryReader fragDataReader = new BinaryReader(new MemoryStream(frag.dat_));

                            bool handled = false;
                            foreach (MessageProcessor messageProcessor in messageProcessors)
                            {
                                long readerStartPos = fragDataReader.BaseStream.Position;

                                bool accepted = messageProcessor.acceptMessageData(fragDataReader, treeView_ParsedData);

                                if (accepted && handled)
                                {
                                    throw new Exception("Multiple message processors are handling the same data!");
                                }

                                if (accepted)
                                {
                                    handled = true;
                                }

                                fragDataReader.BaseStream.Position = readerStartPos;
                            }

                            /*if (!handled) {
                             *  PacketOpcode opcode = Util.readOpcode(fragDataReader);
                             *  treeView_ParsedData.Nodes.Add(new TreeNode("Unhandled: " + opcode));
                             * }*/
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Packet " + curPacket + " Fragment " + curFragment + " EXCEPTION: " + ex.Message);
                    break;
                }
            }
        }
Exemplo n.º 42
0
        public static OrderedDictionary DCOMRemoteCreateInstance(byte[] packet_causality_ID, string packet_target)
        {
            byte[] packet_target_unicode = Encoding.Unicode.GetBytes(packet_target);
            byte[] packet_target_length  = BitConverter.GetBytes(packet_target.Length + 1);
            double bytesize = (Math.Truncate((double)packet_target_unicode.Length / 8 + 1) * 8) - packet_target_unicode.Length;

            packet_target_unicode = packet_target_unicode.Concat(new byte[Convert.ToInt32(bytesize)]).ToArray();
            byte[] packet_cntdata            = BitConverter.GetBytes(packet_target_unicode.Length + 720);
            byte[] packet_size               = BitConverter.GetBytes(packet_target_unicode.Length + 680);
            byte[] packet_total_size         = BitConverter.GetBytes(packet_target_unicode.Length + 664);
            byte[] packet_private_header     = BitConverter.GetBytes(packet_target_unicode.Length + 40).Concat(new byte[] { 0x00, 0x00, 0x00, 0x00 }).ToArray();
            byte[] packet_property_data_size = BitConverter.GetBytes(packet_target_unicode.Length + 56);

            OrderedDictionary packet_DCOMRemoteCreateInstance = new OrderedDictionary();

            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_DCOMVersionMajor", new byte[] { 0x05, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_DCOMVersionMinor", new byte[] { 0x07, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_DCOMFlags", new byte[] { 0x01, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_DCOMReserved", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_DCOMCausalityID", packet_causality_ID);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_Unknown", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_Unknown2", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_Unknown3", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_Unknown4", packet_cntdata);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCntData", packet_cntdata);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesOBJREFSignature", new byte[] { 0x4d, 0x45, 0x4f, 0x57 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesOBJREFFlags", new byte[] { 0x04, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesOBJREFIID", new byte[] { 0xa2, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFCLSID", new byte[] { 0x38, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFCBExtension", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFSize", packet_size);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesTotalSize", packet_total_size);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesReserved", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderPrivateHeader", new byte[] { 0xb0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderTotalSize", packet_total_size);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderCustomHeaderSize", new byte[] { 0xc0, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesCustomHeaderReserved", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesDestinationContext", new byte[] { 0x02, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesNumActivationPropertyStructs", new byte[] { 0x06, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsInfoClsid", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrReferentID", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrReferentID", new byte[] { 0x04, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesNULLPointer", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrMaxCount", new byte[] { 0x06, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid", new byte[] { 0xb9, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid2", new byte[] { 0xab, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid3", new byte[] { 0xa5, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid4", new byte[] { 0xa6, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid5", new byte[] { 0xa4, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsIdPtrPropertyStructGuid6", new byte[] { 0xaa, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrMaxCount", new byte[] { 0x06, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize", new byte[] { 0x68, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize2", new byte[] { 0x58, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize3", new byte[] { 0x90, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize4", packet_property_data_size);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize5", new byte[] { 0x20, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesClsSizesPtrPropertyDataSize6", new byte[] { 0x30, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPrivateHeader", new byte[] { 0x58, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesSessionID", new byte[] { 0xff, 0xff, 0xff, 0xff });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesRemoteThisSessionID", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesClientImpersonating", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPartitionIDPresent", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesDefaultAuthnLevel", new byte[] { 0x02, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesPartitionGuid", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesProcessRequestFlags", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesOriginalClassContext", new byte[] { 0x14, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesFlags", new byte[] { 0x02, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesReserved", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSpecialSystemPropertiesUnusedBuffer", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoPrivateHeader", new byte[] { 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInstantiatedObjectClsId", new byte[] { 0x5e, 0xf0, 0xc3, 0x8b, 0x6b, 0xd8, 0xd0, 0x11, 0xa0, 0x75, 0x00, 0xc0, 0x4f, 0xb6, 0x88, 0x20 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoClassContext", new byte[] { 0x14, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoActivationFlags", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoFlagsSurrogate", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInterfaceIdCount", new byte[] { 0x01, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInfoInstantiationFlag", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsPtr", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationEntirePropertySize", new byte[] { 0x58, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationVersionMajor", new byte[] { 0x05, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationVersionMinor", new byte[] { 0x07, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsPtrMaxCount", new byte[] { 0x01, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIds", new byte[] { 0x18, 0xad, 0x09, 0xf3, 0x6a, 0xd8, 0xd0, 0x11, 0xa0, 0x75, 0x00, 0xc0, 0x4f, 0xb6, 0x88, 0x20 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesInstantiationInterfaceIdsUnusedBuffer", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoPrivateHeader", new byte[] { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientOk", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved2", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoReserved3", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrReferentID", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoNULLPtr", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextUnknown", new byte[] { 0x60, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextCntData", new byte[] { 0x60, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFSignature", new byte[] { 0x4d, 0x45, 0x4f, 0x57 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFFlags", new byte[] { 0x04, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFIID", new byte[] { 0xc0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFCLSID", new byte[] { 0x3b, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFCBExtension", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoClientPtrClientContextOBJREFCUSTOMOBJREFSize", new byte[] { 0x30, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesActivationContextInfoUnusedBuffer", new byte[] { 0x01, 0x00, 0x01, 0x00, 0x63, 0x2c, 0x80, 0x2a, 0xa5, 0xd2, 0xaf, 0xdd, 0x4d, 0xc4, 0xbb, 0x37, 0x4d, 0x37, 0x76, 0xd7, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoPrivateHeader", packet_private_header);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoAuthenticationFlags", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoPtrReferentID", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoNULLPtr", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoReserved", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameReferentID", new byte[] { 0x04, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNULLPtr", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoReserved2", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameMaxCount", packet_target_length);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameOffset", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameActualCount", packet_target_length);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesSecurityInfoServerInfoServerInfoNameString", packet_target_unicode);
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoPrivateHeader", new byte[] { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoNULLPtr", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoProcessID", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoApartmentID", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesLocationInfoContextID", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoCommonHeader", new byte[] { 0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoPrivateHeader", new byte[] { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoNULLPtr", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrReferentID", new byte[] { 0x00, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestClientImpersonationLevel", new byte[] { 0x02, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestNumProtocolSequences", new byte[] { 0x01, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestUnknown", new byte[] { 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrReferentID", new byte[] { 0x04, 0x00, 0x02, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrMaxCount", new byte[] { 0x01, 0x00, 0x00, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoRemoteRequestPtrRemoteRequestProtocolSeqsArrayPtrProtocolSeq", new byte[] { 0x07, 0x00 });
            packet_DCOMRemoteCreateInstance.Add("DCOMRemoteCreateInstance_IActPropertiesCUSTOMOBJREFIActPropertiesPropertiesScmRequestInfoUnusedBuffer", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            return(packet_DCOMRemoteCreateInstance);
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            #if TEST_DICTIONARY
            var dicLongLong = new Dictionary <long, long>
            {
                { 1L, 1L },
                { 2L, 2L },
                { 3L, 3L }
            };

            //lock (dicLongLong[2L]) // Error CS0185  'long' is not a reference type as required by the lock statement
            //{}

            var dicIntVictim = new Dictionary <int, Victim>
            {
                { 0, new Victim {
                      FString = "0"
                  } },
                { 1, new Victim {
                      FString = "1"
                  } },
                { 2, new Victim {
                      FString = "2"
                  } }
            };

            foreach (var k in dicIntVictim.Keys)
            {
                dicIntVictim[k].FString = dicIntVictim[k].FString + dicIntVictim[k].FString;
            }

            var dicIntInt = new Dictionary <int, int>
            {
                { 0, 0 },
                { 1, 1 },
                { 2, 2 }
            };

            try
            {
                foreach (var k in dicIntInt.Keys)
                {
                    dicIntInt[k] = dicIntInt[k] + dicIntInt[k];
                }
            }
            catch (InvalidOperationException eInvalidOperationException)
            {
                WriteLine(eInvalidOperationException.Message);
            }

            Dictionary <string, string>
            dic = null;

            try
            {
                foreach (var kvp in dic)
                {
                    WriteLine("\"{0}\" = \"{1}\"", kvp.Key, kvp.Value);
                }
            }
            catch (NullReferenceException eNullReferenceException)
            {
                WriteLine(eNullReferenceException.Message);
            }

            dic = new Dictionary <string, string>();

            foreach (var kvp in dic)
            {
                WriteLine("\"{0}\" = \"{1}\"", kvp.Key, kvp.Value);
            }

            dic.Add("3rd", "3rd");
            dic.Add("2nd", "2nd");
            dic.Add("1st", "1st");

            dic["4th"] = "4th";
            dic["5th"] = "5th";

            try
            {
                if (dic["6th"] != "6th")
                {
                    WriteLine("Tampax");
                }
            }
            catch (KeyNotFoundException eKeyNotFoundException)
            {
                WriteLine(eKeyNotFoundException.Message);
            }

            foreach (KeyValuePair <string, string> v in dic)
            {
                WriteLine("{0} {1}", v.Key, v.Value);
            }
            WriteLine();

            foreach (string k in dic.Keys)
            {
                WriteLine("{0} {1}", k, dic[k]);
            }
            WriteLine();

            try
            {
                foreach (string k in dic.Keys)
                {
                    dic[k] = dic[k] + dic[k];
                }
            }
            catch (InvalidOperationException eInvalidOperationException)
            {
                WriteLine(eInvalidOperationException.Message);
            }

            Dictionary <string, string> .Enumerator e = dic.GetEnumerator();
            while (e.MoveNext())
            {
                WriteLine("{0} {1}", e.Current.Key, e.Current.Value);

                //e.Current.Value += "3rd"; // Error CS0200  Property or indexer 'KeyValuePair<string, string>.Value' cannot be assigned to --it is read only
            }
            e.Dispose();
            WriteLine();

            Dictionary <string, string> .KeyCollection.Enumerator ek = dic.Keys.GetEnumerator();
            try
            {
                while (ek.MoveNext())
                {
                    WriteLine("{0} {1}", ek.Current, dic[ek.Current]);

                    if (ek.Current == "3rd")
                    {
                        dic[ek.Current] = dic[ek.Current] + dic[ek.Current];
                    }
                }
            }
            catch (InvalidOperationException eInvalidOperationException)
            {
                WriteLine(eInvalidOperationException.Message);
            }
            finally
            {
                ek.Dispose();
            }
            WriteLine();

            #region ReadOnlyDictionary

            ReadOnlyDictionary <string, string> roDic = new ReadOnlyDictionary <string, string>(dic);

            foreach (var kvp in roDic)
            {
                WriteLine($"[\"{kvp.Key}\"] = \"{kvp.Value}\"");
            }
            WriteLine();

            //roDic["3rd"] = "3rd"; // Error CS0200  Property or indexer 'ReadOnlyDictionary<string, string>.this[string]' cannot be assigned to --it is read only

            dic["6th"] = "6th";
            dic["7th"] = "7th";
            dic["3rd"] = "3rd";

            foreach (var kvp in roDic)
            {
                WriteLine($"[\"{kvp.Key}\"] = \"{kvp.Value}\"");
            }
            WriteLine();

            #endregion

            #region OrderedDictionary

            OrderedDictionary
                oDic = new OrderedDictionary();

            oDic.Add("3rd", "3rd");
            oDic.Add("2nd", "2nd");
            oDic.Add("1st", "1st");

            oDic["4th"] = "4th";
            oDic["5th"] = "5th";

            foreach (DictionaryEntry v in oDic)
            {
                Console.WriteLine("{0} {1}", v.Key, v.Value);
            }
            Console.WriteLine();

            IDictionaryEnumerator oe = oDic.GetEnumerator();
            while (oe.MoveNext())
            {
                Console.WriteLine("{0} {1}", oe.Key, oe.Value);
            }
            Console.WriteLine();

            IEnumerator oek = oDic.Keys.GetEnumerator();
            while (oek.MoveNext())
            {
                Console.WriteLine("{0} {1}", oek.Current, oDic[oek.Current]);
            }
            Console.WriteLine();

            oDic = new OrderedDictionary();
            oDic.Add("3rd", "3rd (value)");
            oDic.Add("2nd", "2nd (value)");
            oDic.Insert(0, "1st", "1st (value)");

            for (var i = 0; i < oDic.Count; ++i)
            {
                Console.WriteLine("{0}", oDic[i]);
            }
            Console.WriteLine();

            foreach (DictionaryEntry v in oDic)
            {
                Console.WriteLine("{0} {1}", v.Key, v.Value);
            }
            Console.WriteLine();

            oe = oDic.GetEnumerator();
            while (oe.MoveNext())
            {
                Console.WriteLine("{0} {1}", oe.Key, oe.Value);
            }
            Console.WriteLine();

            oek = oDic.Keys.GetEnumerator();
            while (oek.MoveNext())
            {
                Console.WriteLine("{0} {1}", oek.Current, oDic[oek.Current]);
            }
            Console.WriteLine();

            IList a  = oDic.Cast <DictionaryEntry>().Select(de => de.Value).ToList();
            IList aa = oDic.Keys.Cast <string>().ToList();
            Console.WriteLine();

            #endregion
            #endif

            #if TEST_LIST
            List <StringStringPair>
            listOfStringStringPair = new List <StringStringPair>(new StringStringPair[] { new StringStringPair("aa", "bb") });

            StringStringPair
                stringStringPair = new StringStringPair("aa", "bb");

            if (listOfStringStringPair.Contains(stringStringPair))
            {
                Console.WriteLine("Already exists!");
            }

            stringStringPair = new StringStringPair("bb", "aa");
            if (listOfStringStringPair.Contains(stringStringPair))
            {
                Console.WriteLine("Already exists!");
            }

            stringStringPair = new StringStringPair("bb", "cc");
            if (listOfStringStringPair.Contains(stringStringPair))
            {
                Console.WriteLine("Already exists!");
            }

            listOfStringStringPair.Add(new StringStringPair("bb", "aa"));
            listOfStringStringPair.Add(new StringStringPair("bb", "cc"));

            var tmp = listOfStringStringPair.Distinct().ToArray();
            tmp = listOfStringStringPair.Distinct(new StringStringPairComparer()).ToArray();

            List <int>
            listOfIntI      = new List <int>(new int[] { 1, 2, 3, 4, 5 }),
                listOfIntII = new List <int>(new int[] { 1, 3, 5 });

            listOfIntI.RemoveAll(listOfIntII.Contains);

            A
                a = new A(13);

            List <A>
            listOfAI      = new List <A>(new A[] { a, new A(1), new A(2), new A(3), new A(4), new A(5), null }),
                listOfAII = new List <A>(new A[] { a, new A(1), new A(3), new A(5) });

            listOfAI.RemoveAll(listOfAII.Contains);

            listOfIntI = new List <int>(new int[] { 1, 2, 3, 4, 5 });
            foreach (var i in listOfIntI.ToArray())
            {
                if (i % 2 == 0)
                {
                    listOfIntI.Remove(i);
                }
            }
            #endif
        }
        public JsonResult GetSearchResults_WithLeftFiltersSelected(string jobRequest, int pageNumber, string sortBy)
        {
            //Use preconfigured search config from widget settings if available
            JobSearchResultsFilterModel searchInputs;



            if (SearchConfig != null)
            {
                searchInputs = JsonConvert.DeserializeObject <JobSearchResultsFilterModel>(SearchConfig);
            }
            else
            {
                searchInputs = JsonConvert.DeserializeObject <JobSearchResultsFilterModel>(jobRequest);
            }

            if (this.UseConfigFilters)
            {
                var jobFilterComponents = this.SerializedJobSearchParams == null ? null : JsonConvert.DeserializeObject <List <JobSearchModel> >(this.SerializedJobSearchParams);

                if (jobFilterComponents != null)
                {
                    searchInputs = new JobSearchResultsFilterModel()
                    {
                        Keywords = this.KeywordsSelectedJobs, Filters = new List <JobSearchFilterReceiver>()
                    };
                    foreach (JobSearchModel item in jobFilterComponents)
                    {
                        FilterData(item.Filters);
                        item.Filters = item.Filters.Where(d => d.Show == true || d.Filters?.Count > 0).ToList();
                    }

                    foreach (var configItem in jobFilterComponents)
                    {
                        var rootFilterItem = new JobSearchFilterReceiver()
                        {
                            values = new List <JobSearchFilterReceiverItem>()
                        };
                        rootFilterItem.rootId = configItem.FilterType;

                        foreach (var subFilItem in configItem.Filters)
                        {
                            var targetFilterItem = new JobSearchFilterReceiverItem()
                            {
                                SubTargets = new List <JobSearchFilterReceiverItem>()
                            };
                            ProcessConfigFilterItems(targetFilterItem, subFilItem);
                            rootFilterItem.values.Add(targetFilterItem);
                        }

                        searchInputs.Filters.Add(rootFilterItem);
                    }
                }
            }

            searchInputs.Page   = pageNumber;
            searchInputs.SortBy = sortBy;

            if (!this.PageSize.HasValue || this.PageSize.Value <= 0)
            {
                this.PageSize = PageSizeDefaultValue;
            }

            JXTNext_SearchJobsRequest searchRequest = JobSearchResultsFilterModel.ProcessInputToSearchRequest(searchInputs, this.PageSize, PageSizeDefaultValue);


            #region Filter Logic

            List <string> selectedFilterID = new List <string>();
            List <JobSearchFilterReceiver> selectedFilters = searchInputs.Filters;
            if (selectedFilters != null)
            {
                foreach (var filter in selectedFilters)
                {
                    if (filter != null)
                    {
                        foreach (var value in filter.values)
                        {
                            if (value != null)
                            {
                                selectedFilterID.Add(value.ItemID);
                                if (value.SubTargets != null)
                                {
                                    foreach (var subTarget in value.SubTargets)
                                    {
                                        selectedFilterID.Add(value.ItemID + "_" + subTarget.ItemID);
                                    }
                                }
                            }
                        }
                    }
                }
            }



            #endregion


            string sortingBy = this.Sorting;
            if (searchInputs != null && !searchInputs.SortBy.IsNullOrEmpty())
            {
                sortingBy = searchInputs.SortBy;
            }

            searchRequest.SortBy = JobSearchResultsFilterModel.GetSortEnumFromString(sortingBy);
            ViewBag.SortOrder    = JobSearchResultsFilterModel.GetSortStringFromEnum(searchRequest.SortBy);

            JXTNext_SearchJobsResponse jobResponse = (JXTNext_SearchJobsResponse)_BLConnector.SearchJobs(searchRequest);

            foreach (var item in jobResponse.SearchResults)
            {
                List <OrderedDictionary> classificationItemsList = new List <OrderedDictionary>();
                item.ClassificationsRootName = "Classifications";

                // Assuming the maximum ten parents the job will be posted
                for (int i = 0; i < 10; i++)
                {
                    string key   = "Classifications[0].Filters[" + i + "].ExternalReference";
                    string value = "Classifications[0].Filters[" + i + "].Value";
                    string parentClassificationsKey = "Classifications[0].Filters[" + i + "].SubLevel[0]";
                    if (item.CustomData.ContainsKey(key))
                    {
                        OrderedDictionary classifOrdDict = new OrderedDictionary();
                        classifOrdDict.Add(item.CustomData[key], item.CustomData[value]);
                        JobDetailsViewModel.ProcessCustomData(parentClassificationsKey, item.CustomData, classifOrdDict);
                        OrderedDictionary classifParentIdsOrdDict = new OrderedDictionary();
                        JobDetailsViewModel.AppendParentIds(classifOrdDict, classifParentIdsOrdDict);
                        classificationItemsList.Add(classifParentIdsOrdDict);
                        item.Classifications = classificationItemsList;
                    }
                }

                // Take the first item in the list as SEO route for Job Details page
                if (item.ClassificationURL != null)
                {
                    item.ClassificationsSEORouteName = item.ClassificationURL;
                }
                else if (item.Classifications.Count > 0)
                {
                    List <string> seoString = new List <string>();
                    foreach (var key in item.Classifications[0].Keys)
                    {
                        string value     = item.Classifications[0][key].ToString();
                        string SEOString = Regex.Replace(value, @"([^\w]+)", "-");
                        seoString.Add(SEOString + "-jobs");
                    }
                    seoString.Add(Regex.Replace(item.Title + "-job", @"([^\w]+)", "-"));

                    item.ClassificationsSEORouteName = String.Join("/", seoString);
                }
            }

            jobResponse.SelectedFilters = selectedFilterID;

            return(new JsonResult {
                Data = jobResponse
            });
        }
Exemplo n.º 45
0
        /// <summary>
        /// Gets the name for ingredients in regards to food.
        /// </summary>
        /// <param name="worldForResolve">The world to resolve in.</param>
        /// <param name="recipeCode">The recipe code.</param>
        /// <param name="stacks">The stacks of items to add.</param>
        /// <returns>The name of the food type.</returns>
        public string GetNameForIngredients(IWorldAccessor worldForResolve, string recipeCode, ItemStack[] stacks)
        {
            OrderedDictionary <ItemStack, int> quantitiesByStack = new OrderedDictionary <ItemStack, int>();

            quantitiesByStack = mergeStacks(worldForResolve, stacks);

            CookingRecipe recipe = worldForResolve.CookingRecipes.FirstOrDefault(rec => rec.Code == recipeCode);

            if (recipeCode == null || recipe == null)
            {
                return("unknown");
            }

            int           max                 = 1;
            string        MealFormat          = "meal";
            string        topping             = string.Empty;
            ItemStack     PrimaryIngredient   = null;
            ItemStack     SecondaryIngredient = null;
            List <string> OtherIngredients    = new List <string>();
            List <string> MashedNames         = new List <string>();
            List <string> GarnishedNames      = new List <string>();
            List <string> grainNames          = new List <string>();
            string        mainIngredients;
            string        everythingelse = "";


            switch (recipeCode)
            {
            case "soup":
            {
                max = 0;
                foreach (var val in quantitiesByStack)
                {
                    CookingRecipeIngredient ingred = recipe.GetIngrendientFor(val.Key);
                    if (val.Key.Collectible.Code.Path.Contains("waterportion"))
                    {
                        continue;
                    }
                    if (ingred?.Code == "topping")
                    {
                        topping = "honeyportion";
                        continue;
                    }


                    if (max < val.Value)
                    {
                        max = val.Value;
                        if (PrimaryIngredient != null)
                        {
                            SecondaryIngredient = PrimaryIngredient;
                        }
                        PrimaryIngredient = val.Key;
                    }
                    else
                    {
                        OtherIngredients.Add(ingredientName(val.Key, true));
                    }
                }

                if (max == 2)
                {
                    max = 3;
                }
                else if (max == 3)
                {
                    max = 4;
                }
                else
                {
                    max = 2;
                }

                break;
            }

            case "porridge":
            {
                max = 0;
                foreach (var val in quantitiesByStack)
                {
                    CookingRecipeIngredient ingred = recipe.GetIngrendientFor(val.Key);
                    if (getFoodCat(val.Key) == EnumFoodCategory.Grain)
                    {
                        max++;
                        if (PrimaryIngredient == null)
                        {
                            PrimaryIngredient = val.Key;
                        }
                        else if (SecondaryIngredient == null && val.Key != PrimaryIngredient)
                        {
                            SecondaryIngredient = val.Key;
                        }

                        continue;
                    }

                    if (ingred?.Code == "topping")
                    {
                        topping = "honeyportion";
                        continue;
                    }

                    MashedNames.Add(ingredientName(val.Key, true));
                }
                break;
            }

            case "meatystew":
            {
                max = 0;
                foreach (var val in quantitiesByStack)
                {
                    CookingRecipeIngredient ingred = recipe.GetIngrendientFor(val.Key);

                    EnumFoodCategory foodCat = getFoodCat(val.Key);

                    if (foodCat == EnumFoodCategory.Protein)
                    {
                        if (PrimaryIngredient == val.Key || SecondaryIngredient == val.Key)
                        {
                            continue;
                        }

                        if (PrimaryIngredient == null)
                        {
                            PrimaryIngredient = val.Key;
                        }
                        else if (SecondaryIngredient == null)
                        {
                            SecondaryIngredient = val.Key;
                        }
                        else
                        {
                            OtherIngredients.Add(ingredientName(val.Key, true));
                        }

                        max += val.Value;

                        continue;
                    }


                    if (ingred?.Code == "topping")
                    {
                        topping = "honeyportion";
                        continue;
                    }

                    OtherIngredients.Add(ingredientName(val.Key, true));
                }

                recipeCode = "stew";
                break;
            }

            case "vegetablestew":
            {
                max = 0;

                foreach (var val in quantitiesByStack)
                {
                    if (getFoodCat(val.Key) == EnumFoodCategory.Vegetable)
                    {
                        if (PrimaryIngredient == val.Key || SecondaryIngredient == val.Key)
                        {
                            continue;
                        }

                        if (PrimaryIngredient == null)
                        {
                            PrimaryIngredient = val.Key;
                        }
                        else if (SecondaryIngredient == null)
                        {
                            SecondaryIngredient = val.Key;
                        }
                        else
                        {
                            GarnishedNames.Add(ingredientName(val.Key, true));
                        }

                        max += val.Value;

                        continue;
                    }
                    GarnishedNames.Add(ingredientName(val.Key, true));
                }

                // Slightly ugly hack for soybean stew
                if (PrimaryIngredient == null)
                {
                    foreach (var val in quantitiesByStack)
                    {
                        //CookingRecipeIngredient ingred = recipe.GetIngrendientFor(val.Key); - whats this for?
                        PrimaryIngredient = val.Key;
                        max += val.Value;
                    }
                }

                recipeCode = "stew";
                break;
            }


            case "jam":
            {
                foreach (var val in quantitiesByStack)
                {
                    if (val.Key.Collectible.NutritionProps?.FoodCategory == EnumFoodCategory.Fruit)
                    {
                        return(Lang.Get("{0} jam", val.Key.GetName()));
                    }
                }

                break;
            }
            }



            switch (max)
            {
            case 3:
                MealFormat += "-hearty-" + recipeCode;
                break;

            case 4:
                MealFormat += "-hefty-" + recipeCode;
                break;

            default:
                MealFormat += "-normal-" + recipeCode;
                break;
            }

            if (topping == "honeyportion")
            {
                MealFormat += "-honey";
            }
            //mealformat is done.  Time to do the main inredients.



            if (SecondaryIngredient != null)
            {
                mainIngredients = Lang.Get("multi-main-ingredients-format", getMainIngredientName(PrimaryIngredient, recipeCode), getMainIngredientName(SecondaryIngredient, recipeCode, true));
            }
            else
            {
                mainIngredients = PrimaryIngredient == null ? "" : getMainIngredientName(PrimaryIngredient, recipeCode);
            }
            // Main ingredients are done.

            switch (recipeCode)
            {
            case "porridge":
                if (MashedNames.Count > 0)
                {
                    everythingelse = getMealAddsString("meal-adds-porridge-mashed", MashedNames);
                }
                else
                {
                    everythingelse = "";
                }
                break;

            case "stew":
                if (OtherIngredients.Count > 0)
                {
                    everythingelse = getMealAddsString("meal-adds-meatystew-boiled", OtherIngredients);
                }
                else if (GarnishedNames.Count > 0)
                {
                    everythingelse = getMealAddsString("meal-adds-vegetablestew-garnish", GarnishedNames);
                }
                else
                {
                    everythingelse = "";
                }
                break;

            case "soup":
                if (OtherIngredients.Count > 0)
                {
                    everythingelse = getMealAddsString("meal-adds-generic", OtherIngredients);
                }
                break;
            }
            //everything else is done.

            return(Lang.Get(MealFormat, mainIngredients, everythingelse).Trim().UcFirst());
        }
Exemplo n.º 46
0
        /// <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 =>
                    {
                        try
                        {
                            reference.SourceLine =
                                file.GetLine(reference.ScriptRegion.StartLineNumber);
                        }
                        catch (ArgumentOutOfRangeException e)
                        {
                            reference.SourceLine = string.Empty;
                            this.logger.WriteException("Found reference is out of range in script file", e);
                        }

                        reference.FilePath = file.FilePath;
                        return(reference);
                    });

                    symbolReferences.AddRange(symbolReferencesinFile);
                }

                return
                    (new FindReferencesResult
                {
                    SymbolFileOffset = symbolOffset,
                    SymbolName = foundSymbol.SymbolName,
                    FoundReferences = symbolReferences
                });
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 47
0
 public AcadApplications()
 {
     mblnOpened           = true;
     mcolClass            = new OrderedDictionary();
     mlngApplicationIndex = -1;
 }
Exemplo n.º 48
0
        public static void LoadMembers(Type type, Type attributeType)
        {
            if (type == null)
            {
                throw new NullReferenceException("type");
            }
            if (attributeType == null)
            {
                throw new NullReferenceException("attributeType");
            }

            if (_typeMembersDictionaryCache.ContainsKey(type) &&
                _typeMembersDictionaryCache[type] != null &&
                _typeMembersDictionaryCache[type].ContainsKey(attributeType))
            {
                return;
            }

            lock (_typeMembersDictionaryCacheLockObject)
            {
                if (_typeMembersDictionaryCache.ContainsKey(type) &&
                    _typeMembersDictionaryCache[type] != null &&
                    _typeMembersDictionaryCache[type].ContainsKey(attributeType))
                {
                    return;
                }

                InitDicts(type, attributeType);

                OrderedDictionary myMemberInfos   = new OrderedDictionary();
                OrderedDictionary myFieldInfos    = new OrderedDictionary();
                OrderedDictionary myPropertyInfos = new OrderedDictionary();

                OrderedDictionary myNonReadOnlyMemberInfos   = new OrderedDictionary();
                OrderedDictionary myNonReadOnlyFieldInfos    = new OrderedDictionary();
                OrderedDictionary myNonReadOnlyPropertyInfos = new OrderedDictionary();

                foreach (MemberInfo memberInfo in type.GetMembers(BindingFlags.Instance | BindingFlags.Public))
                {
                    if (!(memberInfo is PropertyInfo) &&
                        !(memberInfo is FieldInfo)
                        )
                    {
                        continue;
                    }

                    object memberAttribute = memberInfo.GetCustomAttribute(attributeType);
                    if (memberAttribute == null)
                    {
                        continue;
                    }

                    myMemberInfos.Add(memberInfo.Name, memberInfo);

                    if (memberInfo is FieldInfo)
                    {
                        myFieldInfos.Add(memberInfo.Name, memberInfo);
                    }
                    else
                    {
                        myPropertyInfos.Add(memberInfo.Name, memberInfo);
                    }

                    if (!ChoType.IsReadOnlyMember(memberInfo))
                    {
                        myNonReadOnlyMemberInfos.Add(memberInfo.Name, memberInfo);

                        if (memberInfo is FieldInfo)
                        {
                            myNonReadOnlyFieldInfos.Add(memberInfo.Name, memberInfo);
                        }
                        else
                        {
                            myNonReadOnlyPropertyInfos.Add(memberInfo.Name, memberInfo);
                        }
                    }
                }

                _typeMembersDictionaryCache[type][attributeType]   = new ArrayList(myMemberInfos.Values).ToArray(typeof(MemberInfo)) as MemberInfo[];
                _typeFieldsDictionaryCache[type][attributeType]    = new ArrayList(myFieldInfos.Values).ToArray(typeof(FieldInfo)) as FieldInfo[];
                _typeProperiesDictionaryCache[type][attributeType] = new ArrayList(myPropertyInfos.Values).ToArray(typeof(PropertyInfo)) as PropertyInfo[];

                _typeNonReadOnlyMembersDictionaryCache[type][attributeType]   = new ArrayList(myNonReadOnlyMemberInfos.Values).ToArray(typeof(MemberInfo)) as MemberInfo[];
                _typeNonReadOnlyFieldsDictionaryCache[type][attributeType]    = new ArrayList(myNonReadOnlyFieldInfos.Values).ToArray(typeof(FieldInfo)) as FieldInfo[];
                _typeNonReadOnlyProperiesDictionaryCache[type][attributeType] = new ArrayList(myNonReadOnlyPropertyInfos.Values).ToArray(typeof(PropertyInfo)) as PropertyInfo[];
            }
        }
Exemplo n.º 49
0
 void publishers_AddEvent(OrderedDictionary <string, Publisher> sender, string key, Publisher value)
 {
     value.Test = this;
 }
Exemplo n.º 50
0
 public ValueCollection(OrderedDictionary <TKey, TValue> orderedDictionary)
 {
     this.orderedDictionary = orderedDictionary;
 }
Exemplo n.º 51
0
 public AttributeList(Datamodel owner)
 {
     Inner = new OrderedDictionary();
     Owner = owner;
 }
Exemplo n.º 52
0
        new protected virtual void GetSelectedItems(Item[] sources, out ArrayList selected, out OrderedDictionary unselected)
        {
            Assert.ArgumentNotNull(sources, "sources");
            var listString = new ListString(Value);

            unselected = new OrderedDictionary();
            selected   = new ArrayList(listString.Count);
            for (int index = 0; index < listString.Count; ++index)
            {
                selected.Add(listString[index]);
            }
            foreach (Item obj in sources)
            {
                string str   = obj.ID.ToString();
                int    index = listString.IndexOf(str);
                if (index >= 0)
                {
                    selected[index] = obj;
                }
                else
                {
                    unselected.Add(MainUtil.GetSortKey(obj.Name), obj);
                }
            }
        }
Exemplo n.º 53
0
 public Document()
 {
     Metadata = new OrderedDictionary();
     Path     = null;
 }
Exemplo n.º 54
0
 public FormTestApplication()
 {
     InitializeComponent();
     localAddresses = new OrderedDictionary();
 }
Exemplo n.º 55
0
        /// <summary>
        /// WMIExec contains all of the functions used to manually create SMB Packet Structures for Pass the Hash attacks.
        /// </summary>
        /// <remarks>
        /// Based Heavily on Kevin Robertsons Invoke-TheHash toolset (Found
        /// at https://github.com/Kevin-Robertson/Invoke-TheHash)
        /// </remarks>

        public static OrderedDictionary RPCBind(int packet_call_ID, byte[] packet_max_frag, byte[] packet_num_ctx_items, byte[] packet_context_ID, byte[] packet_UUID, byte[] packet_UUID_version)
        {
            byte[] packet_call_ID_bytes = BitConverter.GetBytes(packet_call_ID);

            OrderedDictionary packet_RPCBind = new OrderedDictionary();

            packet_RPCBind.Add("RPCBind_Version", new byte[] { 0x05 });
            packet_RPCBind.Add("RPCBind_VersionMinor", new byte[] { 0x00 });
            packet_RPCBind.Add("RPCBind_PacketType", new byte[] { 0x0b });
            packet_RPCBind.Add("RPCBind_PacketFlags", new byte[] { 0x03 });
            packet_RPCBind.Add("RPCBind_DataRepresentation", new byte[] { 0x10, 0x00, 0x00, 0x00 });
            packet_RPCBind.Add("RPCBind_FragLength", new byte[] { 0x48, 0x00 });
            packet_RPCBind.Add("RPCBind_AuthLength", new byte[] { 0x00, 0x00 });
            packet_RPCBind.Add("RPCBind_CallID", packet_call_ID_bytes);
            packet_RPCBind.Add("RPCBind_MaxXmitFrag", new byte[] { 0xb8, 0x10 });
            packet_RPCBind.Add("RPCBind_MaxRecvFrag", new byte[] { 0xb8, 0x10 });
            packet_RPCBind.Add("RPCBind_AssocGroup", new byte[] { 0x00, 0x00, 0x00, 0x00 });
            packet_RPCBind.Add("RPCBind_NumCtxItems", packet_num_ctx_items);
            packet_RPCBind.Add("RPCBind_Unknown", new byte[] { 0x00, 0x00, 0x00 });
            packet_RPCBind.Add("RPCBind_ContextID", packet_context_ID);
            packet_RPCBind.Add("RPCBind_NumTransItems", new byte[] { 0x01 });
            packet_RPCBind.Add("RPCBind_Unknown2", new byte[] { 0x00 });
            packet_RPCBind.Add("RPCBind_Interface", packet_UUID);
            packet_RPCBind.Add("RPCBind_InterfaceVer", packet_UUID_version);
            packet_RPCBind.Add("RPCBind_InterfaceVerMinor", new byte[] { 0x00, 0x00 });
            packet_RPCBind.Add("RPCBind_TransferSyntax", new byte[] { 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60 });
            packet_RPCBind.Add("RPCBind_TransferSyntaxVer", new byte[] { 0x02, 0x00, 0x00, 0x00 });


            if (packet_num_ctx_items[0] == 2)
            {
                packet_RPCBind.Add("RPCBind_ContextID2", new byte[] { 0x01, 0x00 });
                packet_RPCBind.Add("RPCBind_NumTransItems2", new byte[] { 0x01 });
                packet_RPCBind.Add("RPCBind_Unknown3", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_Interface2", new byte[] { 0xc4, 0xfe, 0xfc, 0x99, 0x60, 0x52, 0x1b, 0x10, 0xbb, 0xcb, 0x00, 0xaa, 0x00, 0x21, 0x34, 0x7a });
                packet_RPCBind.Add("RPCBind_InterfaceVer2", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_InterfaceVerMinor2", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_TransferSyntax2", new byte[] { 0x2c, 0x1c, 0xb7, 0x6c, 0x12, 0x98, 0x40, 0x45, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_TransferSyntaxVer2", new byte[] { 0x01, 0x00, 0x00, 0x00 });
            }
            else if (packet_num_ctx_items[0] == 3)
            {
                packet_RPCBind.Add("RPCBind_ContextID2", new byte[] { 0x01, 0x00 });
                packet_RPCBind.Add("RPCBind_NumTransItems2", new byte[] { 0x01 });
                packet_RPCBind.Add("RPCBind_Unknown3", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_Interface2", new byte[] { 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
                packet_RPCBind.Add("RPCBind_InterfaceVer2", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_InterfaceVerMinor2", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_TransferSyntax2", new byte[] { 0x33, 0x05, 0x71, 0x71, 0xba, 0xbe, 0x37, 0x49, 0x83, 0x19, 0xb5, 0xdb, 0xef, 0x9c, 0xcc, 0x36 });
                packet_RPCBind.Add("RPCBind_TransferSyntaxVer2", new byte[] { 0x01, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_ContextID3", new byte[] { 0x02, 0x00 });
                packet_RPCBind.Add("RPCBind_NumTransItems3", new byte[] { 0x01 });
                packet_RPCBind.Add("RPCBind_Unknown4", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_Interface3", new byte[] { 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 });
                packet_RPCBind.Add("RPCBind_InterfaceVer3", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_InterfaceVerMinor3", new byte[] { 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_TransferSyntax3", new byte[] { 0x2c, 0x1c, 0xb7, 0x6c, 0x12, 0x98, 0x40, 0x45, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_TransferSyntaxVer3", new byte[] { 0x01, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_AuthType", new byte[] { 0x0a });
                packet_RPCBind.Add("RPCBind_AuthLevel", new byte[] { 0x04 });
                packet_RPCBind.Add("RPCBind_AuthPadLength", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_AuthReserved", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_ContextID4", new byte[] { 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_Identifier", new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 });
                packet_RPCBind.Add("RPCBind_MessageType", new byte[] { 0x01, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_NegotiateFlags", new byte[] { 0x97, 0x82, 0x08, 0xe2 });
                packet_RPCBind.Add("RPCBind_CallingWorkstationDomain", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_CallingWorkstationName", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_OSVersion", new byte[] { 0x06, 0x01, 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f });
            }

            if (packet_call_ID == 3)
            {
                packet_RPCBind.Add("RPCBind_AuthType", new byte[] { 0x0a });
                packet_RPCBind.Add("RPCBind_AuthLevel", new byte[] { 0x02 });
                packet_RPCBind.Add("RPCBind_AuthPadLength", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_AuthReserved", new byte[] { 0x00 });
                packet_RPCBind.Add("RPCBind_ContextID3", new byte[] { 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_Identifier", new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 });
                packet_RPCBind.Add("RPCBind_MessageType", new byte[] { 0x01, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_NegotiateFlags", new byte[] { 0x97, 0x82, 0x08, 0xe2 });
                packet_RPCBind.Add("RPCBind_CallingWorkstationDomain", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_CallingWorkstationName", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
                packet_RPCBind.Add("RPCBind_OSVersion", new byte[] { 0x06, 0x01, 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f });
            }

            return(packet_RPCBind);
        }
Exemplo n.º 56
0
        /// <summary>
        ///     Now that the portData has been set for the new ports, we recreate the connections we
        ///     so mercilessly destroyed, restoring peace and balance to the world once again.
        /// </summary>
        /// <param name="inportConnections"></param>
        /// <param name="outportConnections"> List of the connections that were killed</param>
        private void LoadAndCreateConnectors(OrderedDictionary inportConnections, OrderedDictionary outportConnections)
        {
            //----------------------------Inputs---------------------------------
            /* Input Port connections are matched only if the name is the same */
            for (int i = 0; i < InPortData.Count; i++)
            {
                string varName = InPortData[i].ToolTipString;
                if (inportConnections.Contains(varName))
                {
                    if (inportConnections[varName] != null)
                    {
                        foreach (var startPortModel in (inportConnections[varName] as List <PortModel>))
                        {
                            NodeModel startNode = startPortModel.Owner;
                            var       connector = ConnectorModel.Make(
                                startNode,
                                this,
                                startPortModel.Index,
                                i);
                        }
                        outportConnections[varName] = null;
                    }
                }
            }

            //----------------------------Outputs--------------------------------

            /*The matching is done in three parts:
             * Step 1:
             *   First, it tries to match the connectors wrt to the defined
             *   variable name. Hence it first checks to see if any of the old
             *   variable names are present. If so, if there were any connectors
             *   presnt then it makes the new connectors. As it iterates through
             *   the new ports, it also finds the ports that didnt exist before
             */
            List <int> undefinedIndices = new List <int>();

            for (int i = 0; i < OutPortData.Count; i++)
            {
                string varName = OutPortData[i].ToolTipString;
                if (outportConnections.Contains(varName))
                {
                    if (outportConnections[varName] != null)
                    {
                        foreach (var endPortModel in (outportConnections[varName] as List <PortModel>))
                        {
                            NodeModel endNode   = endPortModel.Owner;
                            var       connector = ConnectorModel.Make(this, endNode, i, endPortModel.Index);
                        }
                        outportConnections[varName] = null;
                    }
                }
                else
                {
                    undefinedIndices.Add(i);
                }
            }

            /*
             * Step 2:
             *   The second priority is to match the connections to the previous
             *   indices. For all the ports that were not previously defined, it
             *   now checks if that "numbered" port had any connections
             *   previously, ie, if the old third port had 2 connections, then
             *   these would go to the new 3rd port (if it is not a variable that
             *   was defined before)
             */
            for (int i = 0; i < undefinedIndices.Count; i++)
            {
                int index = undefinedIndices[i];
                if (index < outportConnections.Count && outportConnections[index] != null)
                {
                    foreach (PortModel endPortModel in (outportConnections[index] as List <PortModel>))
                    {
                        NodeModel endNode   = endPortModel.Owner;
                        var       connector = ConnectorModel.Make(this, endNode, index, endPortModel.Index);
                    }
                    outportConnections[index] = null;
                    undefinedIndices.Remove(index);
                    i--;
                }
            }

            /*
             * Step 2:
             *   The final step. Now that the priorties are finished, the
             *   function tries to reuse any existing connections by attaching
             *   them to any ports that have not already been given connections
             */
            List <List <PortModel> > unusedConnections =
                outportConnections.Values.Cast <List <PortModel> >()
                .Where(portModelList => portModelList != null)
                .ToList();

            while (undefinedIndices.Count > 0 && unusedConnections.Count != 0)
            {
                foreach (PortModel endPortModel in unusedConnections[0])
                {
                    NodeModel      endNode   = endPortModel.Owner;
                    ConnectorModel connector = ConnectorModel.Make(
                        this,
                        endNode,
                        undefinedIndices[0],
                        endPortModel.Index);
                }
                undefinedIndices.RemoveAt(0);
                unusedConnections.RemoveAt(0);
            }
        }
        protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources)
        {
            if (resource == null)
            {
                return;
            }
            // Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required
            // location is Head, so too should Bar's location.
            // forge the effective require settings for this resource
            // (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values.
            // (2) If no require already exists, form a new settings object based on the given one but with its own type/name.
            settings = allResources.Contains(resource)
                ? ((RequireSettings)allResources[resource]).Combine(settings)
                : new RequireSettings {
                Type = resource.Type, Name = resource.Name
            }.Combine(settings);
            if (resource.Dependencies != null)
            {
                var dependencies =
                    from d in resource.Dependencies
                    select FindResource(new RequireSettings { Type = resource.Type, Name = d });

                foreach (var dependency in dependencies)
                {
                    if (dependency == null)
                    {
                        continue;
                    }
                    ExpandDependencies(dependency, settings, allResources);
                }
            }
            allResources[resource] = settings;
        }
        /// <summary>
        ///     Produces an aggregation service for use with match-recognice.
        /// </summary>
        /// <param name="numStreams">number of streams</param>
        /// <param name="measureExprNodesPerStream">measure nodes</param>
        /// <param name="typesPerStream">type information</param>
        /// <exception cref="ExprValidationException">for validation errors</exception>
        /// <returns>service</returns>
        public static AggregationServiceMatchRecognizeFactoryDesc GetServiceMatchRecognize(
            int numStreams,
            IDictionary<int, IList<ExprAggregateNode>> measureExprNodesPerStream,
            EventType[] typesPerStream)
        {
            var equivalencyListPerStream = new OrderedDictionary<int, List<AggregationServiceAggExpressionDesc>>();

            foreach (var entry in measureExprNodesPerStream)
            {
                var equivalencyList = new List<AggregationServiceAggExpressionDesc>();
                equivalencyListPerStream.Put(entry.Key, equivalencyList);
                foreach (ExprAggregateNode selectAggNode in entry.Value)
                {
                    AddEquivalent(selectAggNode, equivalencyList);
                }
            }

            var aggregatorsPerStream = new LinkedHashMap<int, AggregationMethodFactory[]>();
            var evaluatorsPerStream = new Dictionary<int, ExprEvaluator[]>();

            foreach (var equivalencyPerStream in equivalencyListPerStream)
            {
                int index = 0;
                int stream = equivalencyPerStream.Key;

                var aggregators = new AggregationMethodFactory[equivalencyPerStream.Value.Count];
                aggregatorsPerStream.Put(stream, aggregators);

                var evaluators = new ExprEvaluator[equivalencyPerStream.Value.Count];
                evaluatorsPerStream.Put(stream, evaluators);

                foreach (AggregationServiceAggExpressionDesc aggregation in equivalencyPerStream.Value)
                {
                    ExprAggregateNode aggregateNode = aggregation.AggregationNode;
                    if (aggregateNode.ChildNodes.Count > 1)
                    {
                        evaluators[index] = ExprMethodAggUtil.GetMultiNodeEvaluator(
                            aggregateNode.ChildNodes, typesPerStream.Length > 1, typesPerStream);
                    }
                    else if (aggregateNode.ChildNodes.Count > 0)
                    {
                        // Use the evaluation node under the aggregation node to obtain the aggregation value
                        evaluators[index] = aggregateNode.ChildNodes[0].ExprEvaluator;
                    }
                    else
                    {
                        // For aggregation that doesn't evaluate any particular sub-expression, return null on evaluation
                        evaluators[index] = new ProxyExprEvaluator
                        {
                            ProcEvaluate = eventParams => null,
                            ProcReturnType = () => null
                        };
                    }

                    aggregators[index] = aggregateNode.Factory;
                    index++;
                }
            }

            // Assign a column number to each aggregation node. The regular aggregation goes first followed by access-aggregation.
            int columnNumber = 0;
            var allExpressions = new List<AggregationServiceAggExpressionDesc>();
            foreach (var equivalencyPerStream in equivalencyListPerStream)
            {
                foreach (AggregationServiceAggExpressionDesc entry in equivalencyPerStream.Value)
                {
                    entry.ColumnNum = columnNumber++;
                }
                allExpressions.AddAll(equivalencyPerStream.Value);
            }

            var factory = new AggregationServiceMatchRecognizeFactoryImpl(
                numStreams, aggregatorsPerStream, evaluatorsPerStream);
            return new AggregationServiceMatchRecognizeFactoryDesc(factory, allExpressions);
        }
Exemplo n.º 59
0
        // Writes data into Excel tab containing compound and sample names.
        // Compound names must be in the sheet. Sample names are optional
        // and will be checked for and filled in if missing. Put sample names in sheet
        // if you want a particular order.
        //
        // The following are optional parameters and can be omitted if using info from options dictionary:
        // useOptions - default is true. If false, you must fill in the remaining parameters
        // startRow and startCol - where to start writing data
        // sampleLoc and compoundLoc - where the sample and compound names are located
        public static ExcelPackage WriteIntoTemplate(
            OrderedDictionary dataMap, ExcelPackage excelPkg, Dictionary <string, string> options, string templateTab,
            bool useOptions = true, int startRow = 2, int startCol = 2, int sampleLoc = 1, int compoundLoc = 1)
        {
            var worksheet = excelPkg.Workbook.Worksheets[templateTab];
            int numSamples, numCompounds, endRow, endCol;

            // Check if map contains sample names, prevents index error later
            List <string> samplesKeys;

            try
            {
                samplesKeys = ((OrderedDictionary)dataMap[0]).Keys.Cast <string>().ToList();
            }
            catch
            {
                MessageBox.Show($"No data to write in {templateTab}. " +
                                $"Check if template and samples are in rows or columns.");
                return(excelPkg);
            }

            // Get row and col to start writing
            if (useOptions)
            {
                (startRow, startCol) = ExcelUtils.GetRowCol(options["StartInCell"]);

                // Convert column name to number
                sampleLoc = int.TryParse(options["SampleLoc"], out var sampleLocNum)
                    ? sampleLocNum
                    : ExcelUtils.ColumnNameToNumber(options["SampleLoc"]);
                compoundLoc = int.TryParse(options["CompoundLoc"], out var compoundLocNum)
                    ? compoundLocNum
                    : ExcelUtils.ColumnNameToNumber(options["CompoundLoc"]);
            }

            if (options["SamplesOut"] == "rows")
            {
                // Fill in sample names if not in template
                var name = worksheet.Cells[startRow, sampleLoc].Value?.ToString();
                if (name is null || name.Length < 1)
                {
                    var r = startRow;
                    foreach (string sampleName in samplesKeys)
                    {
                        worksheet.Cells[r++, sampleLoc].Value = sampleName;
                    }
                }

                // Get approximate bounds, samples in rows (in column sampleLoc)
                numSamples   = ExcelUtils.RowsInColumn(worksheet, sampleLoc);
                numCompounds = ExcelUtils.ColumnsInRow(worksheet, compoundLoc);
                endRow       = numSamples + startRow;
                endCol       = numCompounds + startCol;

                // Write each compound data (column)
                for (int col = startCol; col <= endCol; ++col)
                {
                    for (int row = startRow; row <= endRow; ++row)
                    {
                        // Write peak area corresponding to compound and sample name
                        // Compound in row compoundLoc
                        var compound = worksheet.Cells[compoundLoc, col]?.Value?.ToString();
                        if (compound != null && dataMap.Contains(compound))
                        {
                            // Read sample name from sample column, lookup data for sample in map
                            var sampleName = worksheet.Cells[row, sampleLoc]?.Value?.ToString();
                            if (sampleName is null)
                            {
                                continue;
                            }
                            var data = ((OrderedDictionary)dataMap[compound])[sampleName]?.ToString();

                            // Write data to cell, as a number if possible
                            if (double.TryParse(data, out double dataNum))
                            {
                                worksheet.Cells[row, col].Value = dataNum;
                            }
                            else
                            {
                                worksheet.Cells[row, col].Value = data;
                            }
                        }
                    }
                }
            }
            else
            {
                // Fill in sample names if not in template
                var name = worksheet.Cells[sampleLoc, startCol].Value?.ToString();
                if (name is null || name.Length < 1)
                {
                    var c = startCol;
                    foreach (string sampleName in samplesKeys)
                    {
                        worksheet.Cells[sampleLoc, c++].Value = sampleName;
                    }
                }

                // Get approximate bounds, samples in columns (in row sampleLoc)
                numCompounds = ExcelUtils.RowsInColumn(worksheet, compoundLoc);
                numSamples   = ExcelUtils.ColumnsInRow(worksheet, sampleLoc);
                endRow       = numCompounds + startRow;
                endCol       = numSamples + startCol;

                // Write each compound data (row)
                for (int row = startRow; row <= endRow; ++row)
                {
                    for (int col = startCol; col <= endCol; ++col)
                    {
                        // Write peak area corresponding to compound and sample name
                        // Compounds in column compoundLoc
                        var compound = worksheet.Cells[row, compoundLoc]?.Value?.ToString();
                        if (compound != null && dataMap.Contains(compound))
                        {
                            // Read sample name from row, lookup data for sample in map
                            var sampleName = worksheet.Cells[sampleLoc, col]?.Value?.ToString();
                            if (sampleName is null)
                            {
                                continue;
                            }
                            var data = ((OrderedDictionary)dataMap[compound])[sampleName]?.ToString();

                            // Write data to cell, as a number if possible
                            if (double.TryParse(data, out double dataNum))
                            {
                                worksheet.Cells[row, col].Value = dataNum;
                            }
                            else
                            {
                                worksheet.Cells[row, col].Value = data;
                            }
                        }
                    }
                }
            }

            worksheet.Cells[startRow, startCol, endRow, endCol].Style.Numberformat.Format = "0";
            worksheet.Cells[startRow, startCol, endRow, endCol].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

            // TODO - check that save as new name works
            //excelPkg.SaveAs(new FileInfo(options["OutputFolder"] + "\\" + options["OutputFileName"]));
            excelPkg.Save();
            return(excelPkg);
        }
Exemplo n.º 60
0
        public void Write(Stream stream)
        {
            using (GrnBinaryWriter writer = new GrnBinaryWriter(stream))
            {
                this.WriteHeader(writer);

                GrnMainNode mainNode = new GrnMainNode();
                mainNode.NumTotalChildNodes = 3;
                this.CreateVerFrameDir(mainNode);

                GrnSectionNode staFrameDir = new GrnSectionNode(mainNode, GrnNodeType.StandardFrameDirectory);
                staFrameDir.Offset = 440;
                mainNode.AppendChild(staFrameDir);

                // 0StringTable
                OrderedDictionary  stringMap    = this.CreateStringMap();
                GrnStringTableNode strTableNode = new GrnStringTableNode(staFrameDir);
                strTableNode.Strings = stringMap.Keys.Cast <string>().ToList();
                staFrameDir.AppendChild(strTableNode);

                // 1DataExtension
                GrnNode dataExtSecNode = new GrnNode(staFrameDir, GrnNodeType.DataExtensionSection);
                staFrameDir.AppendChild(dataExtSecNode);
                this.WriteDataExtensions(dataExtSecNode, stringMap);

                // 2VectorChannel
                GrnNode vecChanSecNode = new GrnNode(staFrameDir, GrnNodeType.VectorChannelSection);
                staFrameDir.AppendChild(vecChanSecNode);

                // 3TransformChannel
                GrnNode traChanSecNode = new GrnNode(staFrameDir, GrnNodeType.TransformChannelSection);
                staFrameDir.AppendChild(traChanSecNode);
                foreach (GrnBone bone in this.Bones)
                {
                    GrnNode traChanNode = new GrnNode(traChanSecNode, GrnNodeType.TransformChannel);
                    traChanSecNode.AppendChild(traChanNode);

                    GrnDataExtensionReferenceNode refNode = new GrnDataExtensionReferenceNode(traChanNode);
                    refNode.DataExtensionIndex = bone.DataExtensionIndex + 1;
                    traChanNode.AppendChild(refNode);
                }

                // 4Mesh
                GrnNode meshSecNode = new GrnNode(staFrameDir, GrnNodeType.MeshSection);
                staFrameDir.AppendChild(meshSecNode);
                foreach (GrnMesh mesh in this.Meshes)
                {
                    mesh.Write(meshSecNode);
                }

                // 5Skeleton
                GrnNode skelSecNode = new GrnNode(staFrameDir, GrnNodeType.SkeletonSection);
                staFrameDir.AppendChild(skelSecNode);
                GrnNode skelNode = new GrnNode(skelSecNode, GrnNodeType.Skeleton);
                skelSecNode.AppendChild(skelNode);
                GrnNode boneSecNode = new GrnNode(skelNode, GrnNodeType.BoneSection);
                skelNode.AppendChild(boneSecNode);
                foreach (GrnBone bone in this.Bones)
                {
                    bone.Write(boneSecNode);
                }

                // 6Texture
                GrnNode texSecNode = new GrnNode(staFrameDir, GrnNodeType.TextureSection);
                staFrameDir.AppendChild(texSecNode);
                foreach (GrnTexture tex in this.Textures)
                {
                    tex.Write(texSecNode);
                }

                // 7Material
                GrnNode matSecNode = new GrnNode(staFrameDir, GrnNodeType.MaterialSection);
                staFrameDir.AppendChild(matSecNode);
                foreach (GrnMaterial mat in this.Materials)
                {
                    mat.Write(matSecNode);
                }

                // 8Form
                GrnNode formSecNode = new GrnNode(staFrameDir, GrnNodeType.FormSection);
                staFrameDir.AppendChild(formSecNode);
                this.WriteForm(formSecNode);

                // 9Model
                GrnNode modelSecNode = new GrnNode(staFrameDir, GrnNodeType.ModelSection);
                staFrameDir.AppendChild(modelSecNode);
                GrnNode modelNode = new GrnNode(modelSecNode, GrnNodeType.Model);
                modelNode.Data = new byte[] { 0x01, 0x00, 0x00, 0x00 };
                modelSecNode.AppendChild(modelNode);
                GrnNode rendPassSecNode = new GrnNode(modelNode, GrnNodeType.RenderPassSection);
                modelNode.AppendChild(rendPassSecNode);
                for (int i = 0; i < this.Meshes.Count; ++i)
                {
                    this.Meshes[i].WriteRenderPass(rendPassSecNode, i);
                }

                // 10Animation
                GrnNode animSecNode = new GrnNode(staFrameDir, GrnNodeType.AnimationSection);
                staFrameDir.AppendChild(animSecNode);
                GrnNode animNode = new GrnNode(animSecNode, GrnNodeType.Animation);
                animSecNode.AppendChild(animNode);
                GrnNode animVecTraSecNode = new GrnNode(animNode, GrnNodeType.AnimationVectorTrackSection);
                animNode.AppendChild(animVecTraSecNode);
                GrnNode animTraTraSecNode = new GrnNode(animNode, GrnNodeType.AnimationTransformTrackSection);
                animNode.AppendChild(animTraTraSecNode);
                for (int i = 0; i < this.Animation.BoneTracks.Count; ++i)
                {
                    this.Animation.BoneTracks[i].Write(animTraTraSecNode, i);
                }

                // 11NullTerminator
                GrnNode nullTermNode = new GrnNode(staFrameDir, GrnNodeType.NullTerminator);
                staFrameDir.AppendChild(nullTermNode);

                GrnSectionNode nullFrameDir = new GrnSectionNode(mainNode, GrnNodeType.NullFrameDirectory);
                mainNode.AppendChild(nullFrameDir);
                nullTermNode = new GrnNode(nullFrameDir, GrnNodeType.NullTerminator);
                nullFrameDir.AppendChild(nullTermNode);

                mainNode.Write(writer);
            }
        }