/// <summary>
        /// Get Spinned Sentences
        /// </summary>
        /// <param name="RawText">Format: (I/we/us) (am/are) planning to go (market/outing)...</param>
        /// <param name="RawText">Format: "|" or "/"...</param>
        /// <returns></returns>
        public static List<string> spinSmallText(string RawText, char separator)
        {
            #region Using Dictionary
            /// <summary>
            /// Hashtable that stores (DataInsideBraces) as Key and DataInsideBracesArray as Value
            /// </summary>
            //Hashtable commentsHashTable = new Hashtable();
            Dictionary<Match, string[]> commentsHashTable = new Dictionary<Match, string[]>();

            ///This is final possible cominations of comments
            List<string> listModComments = new List<string>();

            ///Put braces data in list of string array
            List<string[]> listDataInsideBracesArray = new List<string[]>();

            ///This Regex will fetch data within braces and put it in list of string array
            var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
            foreach (Match Data in regex.Matches(RawText))
            {
                string data = Data.Value.Replace("(", "").Replace(")", "");
                string[] DataInsideBracesArray = data.Split(separator);//data.Split('/');
                commentsHashTable.Add(Data, DataInsideBracesArray);
                listDataInsideBracesArray.Add(DataInsideBracesArray);
            }

            string ModifiedComment = RawText;

            IDictionaryEnumerator en = commentsHashTable.GetEnumerator();

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

            listModifiedComment.Add(ModifiedComment);

            //en.Reset();

            string ModifiedComment1 = ModifiedComment;

            #region Assigning Values and adding in List
            foreach (string[] item in listDataInsideBracesArray)
            {
                en.MoveNext();
                foreach (string modItem in listModifiedComment)
                {
                    foreach (string innerItem in item)
                    {
                        string ModComment = modItem.Replace(en.Key.ToString(), innerItem);
                        listModComments.Add(ModComment);
                    }
                }
                listModifiedComment.AddRange(listModComments);
                //string ModComment = ModifiedComment1.Replace(en.Key, item
            }
            #endregion

            List<string> listRequiredComments = listModifiedComment.FindAll(s => !s.Contains("("));

            //listComments.AddRange(listRequiredComments);
            return listRequiredComments;
            #endregion
        }
        public void DumpElements()
        {
            #if DEBUG
            Dictionary<IntPtr, int> list = new Dictionary<IntPtr,int>();

            IDictionaryEnumerator en = Elements.GetEnumerator();

            while (en.MoveNext())
            {
                if (!list.ContainsKey((IntPtr)en.Key))
                    {
                    list.Add((IntPtr)en.Key, 1);
                } else {
                    list[(IntPtr)en.Key] ++;
                }
            }
            en = list.GetEnumerator();

            long memused = 0;

            memused = GC.GetTotalMemory(true);

            Console.WriteLine("Begin dump of the Elements:\n");
            while (en.MoveNext())
            {
                Console.WriteLine("\t"+en.Key+"\tdup\t"+en.Value+"\ttype:\t"+Elements[(IntPtr)en.Key].ToString());
            }
            Console.WriteLine("=========================================================");
            Console.WriteLine("\tTotal memory used: "+memused+" Kb");
            #endif // Debug
        }
        public IDictionaryEnumerator GetEnumerator()
        {

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

            foreach (XmlNode item in this.Document.GetElementsByTagName("add"))
            {

                set.Add(item.Attributes["name"].Value, item.Attributes["value"].Value);

            }

            return set.GetEnumerator();

        }
        public virtual void WriteMountCollection( Dictionary<Serial, BaseCreature> dictionary, GenericWriter writer )
        {
            IDictionaryEnumerator myEnum = dictionary.GetEnumerator();

            int count = dictionary.Count;

            writer.Write( count );
            while( myEnum.MoveNext() )
            {
                Serial serial = ( Serial )myEnum.Key;
                Mobile m = (Mobile)myEnum.Value;

                writer.Write( serial );
                writer.Write( m );
            }
        }
Exemple #5
0
            public void MergesMetadata()
            {
                // Given
                IExecutionContext context = Substitute.For<IExecutionContext>();
                context
                    .GetDocument(Arg.Any<IDocument>(), Arg.Any<string>(), Arg.Any<IEnumerable<KeyValuePair<string, object>>>())
                    .Returns(x =>
                    {
                        Dictionary<string, object> metadata = new Dictionary<string, object>();
                        foreach (KeyValuePair<string, object> kvp in x.ArgAt<IDocument>(0))
                        {
                            metadata[kvp.Key] = kvp.Value;
                        }
                        foreach (KeyValuePair<string, object> kvp in x.ArgAt<IEnumerable<KeyValuePair<string, object>>>(2))
                        {
                            metadata[kvp.Key] = kvp.Value;
                        }
                        IDocument result = Substitute.For<IDocument>();
                        result.GetEnumerator().Returns(metadata.GetEnumerator());
                        return result;
                    });
                IDocument a = Substitute.For<IDocument>();
                a.GetEnumerator().Returns(new Dictionary<string, object>
                {
                    { "a", 1 },
                    { "b", 2 }
                }.GetEnumerator());
                IDocument b = Substitute.For<IDocument>();
                b.GetEnumerator().Returns(new Dictionary<string, object>
                {
                    { "b", 3 },
                    { "c", 4 }
                }.GetEnumerator());
                Combine combine = new Combine();

                // When
                List<IDocument> results = combine.Execute(new[] { a, b }, context).ToList();  // Make sure to materialize the result list

                // Then
                CollectionAssert.AreEquivalent(new Dictionary<string, object>
                {
                    { "a", 1 },
                    { "b", 3 },
                    { "c", 4 }
                }, Iterate(results.First().GetEnumerator()));
            }
Exemple #6
0
        private void Write(string fp, Dictionary<XmlTrack, List<string>> dic)
        {
            if (dic.Count > 0)
            {
                using (StreamWriter sw = new StreamWriter(fp, false))
                {
                    IEnumerator i = dic.GetEnumerator();
                    KeyValuePair<XmlTrack, List<string>> kvp = new KeyValuePair<XmlTrack, List<string>>();

                    while (i.MoveNext())
                    {
                        kvp = (KeyValuePair<XmlTrack, List<string>>)i.Current;
                        XmlTrack track = kvp.Key;
                        List<string> missingTags = kvp.Value;
                        string errors = string.Join("; ", missingTags.ToArray());
                        sw.WriteLine(track.Location + " --> " + errors);
                    }
                }
            }
        }
        public static string Encode(Dictionary<string, string> dictionary )
        {
            var @value = "";
            var e = dictionary.GetEnumerator();
            bool hasFirst = e.MoveNext();
            if (hasFirst)
            {
                var tb = new StringBuilder();
// ReSharper disable PossibleNullReferenceException
                tb.Append(e.Current.Key).Append("=").Append(e.Current.Value);
// ReSharper restore PossibleNullReferenceException
                while (e.MoveNext())
                {
// ReSharper disable PossibleNullReferenceException
                    tb.Append("; ").Append(e.Current.Key).Append("=").Append(e.Current.Value);
// ReSharper restore PossibleNullReferenceException
                }
                @value = tb.ToString();
            }
            return @value;
        }
 /// <summary>
 /// Tries to find an implemented <see cref="IDictionary{TKey,TValue}"/> or <see cref="IDictionary{TKey,TValue}"/>
 /// interface and returns it. If the resulting dictionary is a generic type,
 /// the key type (type parameter TKey) and the value type (type parameter TValue) of this dictionary
 /// will be returned too.
 /// </summary>
 /// <param name="type">The type to examine.</param>
 /// <param name="resultDictionaryType">Returns the dictionary type found. If an implemented
 /// generic dictionary type was found, this type will be returned. Else, if the standard
 /// dictionary type is implemented, this type will be returned. If no dictionary type is
 /// implemented, this value will be <c>null</c>.</param>
 /// <param name="resultKeyType">Returns the key type (type parameter TKey) of the implemented
 /// generic type, if any.</param>
 /// <param name="resultValueType">Returns the value type (type parameter TValue) of the implemented
 /// generic type, if any.</param>
 public static void FindImplementedDictionaryType(Type type,
   out Type resultDictionaryType, out Type resultKeyType, out Type resultValueType)
 {
   resultDictionaryType = null;
   resultKeyType = null;
   resultValueType = null;
   // First check generic interfaces
   IDictionary<Type, KeyValuePair<Type, Type>> foundGeneric = new Dictionary<Type, KeyValuePair<Type, Type>>();
   foreach (Type interfaceType in type.GetInterfaces())
   {
     Type[] genericArguments;
     if (interfaceType.IsGenericType && (genericArguments = interfaceType.GetGenericArguments()).Length == 2)
     {
       Type keyType = genericArguments[0];
       Type valueType = genericArguments[1];
       Type collectionType = typeof(IDictionary<,>).MakeGenericType(keyType, valueType);
       if (collectionType.IsAssignableFrom(type))
         if (!foundGeneric.ContainsKey(collectionType))
           foundGeneric.Add(collectionType, new KeyValuePair<Type, Type>(keyType, valueType));
     }
   }
   IEnumerator<KeyValuePair<Type, KeyValuePair<Type, Type>>> ge = foundGeneric.GetEnumerator();
   if (ge.MoveNext())
   {
     resultDictionaryType = ge.Current.Key;
     resultKeyType = ge.Current.Value.Key;
     resultValueType = ge.Current.Value.Value;
     return;
   }
   // Fallback: Check non-generic type
   if (typeof(IDictionary).IsAssignableFrom(type))
   {
     resultDictionaryType = typeof(IDictionary);
     return;
   }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null)
                Response.Redirect("../login.aspx");

            if (!IsPostBack)
            {
                // build table of service admin grants
                servAdminGrants = getServiceAdminGrants();
                if (servAdminGrants != null)
                {
                    // load the PA's that this user is an administer of
                    Dictionary<int, List<Grant>>.Enumerator paEnum = servAdminGrants.GetEnumerator();
                    paDropDownList.Items.Add(new ListItem("--- Select Process Agent ---"));

                    while (paEnum.MoveNext())
                    {
                        KeyValuePair<int, List<Grant>> entry = paEnum.Current;
                        IntTag tag = ticketIssuer.GetProcessAgentTagWithType((int)entry.Key);
                        if (tag != null)
                        {
                            string agentName = tag.tag;
                            List<Grant> grants = entry.Value;
                            StringBuilder buf = new StringBuilder();
                            int count = 0;
                            foreach (Grant g in grants)
                            {
                                if (count > 0)
                                {
                                    buf.Append(",");
                                }
                                buf.Append(g.grantID);
                                count++;
                            }
                            paDropDownList.Items.Add(new ListItem(agentName, buf.ToString()));
                        }
                    }
                }

            }
        }
Exemple #10
0
		public void ResetShimEnumerator ()
		{
			IDictionary test = new Dictionary<string, string> ();
			test.Add ("monkey", "singe");
			test.Add ("singe", "mono");
			test.Add ("mono", "monkey");

			IEnumerator enumerator = test.GetEnumerator ();

			Assert.IsTrue (enumerator.MoveNext ());
			Assert.IsTrue (enumerator.MoveNext ());

			enumerator.Reset ();

			Assert.IsTrue (enumerator.MoveNext ());
			Assert.IsTrue (enumerator.MoveNext ());
			Assert.IsTrue (enumerator.MoveNext ());
			Assert.IsFalse (enumerator.MoveNext ());
		}
Exemple #11
0
		// based on #491858, #517415
		public void ValueEnumerator_Current ()
		{
			var e1 = new Dictionary<int,int>.ValueCollection.Enumerator ();
			Assert.IsFalse (Throws (delegate { var x = e1.Current; }));

			var d = new Dictionary<int,int> ().Values;
			var e2 = d.GetEnumerator ();
			Assert.IsFalse (Throws (delegate { var x = e2.Current; }));
			e2.MoveNext ();
			Assert.IsFalse (Throws (delegate { var x = e2.Current; }));
			e2.Dispose ();
			Assert.IsFalse (Throws (delegate { var x = e2.Current; }));

			var e3 = ((IEnumerable<int>) d).GetEnumerator ();
			Assert.IsFalse (Throws (delegate { var x = e3.Current; }));
			e3.MoveNext ();
			Assert.IsFalse (Throws (delegate { var x = e3.Current; }));
			e3.Dispose ();
			Assert.IsFalse (Throws (delegate { var x = e3.Current; }));

			var e4 = ((IEnumerable) d).GetEnumerator ();
			Assert.IsTrue (Throws (delegate { var x = e4.Current; }));
			e4.MoveNext ();
			Assert.IsTrue (Throws (delegate { var x = e4.Current; }));
			((IDisposable) e4).Dispose ();
			Assert.IsTrue (Throws (delegate { var x = e4.Current; }));
		}
        private String generateOrderTable(Dictionary<String, Double> config)
        {
            String tableStr = "";
            int nextId = 1;
            IDictionaryEnumerator ienum = config.GetEnumerator();
            while (ienum.MoveNext())
            {
                String key = (String)ienum.Key;
                Double val = (Double)ienum.Value;

                if (tableStr.Length > 0)
                {
                    tableStr += ", ";
                    tableStr += Environment.NewLine;
                }
                else
                {
                    tableStr += "{";
                    tableStr += Environment.NewLine;
                }

                tableStr += "[";
                if (key.GetType() == typeof(Double))
                {
                    tableStr += key;
                }
                else
                {
                    tableStr += "\"" + key + "\"";
                }
                tableStr += "] = ";

                if (val > 0.0)
                {
                    //append next id
                    tableStr += nextId;
                }
                else
                {
                    //its disabled just append 0
                    tableStr += "0";
                }

                nextId++;
            }


            if (tableStr.Length > 0)
            {
                tableStr += Environment.NewLine;
                tableStr += "}";
            }

            return tableStr;
        }
 protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator()
 {
     Dictionary<string, object> h = new Dictionary<string, object>();
     if (!this.IsDisposed)
     {
         foreach (MemoryCacheStore store in this._stores)
         {
             store.CopyTo(h);
         }
     }
     return h.GetEnumerator();
 }
 public static IntPtr CFDictionaryFromManagedDictionary(Dictionary<object, object> sourceDict)
 {
     if (sourceDict == null)
     {
         IntPtr ptr = IntPtr.Zero;
         return ptr;
     }
     IntPtr zero = IntPtr.Zero;
     try
     {
         IntPtr ptr1 = IntPtr.Zero;
         Dictionary<object, object>.Enumerator enumerator;
         zero = CFDictionaryCreateMutable(kCFAllocatorDefault, sourceDict.Count, ref ptr1, ref ptr1);
         try
         {
             enumerator = sourceDict.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 KeyValuePair<object, object> current = enumerator.Current;
                 IntPtr ptr3 = CFTypeFromManagedType(RuntimeHelpers.GetObjectValue(current.Key));
                 IntPtr ptr4 = CFTypeFromManagedType(RuntimeHelpers.GetObjectValue(current.Value));
                 if (ptr3 != IntPtr.Zero && ptr4 != IntPtr.Zero) CFDictionaryAddValue(zero, ptr3, ptr4);
             }
         }
         finally
         {
             //enumerator.Dispose();
         }
     }
     catch (Exception exception1)
     {
         ProjectData.SetProjectError(exception1);
         ProjectData.ClearProjectError();
     }
     return zero;
 }
Exemple #15
0
 private void WriteResults(bool csvOutput, Dictionary<String, String> pdfInfo)
 {
     if (pdfInfo.Count > 0)
     {
         IDictionaryEnumerator infoEnumerator = pdfInfo.GetEnumerator();
         while (infoEnumerator.MoveNext())
         {
             switch (csvOutput)
             {
                 case (true):
                     System.Console.WriteLine(String.Format(reportMessageCSVOutput, infoEnumerator.Key, infoEnumerator.Value));
                     break;
                 default:
                     System.Console.WriteLine(String.Format(reportMessageStandardOutput, infoEnumerator.Key, infoEnumerator.Value));
                     break;
             }
         }
     }
     else
     {
         System.Console.WriteLine(Environment.NewLine + reportNoPdfInfo);
     }
 }
        /// <summary>
        /// Analyzes the tag of the htmlElement and infers its associated formatted properties.
        /// After that parses style attribute and adds all inline css styles.
        /// The resulting style attributes are collected in output parameter localProperties.
        /// </summary>
        /// <param name="htmlElement">
        /// </param>
        /// <param name="inheritedProperties">
        /// set of properties inherited from ancestor elements. Currently not used in the code. Reserved for the future development.
        /// </param>
        /// <param name="localProperties">
        /// returns all formatting properties defined by this element - implied by its tag, its attributes, or its css inline style
        /// </param>
        /// <param name="stylesheet"></param>
        /// <param name="sourceContext"></param>
        /// <returns>
        /// returns a combination of previous context with local set of properties.
        /// This value is not used in the current code - inntended for the future development.
        /// </returns>
        private static IDictionary GetElementProperties(XmlElement htmlElement, IDictionary inheritedProperties, out IDictionary localProperties, CssStylesheet stylesheet, List<XmlElement> sourceContext)
        {
            // Start with context formatting properties
            IDictionary currentProperties = new Dictionary<string,string>();
            IDictionaryEnumerator propertyEnumerator = inheritedProperties.GetEnumerator();
            while (propertyEnumerator.MoveNext())
            {
                currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value;
            }

            // Identify element name
            string elementName = htmlElement.LocalName.ToLower();
            string elementNamespace = htmlElement.NamespaceUri.ToString();

            // update current formatting properties depending on element tag

            localProperties = new Dictionary<string,string>();
            switch (elementName)
            {
                // Character formatting
                case "i":
                case "italic":
                case "em":
                    localProperties["font-style"] = "italic";
                    break;
                case "b":
                case "bold":
                case "strong":
                case "dfn":
                    localProperties["font-weight"] = "bold";
                    break;
                case "u":
                case "underline":
                    localProperties["text-decoration-underline"] = "true";
                    break;
                case "font":
                    string attributeValue = GetAttribute(htmlElement, "face");
                    if (attributeValue != null)
                    {
                        localProperties["font-family"] = attributeValue;
                    }
                    attributeValue = GetAttribute(htmlElement, "size");
                    if (attributeValue != null)
                    {
                        double fontSize = double.Parse(attributeValue) * (12.0 / 3.0);
                        if (fontSize < 1.0)
                        {
                            fontSize = 1.0;
                        }
                        else if (fontSize > 1000.0)
                        {
                            fontSize = 1000.0;
                        }
                        localProperties["font-size"] = fontSize.ToString();
                    }
                    attributeValue = GetAttribute(htmlElement, "color");
                    if (attributeValue != null)
                    {
                        localProperties["color"] = attributeValue;
                    }
                    break;
                case "samp":
                    localProperties["font-family"] = "Courier New"; // code sample
                    localProperties["font-size"] = Xaml_FontSize_XXSmall;
                    localProperties["text-align"] = "Left";
                    break;
                case "sub":
                    break;
                case "sup":
                    break;

                // Hyperlinks
                case "a": // href, hreflang, urn, methods, rel, rev, title
                    //  Set default hyperlink properties
                    break;
                case "acronym":
                    break;

                // Paragraph formatting:
                case "p":
                    //  Set default paragraph properties
                    break;
                case "div":
                    //  Set default div properties
                    break;
                case "pre":
                    localProperties["font-family"] = "Courier New"; // renders text in a fixed-width font
                    localProperties["font-size"] = Xaml_FontSize_XXSmall;
                    localProperties["text-align"] = "Left";
                    break;
                case "blockquote":
                    localProperties["margin-left"] = "16";
                    break;

                case "h1":
                    localProperties["font-size"] = Xaml_FontSize_XXLarge;
                    break;
                case "h2":
                    localProperties["font-size"] = Xaml_FontSize_XLarge;
                    break;
                case "h3":
                    localProperties["font-size"] = Xaml_FontSize_Large;
                    break;
                case "h4":
                    localProperties["font-size"] = Xaml_FontSize_Medium;
                    break;
                case "h5":
                    localProperties["font-size"] = Xaml_FontSize_Small;
                    break;
                case "h6":
                    localProperties["font-size"] = Xaml_FontSize_XSmall;
                    break;
                // List properties
                case "ul":
                    localProperties["list-style-type"] = "disc";
                    break;
                case "ol":
                    localProperties["list-style-type"] = "decimal";
                    break;

                case "table":
                case "body":
                case "html":
                    break;
            }

            // Override html defaults by css attributes - from stylesheets and inline settings
            HtmlCssParser.GetElementPropertiesFromCssAttributes(htmlElement, elementName, stylesheet, localProperties, sourceContext);

            // Combine local properties with context to create new current properties
            propertyEnumerator = localProperties.GetEnumerator();
            while (propertyEnumerator.MoveNext())
            {
                currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value;
            }

            return currentProperties;
        }
		/// <summary>
		/// Remove used raw material from player inventory
		/// </summary>
		/// <param name="player"></param>
		/// <param name="recipe"></param>
		/// <returns></returns>
		public virtual bool RemoveUsedMaterials(GamePlayer player, DBCraftedItem recipe, IList<DBCraftedXItem> rawMaterials)
		{
			Dictionary<int, int?> dataSlots = new Dictionary<int, int?>(10);

			lock (player.Inventory)
			{
				foreach (DBCraftedXItem material in rawMaterials)
				{
					ItemTemplate template = GameServer.Database.FindObjectByKey<ItemTemplate>(material.IngredientId_nb);

					if (template == null)
					{
						player.Out.SendMessage("Can't find a material (" + material.IngredientId_nb + ") needed for this recipe.", eChatType.CT_System, eChatLoc.CL_SystemWindow);
						log.Error("RemoveUsedMaterials: Cannot find raw material ItemTemplate: " + material.IngredientId_nb + " needed for recipe: " + recipe.CraftedItemID);
						return false;
					}

					bool result = false;
					int count = material.Count;

					foreach (InventoryItem item in player.Inventory.GetItemRange(eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack))
					{
						if (item != null && item.Name == template.Name)
						{
							if (item.Count >= count)
							{
								if (item.Count == count)
								{
									dataSlots.Add(item.SlotPosition, null);
								}
								else
								{
									dataSlots.Add(item.SlotPosition, count);
								}
								result = true;
								break;
							}
							else
							{
								dataSlots.Add(item.SlotPosition, null);
								count -= item.Count;
							}
						}
					}
					if (result == false)
					{
						return false;
					}
				}
			}

			player.Inventory.BeginChanges();
			Dictionary<int, int?>.Enumerator enumerator = dataSlots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<int, int?> de = enumerator.Current;
				InventoryItem item = player.Inventory.GetItem((eInventorySlot)de.Key);
				if (item != null)
				{
					if (!de.Value.HasValue)
					{
						player.Inventory.RemoveItem(item);
					}
					else
					{
						player.Inventory.RemoveCountFromStack(item, de.Value.Value);
					}
					InventoryLogging.LogInventoryAction(player, "(craft)", eInventoryActionType.Craft, item.Template, de.Value.HasValue ? de.Value.Value : item.Count);
				}
			}
			player.Inventory.CommitChanges();

			return true;//all raw material removed and item created
		}
        //--- Methods ---
        public IDictionaryEnumerator GetEnumerator() {
            Dictionary<String, String> resources = new Dictionary<String, String>();
            if(System.IO.File.Exists(_filename)) {
                char[] brackets = new char[] { ']' };
                char[] equals = new char[] { '=' };
                string[] parts;

                // read the file into the hashtable
                using(StreamReader sr = new StreamReader(_filename, System.Text.Encoding.UTF8, true)) {
                    int count = 0;
                    string section = null;
                    for(string line = sr.ReadLine(); line != null; line = sr.ReadLine()) {
                        line = line.TrimStart();
                        ++count;

                        // check if line is a comment
                        if(line.StartsWith(";")) {
                            continue;
                        }

                        // check if line is a new section
                        if(line.StartsWith("[")) {
                            parts = line.Substring(1).Split(brackets, 2);
                            if(!string.IsNullOrEmpty(parts[0])) {
                                section = parts[0].Trim();
                            } else {
                                section = null;
                                _log.WarnMethodCall("missing namespace name", _filename, count);
                            }
                            continue;
                        }

                        // parse the line as key=value 
                        parts = line.Split(equals, 2);
                        if(parts.Length == 2) {
                            if(!string.IsNullOrEmpty(parts[0])) {
                                string key;

                                // check if a section is defined
                                if(section != null) {
                                    key = section + "." + parts[0];
                                } else {
                                    key = parts[0];
                                    _log.WarnMethodCall("missing namespace prefix", _filename, count, parts[0]);
                                }

                                // check if key already exists
                                if(resources.ContainsKey(key)) {
                                    _log.WarnMethodCall("duplicate key", _filename, count, key);
                                }
                                resources[key] = PhpUtil.ConvertToFormatString(parts[1]);
                            } else {
                                _log.WarnMethodCall("empty key", _filename, count, line);
                            }
                        } else if(line != string.Empty) {
                            _log.WarnMethodCall("bad key/value pair", _filename, count, line);
                        }
                    }
                    sr.Close();
                }
            }
            return resources.GetEnumerator();
        }
		/// <summary>
		/// Make the crafted item and add it to player's inventory
		/// </summary>
		/// <param name="player"></param>
		/// <param name="recipe"></param>
		/// <returns></returns>
		protected virtual void BuildCraftedItem(GamePlayer player, DBCraftedItem recipe, ItemTemplate itemToCraft)
		{
			Dictionary<int, int> changedSlots = new Dictionary<int, int>(5); // key : > 0 inventory ; < 0 ground || value: < 0 = new item count; > 0 = add to old

			lock (player.Inventory)
			{
				int count = itemToCraft.PackSize < 1 ? 1 : itemToCraft.PackSize;
				foreach (InventoryItem item in player.Inventory.GetItemRange(eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack))
				{
					if (item == null)
						continue;

					if (item.Id_nb.Equals(itemToCraft.Id_nb) == false)
						continue;

					if (item.Count >= itemToCraft.MaxCount)
						continue;

					int countFree = item.MaxCount - item.Count;
					if (count > countFree)
					{
						changedSlots.Add(item.SlotPosition, countFree); // existing item should be changed
						count -= countFree;
					}
					else
					{
						changedSlots.Add(item.SlotPosition, count); // existing item should be changed
						count = 0;
						break;
					}
				}

				if (count > 0) // Add new object
				{
					eInventorySlot firstEmptySlot = player.Inventory.FindFirstEmptySlot(eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack);
					if (firstEmptySlot == eInventorySlot.Invalid)
					{
						changedSlots.Add(-1, -count); // Create the item on the ground
					}
					else
					{
						changedSlots.Add((int)firstEmptySlot, -count); // Create the item in the free slot
					}
					count = 0;
				}

				InventoryItem newItem = null;

				player.Inventory.BeginChanges();

				Dictionary<int, int>.Enumerator enumerator = changedSlots.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<int, int> slot = enumerator.Current;
					int countToAdd = slot.Value;
					if (countToAdd > 0)	// Add to exiting item
					{
						newItem = player.Inventory.GetItem((eInventorySlot)slot.Key);
						if (newItem != null && player.Inventory.AddCountToStack(newItem, countToAdd))
						{
							InventoryLogging.LogInventoryAction("(craft)", player, eInventoryActionType.Other, newItem.Template, countToAdd);
							// count incremented, continue with next change
							continue;
						}
					}

					if (recipe.MakeTemplated)
					{
						string adjItem = itemToCraft.Id_nb+(GetQuality(player, recipe).ToString());
						ItemTemplate adjItemToCraft = GameServer.Database.FindObjectByKey<ItemTemplate>(adjItem);
						if (adjItemToCraft != null)
						{
							newItem = GameInventoryItem.Create<ItemTemplate>(adjItemToCraft);
						}
						else
						{
							newItem = GameInventoryItem.Create<ItemTemplate>(itemToCraft);
						}
					}
					else
					{
						ItemUnique unique = new ItemUnique(itemToCraft);
						GameServer.Database.AddObject(unique);
						newItem = GameInventoryItem.Create<ItemUnique>(unique);
						newItem.Quality = GetQuality(player, recipe);
					}

					newItem.IsCrafted = true;
					newItem.Creator = player.Name;
					newItem.Count = -countToAdd;

					if (slot.Key > 0)	// Create new item in the backpack
					{
						player.Inventory.AddItem((eInventorySlot)slot.Key, newItem);
						InventoryLogging.LogInventoryAction("(craft)", player, eInventoryActionType.Craft, newItem.Template, newItem.Count);
					}
					else					// Create new item on the ground
					{
						player.CreateItemOnTheGround(newItem);
						player.Out.SendDialogBox(eDialogCode.SimpleWarning, 0, 0, 0, 0, eDialogType.Ok, true, LanguageMgr.GetTranslation(player.Client.Account.Language, "AbstractCraftingSkill.BuildCraftedItem.BackpackFull", itemToCraft.Name));
					}
				}

				player.Inventory.CommitChanges();

				player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "AbstractCraftingSkill.BuildCraftedItem.Successfully", itemToCraft.Name, newItem.Quality), eChatType.CT_Missed, eChatLoc.CL_SystemWindow);

				if (recipe.MakeTemplated == false && newItem.Quality == 100)
				{
					player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "AbstractCraftingSkill.BuildCraftedItem.Masterpiece"), eChatType.CT_Important, eChatLoc.CL_SystemWindow);
					player.Out.SendPlaySound(eSoundType.Craft, 0x04);
				}
				else
				{
					player.Out.SendPlaySound(eSoundType.Craft, 0x03);
				}
			}
		}
Exemple #20
0
        /// <summary>
        /// Execute the MSBuild Task.
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            _modifiedFiles = new ArrayList();
            _deletedFiles = new ArrayList();

            // Parse local manifest to retrieve list of files and their hashes.
            string[] localManifest = File.ReadAllLines(_localManifestFile);
            Dictionary<string, string> localFiles = new Dictionary<string,string>();
            for (int i = 0; i < localManifest.Length; i++)
            {
                if (localManifest[i].StartsWith("Archive-Asset-Name: "))
                {
                    string assetName = localManifest[i].Substring(20);
                    i++;
                    if (localManifest[i].StartsWith("Archive-Asset-SHA-512-Digest: "))
                    {
                        string assetHash = localManifest[i].Substring(30);
                        localFiles.Add(assetName, assetHash);
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            // Do the same for the target manifest.
            string[] targetManifest = File.ReadAllLines(_targetManifestFile);
            Dictionary<string, string> targetFiles = new Dictionary<string,string>();
            for (int i = 0; i < targetManifest.Length; i++)
            {
                if (targetManifest[i].StartsWith("Archive-Asset-Name: "))
                {
                    string assetName = targetManifest[i].Substring(20);
                    i++;
                    if (targetManifest[i].StartsWith("Archive-Asset-SHA-512-Digest: "))
                    {
                        string assetHash = targetManifest[i].Substring(30);
                        targetFiles.Add(assetName, assetHash);
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            // Compare hashes and populate the lists of modified and deleted files.
            string[] targetFileMap = File.ReadAllLines(_targetFileMap);
            foreach (KeyValuePair<string, string> file in localFiles)
            {
                // For some reason this MANIFEST.bbr file appears in the manifest, even though
                // it doesn't actually exist anywhere...?  It doesn't seem to correspond to
                // MANIFEST.MF either.
                if (file.Key == "META-INF/MANIFEST.bbr")
                {
                    continue;
                }

                // If the target manifest doesn't contain the same key/value pair,
                // that means the local file has been either added or modified.
                if (!targetFiles.Contains(file))
                {
                    TaskItem item = new TaskItem(file.Key);
                    item.SetMetadata("SourcePath", getSourcePath(file.Key, targetFileMap));
                    _modifiedFiles.Add(item);
                }
            }

            IDictionaryEnumerator targetEnum = targetFiles.GetEnumerator();
            while (targetEnum.MoveNext())
            {
                // If the local manifest doesn't contain the same key,
                // that means the target file has been deleted from the project.
                if (!localFiles.ContainsKey((string)targetEnum.Key))
                {
                    TaskItem item = new TaskItem((string)targetEnum.Key);
                    _deletedFiles.Add(item);
                }
            }

            // For some reason the manifest file doesn't show up in the target file map
            // or the manifest itself, so we add it manually here and always upload it.
            TaskItem manifestItem = new TaskItem("META-INF/MANIFEST.MF");
            manifestItem.SetMetadata("SourcePath", "localManifest.mf");
            _modifiedFiles.Add(manifestItem);

            return true;
        }
        /// <summary>
        /// Get Spinned Sentences
        /// </summary>
        /// <param name="RawComment">Format: (I/we/us) (am/are) planning to go (market/outing)...</param>
        /// <returns></returns>
        public static List<string> GetSpinnedComments(string RawComment)
        {
            #region Using Hashtable
            ///// <summary>
            ///// Hashtable that stores (DataInsideBraces) as Key and DataInsideBracesArray as Value
            ///// </summary>
            //Hashtable commentsHashTable = new Hashtable();

            /////This is final possible cominations of comments
            //List<string> listModComments = new List<string>();

            /////Put braces data in list of string array
            //List<string[]> listDataInsideBracesArray = new List<string[]>();

            /////This Regex will fetch data within braces and put it in list of string array
            //var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
            //foreach (Match Data in regex.Matches(RawComment))
            //{
            //    string data = Data.Value.Replace("(", "").Replace(")", "");
            //    string[] DataInsideBracesArray = data.Split(separator);//data.Split('/');
            //    commentsHashTable.Add(Data, DataInsideBracesArray);
            //    listDataInsideBracesArray.Add(DataInsideBracesArray);
            //}

            //string ModifiedComment = RawComment;

            //IDictionaryEnumerator en = commentsHashTable.GetEnumerator();

            //List<string> listModifiedComment = new List<string>();

            //listModifiedComment.Add(ModifiedComment);

            ////en.Reset();

            //string ModifiedComment1 = ModifiedComment;

            //#region Assigning Values and adding in List
            //foreach (string[] item in listDataInsideBracesArray)
            //{
            //    en.MoveNext();
            //    foreach (string modItem in listModifiedComment)
            //    {
            //        foreach (string innerItem in item)
            //        {
            //            string ModComment = modItem.Replace(en.Key.ToString(), innerItem);
            //            listModComments.Add(ModComment);
            //        }
            //    }
            //    listModifiedComment.AddRange(listModComments);
            //    //string ModComment = ModifiedComment1.Replace(en.Key, item
            //}
            //#endregion

            //List<string> listRequiredComments = listModifiedComment.FindAll(s => !s.Contains("("));

            ////listComments.AddRange(listRequiredComments);
            //return listRequiredComments;
            #endregion

            #region Using Dictionary
            /// <summary>
            /// Hashtable that stores (DataInsideBraces) as Key and DataInsideBracesArray as Value
            /// </summary>
            //Hashtable commentsHashTable = new Hashtable();
            List<string> listRequiredComments = new List<string>();

            try
            {
                Dictionary<Match, string[]> commentsHashTable = new Dictionary<Match, string[]>();

                ///This is final possible cominations of comments
                List<string> listModComments = new List<string>();

                ///Put braces data in list of string array
                List<string[]> listDataInsideBracesArray = new List<string[]>();

                ///This Regex will fetch data within braces and put it in list of string array
                var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
                foreach (Match Data in regex.Matches(RawComment))
                {
                    string data = Data.Value.Replace("(", "").Replace(")", "");
                    string[] DataInsideBracesArray = data.Split('|');
                    commentsHashTable.Add(Data, DataInsideBracesArray);
                    listDataInsideBracesArray.Add(DataInsideBracesArray);

                    if (listDataInsideBracesArray.Count >= 5)
                    {
                        break;
                    }
                }

                string ModifiedComment = RawComment;

                IDictionaryEnumerator en = commentsHashTable.GetEnumerator();

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

                listModifiedComment.Add(ModifiedComment);

                //en.Reset();

                string ModifiedComment1 = ModifiedComment;

                #region Assigning Values and adding in List

                    foreach (string[] item in listDataInsideBracesArray)
                    {
                        en.MoveNext();

                        foreach (string modItem in listModifiedComment)
                        {
                            foreach (string innerItem in item)
                            {
                                string ModComment = modItem.Replace(en.Key.ToString(), innerItem);
                                listModComments.Add(ModComment);

                            }
                        }

                        try
                        {
                            listModifiedComment.AddRange(listModComments);
                            //if (listModifiedComment.Count > 5000)
                            //{
                            //    listRequiredComments = listModifiedComment.FindAll(s => !s.Contains("|"));
                            //    listRequiredComments = listModifiedComment.FindAll(s => !s.Contains("("));
                            //    return listModifiedComment;
                            //}
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.Message);
                        }
                        //string ModComment = ModifiedComment1.Replace(en.Key, item

                    }
                #endregion

                    listRequiredComments = listModifiedComment.FindAll(s => !s.Contains("("));
                    //listComments.AddRange(listRequiredComments);
            }
            catch
            {
            }
            return listRequiredComments;
            #endregion
        }
Exemple #22
0
		[Test] // bug #332534
		public void Dictionary_MoveNext ()
		{
			Dictionary<int,int> a = new Dictionary<int,int>();
			a.Add(3,1);
			a.Add(4,1);

			IEnumerator en = a.GetEnumerator();
			for (int i = 1; i < 10; i++)
				en.MoveNext();
		}
Exemple #23
0
		/// <summary>
		/// Called when craft time is finished
		/// </summary>
		/// <param name="timer"></param>
		/// <returns></returns>
		protected static int Proceed(RegionTimer timer)
		{
			GamePlayer player = timer.Properties.getProperty<GamePlayer>(AbstractCraftingSkill.PLAYER_CRAFTER, null);
			InventoryItem itemToSalvage = timer.Properties.getProperty<InventoryItem>(SALVAGED_ITEM, null);
			SalvageYield yield = timer.Properties.getProperty<SalvageYield>(SALVAGE_YIELD, null);
			int materialCount = yield.Count;

			if (player == null || itemToSalvage == null || yield == null || materialCount == 0)
			{
				player.Out.SendMessage("Error retrieving salvage data for this item!", eChatType.CT_Important, eChatLoc.CL_SystemWindow);
				log.Error("Salvage: There was a problem getting back salvage info from the craft timer.");
				return 0;
			}

			ItemTemplate rawMaterial = null;

			if (string.IsNullOrEmpty(yield.MaterialId_nb) == false)
			{
				rawMaterial = GameServer.Database.FindObjectByKey<ItemTemplate>(yield.MaterialId_nb);
			}

			if (rawMaterial == null)
			{
				player.Out.SendMessage("Error finding the raw material needed to salvage this item!", eChatType.CT_Important, eChatLoc.CL_SystemWindow);
				log.Error("Salvage: Error finding raw material " + yield.MaterialId_nb);
				return 0;
			}

			player.CraftTimer.Stop();
			player.Out.SendCloseTimerWindow();

			if (!player.Inventory.RemoveItem(itemToSalvage)) // clean the free of the item to salvage
			{
				player.Out.SendMessage("Error finding the item to salvage!", eChatType.CT_Important, eChatLoc.CL_SystemWindow);
				return 0;
			}

			InventoryLogging.LogInventoryAction(player, "(salvage)", eInventoryActionType.Craft, itemToSalvage.Template, itemToSalvage.Count);

			Dictionary<int, int> changedSlots = new Dictionary<int, int>(5); // value: < 0 = new item count; > 0 = add to old
			lock(player.Inventory)
			{
				int count = materialCount;
				foreach (InventoryItem item in player.Inventory.GetItemRange(eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack))
				{
					if (item == null) continue;
					if (item.Id_nb != rawMaterial.Id_nb) continue;
					if (item.Count >= item.MaxCount) continue;

					int countFree = item.MaxCount - item.Count;
					if (count > countFree)
					{
						changedSlots.Add(item.SlotPosition, countFree); // existing item should be changed
						count -= countFree;
					}
					else
					{
						changedSlots.Add(item.SlotPosition, count); // existing item should be changed
						count = 0;
						break;
					}
				}

				if(count > 0) // Add new object
				{
					eInventorySlot firstEmptySlot = player.Inventory.FindFirstEmptySlot(eInventorySlot.FirstBackpack, eInventorySlot.LastBackpack);
					changedSlots.Add((int)firstEmptySlot, -count); // Create the item in the free slot (always at least one)
					count = 0;
				}
				
			}

			InventoryItem newItem = null;

			player.Inventory.BeginChanges();
			Dictionary<int, int>.Enumerator enumerator = changedSlots.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<int, int> de = enumerator.Current;
				int countToAdd = de.Value;
				if(countToAdd > 0)	// Add to exiting item
				{
					newItem = player.Inventory.GetItem((eInventorySlot)de.Key);
					player.Inventory.AddCountToStack(newItem, countToAdd);
					InventoryLogging.LogInventoryAction("(salvage)", player, eInventoryActionType.Craft, newItem.Template, countToAdd);
				}
				else
				{
					newItem = GameInventoryItem.Create<ItemTemplate>(rawMaterial);
					newItem.Count = -countToAdd;
					player.Inventory.AddItem((eInventorySlot)de.Key, newItem);
					InventoryLogging.LogInventoryAction("(salvage)", player, eInventoryActionType.Craft, newItem.Template, newItem.Count);
				}
			}

			player.Inventory.CommitChanges();
			player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client.Account.Language, "Salvage.Proceed.GetBackMaterial", materialCount, rawMaterial.Name, itemToSalvage.Name), eChatType.CT_Important, eChatLoc.CL_SystemWindow);
			
			return 0;
		}
        /// <summary>
        /// This examines the specified parameters to resove the next action.
        /// This may only be called after a user is Authenticated.
        /// </summary>
        public IntTag ResolveAction(int clientID, int  userID, int groupID, DateTime start, long duration, bool autoStart)
        {
            int user_ID = -1;
                    int group_ID = -1;
                    int client_ID = -1;
                    string groupName;
                    IntTag result = new IntTag(-1,"Access Denied");
                    StringBuilder buf = new StringBuilder();
                    int[] userGroups = AdministrativeAPI.ListGroupIDsForUserRecursively(userID);
                    if (groupID > 0)
                    {
                            if (AdministrativeAPI.IsUserMember(groupID, userID))
                            {
                                group_ID = groupID;
                            }
                            else
                            {
                                // user is not a member of the group
                                result.tag = "The user is not a member of the requested group!";
                                return result;
                            }

                    }
                    else
                    {
                        result.tag = "You must specifiy a group name!";
                        return result;
                    }

                    // parameters are parsed, do we have enough info to launch
                    int[] clientGroupIDs = null;
                    int[] userGroupIDs = null;

                    // Try and resolve any unspecified parameters
                    if (client_ID <= 0 && group_ID <= 0)
                    {
                        userGroupIDs = AdministrativeAPI.ListGroupIDsForUserRecursively(user_ID);
                        Group[] groups = AdministrativeAPI.GetGroups(userGroupIDs);
                        Dictionary<int, int[]> clientMap = new Dictionary<int, int[]>();
                        foreach (Group g in groups)
                        {
                            if ((g.groupType.CompareTo(GroupType.REGULAR) == 0) )
                            {
                                int[] clientIDs = AdministrativeUtilities.GetGroupLabClients(g.groupID);
                                if (clientIDs != null & clientIDs.Length > 0)
                                {
                                    clientMap.Add(g.groupID, clientIDs);
                                }
                            }
                        }
                        if (clientMap.Count > 1) //more than one group with clients
                        {
                            //modifyUserSession(group_ID, client_ID);
                            buf.Append("myGroups.aspx");
                        }
                        else if (clientMap.Count == 1) // get the group with clients
                        {
                            Dictionary<int, int[]>.Enumerator en = clientMap.GetEnumerator();
                            int gid = -1;
                            int[] clients = null;
                            while (en.MoveNext())
                            {
                                gid = en.Current.Key;
                                clients = en.Current.Value;
                            }
                            if (AdministrativeAPI.IsUserMember(gid, user_ID))
                            {
                                group_ID = gid;
                                groupName = AdministrativeAPI.GetGroupName(gid);

                                if (clients == null || clients.Length > 1)
                                {
                                   // modifyUserSession(group_ID, client_ID);
                                    buf.Append("myLabs.aspx");
                                }
                                else
                                {
                                    client_ID = clients[0];
                                }
                            }
                        }
                    }

                    else if (client_ID > 0 && group_ID <= 0)
                    {
                        int gid = -1;
                        clientGroupIDs = AdministrativeUtilities.GetLabClientGroups(client_ID);
                        if (clientGroupIDs == null || clientGroupIDs.Length == 0)
                        {
                            //modifyUserSession(group_ID, client_ID);
                            buf.Append("myGroups.aspx");
                        }
                        else if (clientGroupIDs.Length == 1)
                        {
                            gid = clientGroupIDs[0];
                        }
                        else
                        {
                            userGroupIDs = AdministrativeAPI.ListParentGroupsForGroupRecursively(user_ID);
                            int count = 0;
                            foreach (int ci in clientGroupIDs)
                            {
                                foreach (int ui in userGroupIDs)
                                {
                                    if (ci == ui)
                                    {
                                        count++;
                                        gid = ui;
                                    }
                                }
                            }
                            if (count != 1)
                            {
                                gid = -1;
                            }
                        }
                        if (gid > 0 && AdministrativeAPI.IsUserMember(gid, user_ID))
                        {
                            group_ID = gid;

                        }
                        else
                        {
                            //modifyUserSession(group_ID, client_ID);
                        }
                    }
                    else if (client_ID <= 0 && group_ID > 0)
                    {
                        int[] clients = AdministrativeUtilities.GetGroupLabClients(group_ID);
                        if (clients == null || clients.Length != 1)
                        {
                            //modifyUserSession(group_ID, client_ID);
                            buf.Append("myLabs.aspx");
                        }
                        else
                        {
                            client_ID = clients[0];
                        }
                    }
                    if (user_ID > 0 && group_ID > 0 && client_ID > 0)
                    {
                        int gid = -1;
                        clientGroupIDs = AdministrativeUtilities.GetLabClientGroups(client_ID);
                        foreach (int g_id in clientGroupIDs)
                        {
                            if (g_id == group_ID)
                            {
                                gid = g_id;
                                break;
                            }
                        }
                        if (gid == -1)
                        {
                            result.tag = "The specified group does not have permission to to run the specified client!";
                            return result;
                        }
                        if (!AdministrativeAPI.IsUserMember(group_ID, user_ID))
                        {
                            result.tag = "The user does not have permission to to run the specified client!";
                            return result;
                        }

                        // is authorized ?

                        //modifyUserSession(group_ID, client_ID);
                        //launchLab(user_ID, group_ID, client_ID, duration, autoStart);
                        result.id = 1;
                        return result;

                    }
                    return result;
        }
Exemple #25
0
        private int SetGridData( GridControl GridControl, DataTable dtSource)
        {
            if (GridControl == null || dtSource == null)
            {
                return -1;
            }
            GridView gridView = GridControl.FocusedView as GridView;
            if (gridView == null)
            {
                return -1;
            }

            try
            {
                int colSourceIndex = 0;
                int dataRows = 0;
                string colDescName = string.Empty;
                string colSourceName = string.Empty;

                DataTable dtDesc = (GridControl.DataSource as System.Data.DataSet).Tables[GridControl.DataMember];
                dtDesc.Rows.Clear();

                Dictionary<int, string> ColMapping = new Dictionary<int, string>();
                if (efRB_col_seq.Checked)
                {
                    GridColumn gridColumn = null;// GridControl.SelectionColumn;
                    if (gridColumn != null)
                    {
                        gridColumn.Visible = false;
                        //gridColumn.VisibleIndex = -gridColumn.VisibleIndex;
                    }
                    for (colSourceIndex = 0; colSourceIndex < dtSource.Columns.Count; ++colSourceIndex)
                    {
                        ColMapping.Add(colSourceIndex, gridView.VisibleColumns[colSourceIndex].FieldName);
                    }
                    if (gridColumn != null)
                    {
                        gridColumn.Visible = true;
                    }
                }
                else if (efRB_col_cname.Checked)
                {
                    for (colSourceIndex = 0; colSourceIndex < dtSource.Columns.Count; ++colSourceIndex)
                    {
                        colDescName = string.Empty;
                        colSourceName = dtSource.Columns[colSourceIndex].Caption.Trim();
                        foreach (GridColumn gridcol in gridView.Columns)
                        {
                            colDescName = gridcol.Caption.Replace("<br>", "");
                            colDescName = colDescName.Replace(" ", "");
                            if (colDescName == colSourceName)
                            {
                                colDescName = gridcol.FieldName;
                                break;
                            }
                            colDescName = string.Empty;
                        }
                        if (colDescName != string.Empty)
                        {
                            ColMapping.Add(colSourceIndex, colDescName);
                        }
                    }
                }
                else if (efRB_col_ename.Checked)
                {
                    for (colSourceIndex = 0; colSourceIndex < dtSource.Columns.Count; ++colSourceIndex)
                    {
                        colDescName = string.Empty;
                        colSourceName = dtSource.Columns[colSourceIndex].ColumnName.Trim();
                        foreach (GridColumn gridcol in gridView.Columns)
                        {
                            if (gridcol.FieldName == colSourceName)
                            {
                                colDescName = gridcol.FieldName;
                            }
                        }
                        if (colDescName != string.Empty)
                        {
                            ColMapping.Add(colSourceIndex, colDescName);
                        }
                    }
                }

                for (dataRows = 0; dataRows < dtSource.Rows.Count; ++dataRows)
                {
                    DataRow drDesc = dtDesc.NewRow();
                    DataRow drSource = dtSource.Rows[dataRows];

                    Dictionary<int, string>.Enumerator enumerator =  ColMapping.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        //if (drDesc.Table.Columns[enumerator.Current.Value].DataType == typeof(Decimal))
                        //{
                        //    drDesc[enumerator.Current.Value] = Convert.ToDecimal(drSource[enumerator.Current.Key]);
                        //}
                        //else
                        //{
                            drDesc[enumerator.Current.Value] = drSource[enumerator.Current.Key];
                        //}
                    }
                    dtDesc.Rows.Add(drDesc);
                }
                GridControl.DataSource = null;
                GridControl.DataSource = dtDesc.DataSet;
                GridControl.DataMember = dtDesc.TableName;

                for (dataRows = 0; dataRows < dtDesc.Rows.Count; ++dataRows)
                {
                    //GridControl.SetSelectedColumnChecked(dataRows, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return -1;
            }
            return 0;
        }
        public static bool SaveToDisk(Dictionary<string, byte[]> data, string fulLSaveToPath)
        {
            // write the dang thing to disk:
            FileInfo fi = new FileInfo(fulLSaveToPath);

            // See if the map file exists and whether we should over write it
            if (!CreateFileOkay(fi))
            {
                return false;
            }

            BinaryWriter w = null;
            try
            {
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }

                w = new BinaryWriter(fi.OpenWrite());

                // iterate over the fields and write 'em out
                IDictionaryEnumerator list = data.GetEnumerator();
                while (list.MoveNext())
                {
                    w.Write(list.Key.ToString()); // Record ID
                    object odata = list.Value;

                    if (odata is byte[])
                    {
                        byte[] dat = (byte[])odata;
                        w.Write(dat.Length);
                        w.Write(dat);
                    }
                    if(odata is List<byte>)
                    {
                        List<byte> bData = (List<byte>)odata;
                        w.Write(bData.Count);
                        w.Write(bData.ToArray());
                    }
                    else if (odata is Stream)
                    {
                        Stream binData = (Stream)odata;
                        w.Write((int)binData.Length);
                        byte[] buffer = new byte[256];
                        int read = binData.Read(buffer, 0, buffer.Length);
                        while (read > 0)
                        {
                            w.Write(buffer, 0, read);
                            read = binData.Read(buffer, 0, buffer.Length);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                return false;
            }
            finally
            {
                if (w != null)
                {
                    w.Close();
                    w = null;
                }
            }

            return true;
        }
 internal LocalValueEnumerator(Dictionary<DependencyProperty,object> properties)
 {
     this.count = properties.Count;
     this.properties = properties;
     this.propertyEnumerator = properties.GetEnumerator();
 }
 protected static void FindImplementedEnumerableType(Type type,
   Type nonGenericType, Type genericType, out Type resultEnumerableType, out Type resultEntryType)
 {
   resultEnumerableType = null;
   resultEntryType = null;
   // First check generic interfaces
   IDictionary<Type, Type> foundGeneric = new Dictionary<Type, Type>();
   foreach (Type interfaceType in type.GetInterfaces())
   {
     Type[] genericArguments;
     if (interfaceType.IsGenericType && (genericArguments = interfaceType.GetGenericArguments()).Length == 1)
     {
       Type entryType = genericArguments[0];
       Type collectionType = genericType.MakeGenericType(entryType);
       if (collectionType.IsAssignableFrom(type))
         if (!foundGeneric.ContainsKey(collectionType))
           foundGeneric.Add(collectionType, entryType);
     }
   }
   IEnumerator<KeyValuePair<Type, Type>> ge = foundGeneric.GetEnumerator();
   if (ge.MoveNext())
   {
     resultEnumerableType = ge.Current.Key;
     resultEntryType = ge.Current.Value;
     return;
   }
   // Fallback: Check non-generic type
   if (nonGenericType.IsAssignableFrom(type))
   {
     resultEnumerableType = nonGenericType;
     return;
   }
 }
        /// <summary>
        /// Compute the min DTW distance between the inputSequence and all possible endings of recorded gestures.
        /// </summary>
        /// <param name="inputSequence">The input gesture</param>
        /// <param name="recordedGesture">Gestures we want to recognize against</param>
        /// <returns>a double indicating level of similarity with closest recorded gesture</returns>        
        public double Dtw(Dictionary<JointID, List<Vector4>> inputSequence, Dictionary<JointID, List<Vector4>> recordedGesture)
        {
            //Make assumption that all lists are same length!
            var inputSeqIterator = inputSequence.GetEnumerator();
            inputSeqIterator.MoveNext();
            int inputLength = inputSeqIterator.Current.Value.Count;

            //Make assumption that all lists are same length!
            var recordedGestureSeqIterator = recordedGesture.GetEnumerator();
            recordedGestureSeqIterator.MoveNext();
            int recordLength = recordedGestureSeqIterator.Current.Value.Count;

            //Book keeping, setting up and initialization.
            var tab = new double[inputLength + 1, recordLength + 1];
            var horizStepsMoved = new int[inputLength + 1, recordLength + 1];
            var vertStepsMoved = new int[inputLength + 1, recordLength + 1];

            for (int i = 0; i < inputLength + 1; ++i)
            {
                for (int j = 0; j < recordLength + 1; ++j)
                {
                    tab[i, j] = double.PositiveInfinity;
                    horizStepsMoved[i, j] = 0;
                    vertStepsMoved[i, j] = 0;
                }
            }

            tab[inputLength, recordLength] = 0;

            //Actually do the DTW algo. Read
            //http://web.science.mq.edu.au/~cassidy/comp449/html/ch11s02.html
            //For a great summary as to what it does.
            for (int i = inputLength - 1; i > -1; --i)
            {
                for (int j = recordLength - 1; j > -1; --j)
                {
                    if (tab[i, j + 1] < tab[i + 1, j + 1] && tab[i, j + 1] < tab[i + 1, j] &&
                        horizStepsMoved[i, j + 1] < _maxSlope)
                    {
                        //Move right, move left on reverse
                        tab[i, j] = CalculateSnapshotPositionDistance(inputSequence, i, recordedGesture, j) + tab[i, j + 1];
                        horizStepsMoved[i, j] = horizStepsMoved[i, j + 1] + 1;
                        vertStepsMoved[i, j] = vertStepsMoved[i, j + 1];

                    }

                    else if (tab[i + 1, j] < tab[i + 1, j + 1] && tab[i + 1, j] < tab[i, j + 1] &&
                             vertStepsMoved[i + 1, j] < _maxSlope)
                    {
                        //Move down, move up on reverse
                        tab[i, j] = CalculateSnapshotPositionDistance(inputSequence, i, recordedGesture, j) + tab[i + 1, j];
                        horizStepsMoved[i, j] = horizStepsMoved[i + 1, j];
                        vertStepsMoved[i, j] = vertStepsMoved[i + 1, j] + 1;
                    }

                    else
                    {
                        //Move diagonally down-right
                        if (tab[i + 1, j + 1] == double.PositiveInfinity)
                        {
                            tab[i, j] = double.PositiveInfinity;
                        }
                        else
                        {
                            tab[i, j] = CalculateSnapshotPositionDistance(inputSequence, i, recordedGesture, j) + tab[i + 1, j + 1];
                        }

                        horizStepsMoved[i, j] = 0;
                        vertStepsMoved[i, j] = 0;

                    }
                }
            }

            double bestMatch = double.PositiveInfinity;

            for (int i = 0; i < inputLength; ++i)
            {
                if (tab[i, 0] < bestMatch)
                {
                    bestMatch = tab[i, 0];
                }
            }
            return bestMatch;
        }
Exemple #30
0
        private static bool SerializeDictInt(Dictionary<string, int> dictionary, StringBuilder builder)
        {
            builder.Append("{");

            IDictionaryEnumerator e = dictionary.GetEnumerator();
            bool first = true;
            while (e.MoveNext())
            {
                string key = e.Key.ToString();
                object value = e.Value;

                if (!first)
                {
                    builder.Append(", ");
                }

                SerializeString(key, builder);
                builder.Append(":");
                if (!SerializeValue(value, builder))
                {
                    return false;
                }

                first = false;
            }

            builder.Append("}");
            return true;
        }
Exemple #31
0
 public Dictionary <object, object> .Enumerator GetEnumerator()
 {
     return(_dic.GetEnumerator());
 }