IndexOfValue() public method

public IndexOfValue ( Object value ) : int
value Object
return int
コード例 #1
0
 public override int IndexOfValue(Object val)
 {
     lock (host.SyncRoot)
     {
         return(host.IndexOfValue(val));
     }
 }
コード例 #2
0
ファイル: SortedList.cs プロジェクト: treesportrait/corefx
 [SuppressMessage("Microsoft.Contracts", "CC1055")]  // Skip extra error checking to avoid *potential* AppCompat problems.
 public override int IndexOfValue(Object value)
 {
     lock (_root)
     {
         return(_list.IndexOfValue(value));
     }
 }
コード例 #3
0
		private void createViewDatatable(SortedList columnOrder)
		{
			ViewDatatable = new DataTable();

			for(int i=0;i<columnOrder.Count; i++)
			{
				viewTableColumnNames viewColumnName;
				Common.Interface.ImportFileColumns dataColumnName;
				string temp = (string)columnOrder.GetKey(
					columnOrder.IndexOfValue(i));
				dataColumnName = convertImportFileColumnsName(temp);
				switch(dataColumnName)
				{
					case Common.Interface.ImportFileColumns.ClubId:
						viewColumnName = viewTableColumnNames.Klubb;
						break;
					case Common.Interface.ImportFileColumns.Email:
						viewColumnName = viewTableColumnNames.Epost;
						break;
					case Common.Interface.ImportFileColumns.Givenname:
						viewColumnName = viewTableColumnNames.Fornamn;
						break;
					case Common.Interface.ImportFileColumns.Lane:
						viewColumnName = viewTableColumnNames.Bana;
						break;
					case Common.Interface.ImportFileColumns.Patrol:
						viewColumnName = viewTableColumnNames.Patrull;
						break;
					case Common.Interface.ImportFileColumns.ShooterClass:
						viewColumnName = viewTableColumnNames.Klass;
						break;
					case Common.Interface.ImportFileColumns.ShooterId:
						viewColumnName = viewTableColumnNames.Skyttekort;
						break;
					case Common.Interface.ImportFileColumns.Surname:
						viewColumnName = viewTableColumnNames.Efternamn;
						break;
					case Common.Interface.ImportFileColumns.WeaponId:
						viewColumnName = viewTableColumnNames.Vapen;
						break;
					default:
						throw new ApplicationException("Unknown datacolumn");
				}
				try
				{
					ViewDatatable.Columns.Add(viewColumnName.ToString(), typeof(string));
				}
				catch(Exception)
				{
				}
			}
		}
コード例 #4
0
 static public int IndexOfValue(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         System.Object a1;
         checkType(l, 2, out a1);
         var ret = self.IndexOfValue(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #5
0
ファイル: SortedListTest.cs プロジェクト: ItsVeryWindy/mono
		public void TestIndexOfValue2 ()
		{
			SortedList list = new SortedList ();
			list.Add ("key0", "la la");
			list.Add ("key1", "value");
			list.Add ("key2", "value");

			int i = list.IndexOfValue ("value");
			Assert.AreEqual (1, i);
		}
コード例 #6
0
ファイル: SortedListTest.cs プロジェクト: ItsVeryWindy/mono
		public void TestIndexOfValue3 ()
		{
			SortedList list = new SortedList ();
			int i = list.IndexOfValue ((string) null);
			Assert.AreEqual (1, -i);
		}
コード例 #7
0
		/// -----------------------------------------------------------------------------
		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		/// <remarks>
		/// </remarks>
		/// <history>
		/// 	[jbrinkman]	5/6/2004	Created
		///		[jhenning] 2/22/2005	Added properties
		/// </history>
		/// -----------------------------------------------------------------------------
		protected override void RenderContents(HtmlTextWriter writer)
		{
			writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
			writer.AddAttribute(HtmlTextWriterAttribute.Class, m_objMenu.CssClass);
			writer.AddAttribute(HtmlTextWriterAttribute.Name, m_objMenu.UniqueID);
			writer.AddAttribute(HtmlTextWriterAttribute.Id, m_objMenu.ClientID);

			writer.AddAttribute("orient", ((int)m_objMenu.Orientation).ToString());
			if (m_objMenu.SubMenuOrientation != Orientation.Vertical)
			{
				writer.AddAttribute("suborient", ((int)m_objMenu.SubMenuOrientation).ToString());
			}
			writer.AddAttribute("sysimgpath", m_objMenu.SystemImagesPath);
			if (!String.IsNullOrEmpty(m_objMenu.Target)) writer.AddAttribute("target", m_objMenu.Target); 

			//--- imagelist logic ---
			if (m_objMenu.ImageList.Count > 0)
			{
				SortedList objImagePaths = new SortedList();
				string strList = "";
				string strImagePathList = "";
				foreach (NodeImage objNodeImage in m_objMenu.ImageList) {
					if (objNodeImage.ImageUrl.IndexOf("/") > -1)
					{
						string strPath = objNodeImage.ImageUrl.Substring(0, objNodeImage.ImageUrl.LastIndexOf("/") + 1);
						string strImage = objNodeImage.ImageUrl.Substring(objNodeImage.ImageUrl.LastIndexOf("/") + 1);
						if (objImagePaths.ContainsValue(strPath) == false)
						{
							objImagePaths.Add(objImagePaths.Count, strPath);
						}
						objNodeImage.ImageUrl = string.Format("[{0}]{1}", objImagePaths.IndexOfValue(strPath).ToString(), strImage);
					}
                        strList += (String.IsNullOrEmpty(strList) ? "" : ",") + objNodeImage.ImageUrl;
				}
				for (int intPaths = 0; intPaths <= objImagePaths.Count - 1; intPaths++) 
                    {
                        strImagePathList += (String.IsNullOrEmpty(strImagePathList) ? "" : ",") + objImagePaths.GetByIndex(intPaths).ToString();
				}
				writer.AddAttribute("imagelist", strList);
				writer.AddAttribute("imagepaths", strImagePathList);
			}

			//--- urllist logic ---'
			//Dim objUsedTokens As ArrayList = New ArrayList
			//Me.AssignUrlTokens(m_objMenu.MenuNodes, Nothing, objUsedTokens)
			//If objUsedTokens.Count > 0 Then
			//	writer.AddAttribute("urllist", Join(objUsedTokens.ToArray(), ","))				  'comma safe?!?!?!
			//End If

			if (!String.IsNullOrEmpty(m_objMenu.RootArrowImage)) writer.AddAttribute("rarrowimg", m_objMenu.RootArrowImage); 
			if (!String.IsNullOrEmpty(m_objMenu.ChildArrowImage)) writer.AddAttribute("carrowimg", m_objMenu.ChildArrowImage); 
			if (!String.IsNullOrEmpty(m_objMenu.WorkImage)) writer.AddAttribute("workimg", m_objMenu.WorkImage); 

			//css attributes
			if (!String.IsNullOrEmpty(m_objMenu.DefaultNodeCssClass)) writer.AddAttribute("css", m_objMenu.DefaultNodeCssClass); 
			if (!String.IsNullOrEmpty(m_objMenu.DefaultChildNodeCssClass)) writer.AddAttribute("csschild", m_objMenu.DefaultChildNodeCssClass); 
			if (!String.IsNullOrEmpty(m_objMenu.DefaultNodeCssClassOver)) writer.AddAttribute("csshover", m_objMenu.DefaultNodeCssClassOver); 
			if (!String.IsNullOrEmpty(m_objMenu.DefaultNodeCssClassSelected)) writer.AddAttribute("csssel", m_objMenu.DefaultNodeCssClassSelected); 
			if (!String.IsNullOrEmpty(m_objMenu.MenuBarCssClass)) writer.AddAttribute("mbcss", m_objMenu.MenuBarCssClass); 
			if (!String.IsNullOrEmpty(m_objMenu.MenuCssClass)) writer.AddAttribute("mcss", m_objMenu.MenuCssClass); 
			if (!String.IsNullOrEmpty(m_objMenu.DefaultIconCssClass)) writer.AddAttribute("cssicon", m_objMenu.DefaultIconCssClass); 

			if (!String.IsNullOrEmpty(m_objMenu.JSFunction)) writer.AddAttribute("js", m_objMenu.JSFunction); 
			if (m_objMenu.UseTables == false) writer.AddAttribute("usetables", "0"); 
			if (m_objMenu.EnablePostbackState) writer.AddAttribute("enablepbstate", "1"); 
			if (m_objMenu.MouseOutDelay != 500) writer.AddAttribute("moutdelay", m_objMenu.MouseOutDelay.ToString()); 
			if (m_objMenu.MouseInDelay != 250) writer.AddAttribute("mindelay", m_objMenu.MouseInDelay.ToString()); 

			writer.AddAttribute("postback", ClientAPI.GetPostBackEventReference(m_objMenu, "[NODEID]" + ClientAPI.COLUMN_DELIMITER + "Click"));

			if (m_objMenu.PopulateNodesFromClient)
			{
				if (DotNetNuke.UI.Utilities.ClientAPI.BrowserSupportsFunctionality(Utilities.ClientAPI.ClientFunctionality.XMLHTTP))
				{
					writer.AddAttribute("callback", DotNetNuke.UI.Utilities.ClientAPI.GetCallbackEventReference(m_objMenu, "'[NODEXML]'", "this.callBackSuccess", "oMNode", "this.callBackFail", "this.callBackStatus"));
				}
				else
				{
					writer.AddAttribute("callback", ClientAPI.GetPostBackClientHyperlink(m_objMenu, "[NODEID]" + ClientAPI.COLUMN_DELIMITER + "OnDemand"));
				}
				if (!String.IsNullOrEmpty(m_objMenu.CallbackStatusFunction))
				{
					writer.AddAttribute("callbacksf", m_objMenu.CallbackStatusFunction);
				}

			}

			if (!String.IsNullOrEmpty(m_objMenu.JSFunction))
			{
				writer.AddAttribute("js", m_objMenu.JSFunction);
			}
			//writer.RenderBeginTag(HtmlTextWriterTag.P)			 '//SAFARI DOES NOT LIKE DIV TAG!!!
			writer.RenderBeginTag(HtmlTextWriterTag.Span);
			//TODO: TEST SAFARI!
			//RenderChildren(writer)	'no longer rendering children for uplevel, only sending down xml and client is responsible
			writer.RenderEndTag();
		}
コード例 #8
0
ファイル: SortedListTest.cs プロジェクト: ItsVeryWindy/mono
		public void TestIndexOfValue ()
		{
			SortedList sl1 = new SortedList (24);
			string s = null;
			for (int i = 0; i < 50; i++) {
				s = string.Format ("{0:D2}", i);
				sl1.Add ("kala " + s, 100 + i * i);
			}
			for (int i = 0; i < 50; i++) {
				s = string.Format ("{0:D2}", i + 50);
				sl1.Add ("kala " + s, 100 + i * i);
			}
			Assert.AreEqual (-1, sl1.IndexOfValue (102), "#1");
			Assert.AreEqual (-1, sl1.IndexOfValue (null), "#2");
			for (int i = 0; i < 50; i++)
				Assert.AreEqual (i, sl1.IndexOfValue (100 + i * i), "#3:" + i);
		}
コード例 #9
0
ファイル: XmlWriter.cs プロジェクト: ChrisMoreton/Test3
		public void Write(System.Xml.XmlWriter writer)
		{
			// Write the XML declaration
			if (_options.WriteXMLDecl)
				writer.WriteStartDocument(true);

			// Write header info
			writer.WriteComment("FlowChart.NET diagram");

			// Write the root element
			writer.WriteStartElement("Diagram");
			writer.WriteAttributeString("Version", Version.ToString());

			// Write brushes
			int id = 0;
			SortedList brushes = new SortedList();
			foreach(Brush b in Brush.Brushes)
			{
				brushes.Add(id, b); // Map brushes to ids
				id++;
			}

			writer.WriteStartElement("Brushes");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(brushes.Count));

			for(int i = 0; i < brushes.Count; i++)
			{
				FlowChartX.Brush b =
					(FlowChartX.Brush)brushes.GetValueList()[i];

				WriteBrushElement(writer, b, brushes);
			}

			// Close the Brushes element
			writer.WriteEndElement();

			// Write the environment information
			writer.WriteStartElement("Environment");

			// Write appearance information
			WriteProperties(writer, _diagram,
				_appearanceProps, "Appearance");

			// Write behaviour information
			WriteProperties(writer, _diagram,
				_behaviourProps, "Behaviour");

			// Write defaults information
			WriteProperties(writer, _diagram,
				_defaultProps, "Defaults");

			// Write default brush and pens
			writer.WriteStartElement("DefaultsGDI");

			WriteBrushRefElement(writer, _diagram.BoxBrush, "BoxBrush", brushes);
			WriteBrushRefElement(writer, _diagram.TableBrush, "TableBrush", brushes);
			WriteBrushRefElement(writer, _diagram.ArrowBrush, "ArrowBrush", brushes);
			WriteBrushRefElement(writer, _diagram.BackBrush, "BackBrush", brushes);
			WriteBrushRefElement(writer, _diagram.ExteriorBrush, "ExteriorBrush", brushes);
			WritePenElement(writer, _diagram.BoxPen, "BoxPen", brushes);
			WritePenElement(writer, _diagram.TablePen, "TablePen", brushes);
			WritePenElement(writer, _diagram.ArrowPen, "ArrowPen", brushes);

			writer.WriteEndElement();

			// Write grid information
			WriteProperties(writer, _diagram,
				_gridProps, "Grid");

			// Write layout information
			WriteProperties(writer, _diagram,
				_layoutProps, "Layout");

			// Write miscellaneous information
			WriteProperties(writer, _diagram,
				_miscProps, "Miscellaneous");

			// Close the environment element
			writer.WriteEndElement();

			// Write the box information
			writer.WriteStartElement("Boxes");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(_diagram.Boxes.Count));

			id = 0;
			SortedList sl = new SortedList();
			foreach(Box b in _diagram.Boxes)
			{
				writer.WriteStartElement("Box");
				writer.WriteAttributeString("Id", XmlConvert.FromInt32(id));
				writer.WriteAttributeString("ZIndex", XmlConvert.FromInt32(b.ZIndex));

				// Write the shape type
				string shape = "Invalid";
				switch(b.Style)
				{
					case BoxStyle.Delay:
						shape = "Delay";
						break;
					case BoxStyle.Ellipse:
						shape = "Ellipse";
						break;
					case BoxStyle.Rectangle:
						shape = "Rectangle";
						break;
					case BoxStyle.Rhombus:
						shape = "Decision";
						break;
					case BoxStyle.RoundedRectangle:
						shape = "RoundRectangle";
						break;
					case BoxStyle.Shape:
						// Only shapes with assigned ids are serialized
						shape = b.Shape.Id;

						if (shape == "")
						{
							// Possibly one of the old predefined shapes
							foreach (ShapeTemplate newShape in ShapeTemplate.Shapes)
							{
								if (b.Shape.Equals(newShape))
								{
									shape = newShape.Id;
									break;
								}
							}

							if (shape == "")
								shape = "Rectangle";
						}
						break;
				}
				writer.WriteElementString("Shape", shape);

				// Write brush index
				WriteBrushRefElement(writer, b.Brush, "Brush", brushes);
				// Write the pen
				WritePenElement(writer, b.Pen, "Pen", brushes);
				// Write the tag
				WriteTagElement(writer, b);

				// Write constraints
				WriteConstraints(writer, b);

				// Write properties
				WriteProperties(writer, b, _boxProps, null);

				writer.WriteEndElement();

				sl.Add(id, b); // map boxes to ids
				id++;
			}

			// Close boxes element
			writer.WriteEndElement();

			// Write the control host information
			writer.WriteStartElement("ControlHosts");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(_diagram.ControlHosts.Count));

			BinaryFormatter fmt = new BinaryFormatter();
			foreach (ControlHost h in _diagram.ControlHosts)
			{
				writer.WriteStartElement("Host");
				writer.WriteAttributeString("Id", XmlConvert.FromInt32(id));
				writer.WriteAttributeString("ZIndex", XmlConvert.FromInt32(h.ZIndex));
				if (h.Control != null)
				{
					System.Type type = h.Control.GetType();
					writer.WriteAttributeString("ControlAssembly", type.Assembly.GetName().Name);
					writer.WriteAttributeString("ControlType", type.FullName);

					// Find the z-index of the contained control
					int controlZIndex = 0;
					for (int i = 0; i < _diagram.Controls.Count; i++)
					{
						if (_diagram.Controls[i] == h.Control)
						{
							controlZIndex = i;
							break;
						}
					}
					writer.WriteAttributeString("ControlZIndex", controlZIndex.ToString());
				}
				else
				{
					writer.WriteAttributeString("ControlAssembly", "");
					writer.WriteAttributeString("ControlType", "");
					writer.WriteAttributeString("ControlZIndex", "0");
				}

				// Write brush index
				WriteBrushRefElement(writer, h.Brush, "Brush", brushes);
				// Write the pen
				WritePenElement(writer, h.Pen, "Pen", brushes);

				// Write control properties
				WriteControlProperties(writer, h.Control, fmt);
				// Write control host properties
				WriteProperties(writer, h, _hostProps, null);
				// Write the tag
				WriteTagElement(writer, h);

				// Write constraints
				WriteConstraints(writer, h);

				writer.WriteEndElement();

				sl.Add(id, h); // map hosts to ids
				id++;
			}

			writer.WriteEndElement();

			// Write table information
			writer.WriteStartElement("Tables");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(_diagram.Tables.Count));

			foreach(Table t in _diagram.Tables)
			{
				writer.WriteStartElement("Table");
				writer.WriteAttributeString("Id",
					XmlConvert.FromInt32(id));
				writer.WriteAttributeString("ZIndex",
					XmlConvert.FromInt32(t.ZIndex));
				writer.WriteAttributeString("Rows",
					XmlConvert.FromInt32(t.RowCount));
				writer.WriteAttributeString("Columns",
					XmlConvert.FromInt32(t.ColumnCount));

				// Write table data
				writer.WriteStartElement("Data");
				for(int r = 0; r < t.RowCount; r++)
				{
					for(int c = 0; c < t.ColumnCount; c++)
					{
						Table.Cell cell = t[c, r];

						writer.WriteStartElement("Cell");

						WriteBrushRefElement(writer, cell.Brush, "Brush",
							brushes);

						// Write the tag
						WriteTagElement(writer, cell);

						WriteProperties(writer, cell, 
							new string[] { "Text", "TextFormat",
								"Picture", "PicturePos", "TextColor",
								"HyperLink", "ToolTip", "RowSpan", "ColumnSpan", }, null);

						writer.WriteEndElement();
					}
				}
				writer.WriteEndElement();

				// Write row data
				writer.WriteStartElement("Rows");
				for(int r = 0; r < t.RowCount; r++)
				{
					writer.WriteStartElement("Row");
					WriteProperties(writer, t.Rows[r],
						new string[] { "Height", "AnchorPattern", "Header", "Expanded" }, null);
					writer.WriteEndElement();
				}
				writer.WriteEndElement();

				// Write column data
				writer.WriteStartElement("Columns");
				for(int c = 0; c < t.ColumnCount; c++)
				{
					writer.WriteStartElement("Column");
					WriteProperties(writer, t.Columns[c],
						new string[] { "ColumnStyle", "Width" }, null);
					writer.WriteEndElement();
				}
				writer.WriteEndElement();

				// Write brush index
				WriteBrushRefElement(writer, t.Brush, "Brush", brushes);
				// Write caption background brush
				WriteBrushRefElement(writer, t.CaptionBackBrush, "CaptionBackBrush", brushes);
				// Write the pen
				WritePenElement(writer, t.Pen, "Pen", brushes);
				// Write the tag
				WriteTagElement(writer, t);

				// Write constraints
				WriteConstraints(writer, t);

				// Write properties
				WriteProperties(writer, t, _tableProps, null);

				writer.WriteEndElement();

				sl.Add(id, t); // map tables to ids
				id++;
			}

			// Close tables element
			writer.WriteEndElement();

			// Write containers in v7
			writer.WriteStartElement("Containers");
			writer.WriteAttributeString("Count", "0");
			writer.WriteEndElement();

			// Write arrows data
			writer.WriteStartElement("Arrows");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(_diagram.Arrows.Count));

			int oi, di;
			int aid = id;
			foreach(Arrow a in _diagram.Arrows)
			{
				writer.WriteStartElement("Arrow");
				writer.WriteAttributeString("Id",
					XmlConvert.FromInt32(aid));
				writer.WriteAttributeString("ZIndex",
					XmlConvert.FromInt32(a.ZIndex));

				if (a.Origin != _diagram.Dummy)
				{
					oi = sl.IndexOfValue(a.Origin);
					if(oi < 0)
						throw new Exception("Unexpected arrow origin index");
					id = (int)sl.GetKey(oi);
				}
				else
				{
					id = -1;
				}

				writer.WriteAttributeString("From", XmlConvert.FromInt32(id));
				if(a.Origin is Table)
					writer.WriteAttributeString("RowFrom",
						XmlConvert.FromInt32(a.OrgnIndex));

				if (a.Destination != _diagram.Dummy)
				{
					di = sl.IndexOfValue(a.Destination);
					if(di < 0)
						throw new Exception("Unexpected arrow destination index");
					id = (int)sl.GetKey(di);
				}
				else
				{
					id = -1;
				}

				writer.WriteAttributeString("To", XmlConvert.FromInt32(id));
				if(a.Destination is Table)
					writer.WriteAttributeString("RowTo",
						XmlConvert.FromInt32(a.DestIndex));

				// Write control points
				writer.WriteStartElement("Data");
				foreach(PointF pt in a.ControlPoints)
				{
					writer.WriteStartElement("Point");

					writer.WriteAttributeString("X", XmlConvert.FromSingle(pt.X));
					writer.WriteAttributeString("Y", XmlConvert.FromSingle(pt.Y));

					writer.WriteEndElement();
				}
				writer.WriteEndElement();

				// Write brush index
				WriteBrushRefElement(writer, a.Brush, "Brush", brushes);
				// Write pen
				WritePenElement(writer, a.Pen, "Pen", brushes);
				// Write head pen
				WritePenElement(writer, a.HeadPen, "HeadPen", brushes);
				// Write the tag
				WriteTagElement(writer, a);

				// Write arrow properties
				WriteProperties(writer, a, _arrowProps, null);

				writer.WriteEndElement();

				sl.Add(aid, a); // map arrows to ids
				aid++;
			}

			// Close arrows element
			writer.WriteEndElement();

			// Write group objects
			writer.WriteStartElement("Groups");
			writer.WriteAttributeString("Count",
				XmlConvert.FromInt32(_diagram.Groups.Count));

			foreach(Group g in _diagram.Groups)
			{
				writer.WriteStartElement("Group");

				oi = sl.IndexOfValue(g.MainObject);
				if(oi < 0)
					throw new Exception("Unexpected group master index");
				id = (int)sl.GetKey(oi);

				// Write group's main object
				writer.WriteStartElement("MainObject");
				writer.WriteAttributeString("Id", XmlConvert.FromInt32(id));
				writer.WriteEndElement();

				// Write group's visibility
				writer.WriteElementString("Visible", g.Visible.ToString());

				// Write AutoDeleteItems flag
				writer.WriteElementString("AutoDeleteItems", g.AutoDeleteItems.ToString());

				// Write Expandable flag
				writer.WriteElementString("Expandable", g.Expandable.ToString());

				// Write FollowMasterRotation flag
				writer.WriteElementString("FollowMasterRotation", g.FollowMasterRotation.ToString());

				// Write group's tag
				WriteTagElement(writer, g);

				// Write attached objects
				writer.WriteStartElement("Attachments");
				writer.WriteAttributeString("Count",
					XmlConvert.FromInt32(g.Attachments.Count));
				foreach(Attachment at in g.Attachments)
				{
					writer.WriteStartElement("Attachment");

					writer.WriteElementString("Data",
						XmlConvert.FromInt32(at.attData));
					oi = sl.IndexOfValue(at.node);
					if(oi < 0)
						throw new Exception("Unexpected group attachee index");
					id = (int)sl.GetKey(oi);
					writer.WriteElementString("Object", XmlConvert.FromInt32(id));
					WriteRectangleFElement(writer, "Percents", at.percents);
					writer.WriteElementString("Type",
						at.type.ToString());

					writer.WriteEndElement();
				}
				writer.WriteEndElement();

				writer.WriteEndElement();
			}

			// Close groups element
			writer.WriteEndElement();


			// Close the diagram element
			writer.WriteEndElement();

			// Finish with this document
			if (_options.WriteXMLDecl)
				writer.WriteEndDocument();

			writer.Flush();
		}
コード例 #10
0
 private XmlDocument DownloadAmeriFluxTS(string SiteCodeTS, string[] VariableCodes, string StartDate, string EndDate)
 {
     if (VariableCodes.Length == 0)
     {
         throw new Exception("No variable codes provided");
     }
     XmlDocument found = null;
     System.DateTime dtStart;
     System.DateTime dtEnd;
     dtStart = Convert.ToDateTime(StartDate);
     dtEnd = Convert.ToDateTime(EndDate);
     string sURL;
     sURL = BuildAmeriFluxTSURL(SiteCodeTS, VariableCodes, dtStart, dtEnd);
     string sTxt;
     sTxt = utils.DownloadASCII(sURL);
     int i;
     int j;
     i = sTxt.IndexOf(".csv");
     if (i == 0)
     {
         throw new Exception("URL did not return link to csv file: " + Environment.NewLine + sURL);
     }
     sTxt = sTxt.Substring(i + 5);
     i = sTxt.IndexOf(".csv");
     sTxt = sTxt.Substring(0, i + 4);
     sTxt = utils.DownloadASCII(sTxt);
     string[] sLines;
     string[] sParts;
     string sPart;
     sLines = sTxt.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
     System.Collections.SortedList slFields = new System.Collections.SortedList();
     System.Collections.SortedList slUnits = new System.Collections.SortedList();
     string sUnits;
     string sField;
     sParts = sLines[0].Split(',');
     for (int k = 0; k <= sParts.Length - 1; k++)
     {
         sPart = sParts[k].Trim();
         i = sPart.IndexOf("(");
         if (i > -1)
         {
             sField = sPart.Substring(0, i).Trim();
             j = sPart.IndexOf(")", i);
             if (j == -1)
             {
                 j = sPart.Length - 1;
             }
             sUnits = sPart.Substring(i + 1, j - i - 1).Trim();
         }
         else
         {
             sField = sPart;
             sUnits = "";
         }
         if (sPart.Length > 0)
         {
             slFields.Add(k, sField);
             slUnits.Add(k, sUnits);
         }
     }
     if (sLines.Length < 2)
     {
         throw new Exception("No time series values returned for site " + SiteCodeTS);
     }
     XmlElement root;
     XmlElement parent;
     XmlElement row;
     XmlElement element;
     XmlDocument xmlDoc = new XmlDocument();
     root = xmlDoc.CreateElement("AmeriFluxTimeSeries");
     xmlDoc.AppendChild(root);
     XmlElement metadata;
     metadata = xmlDoc.CreateElement("Metadata");
     element = xmlDoc.CreateElement("SiteCode");
     element.InnerText = SiteCodeTS;
     metadata.AppendChild(element);
     element = xmlDoc.CreateElement("SiteName");
     i = slFields.IndexOfValue("Site");
     sParts = sLines[1].Split(',');
     element.InnerText = sParts[i].Replace("'", "");
     metadata.AppendChild(element);
     parent = xmlDoc.CreateElement("Flags");
     metadata.AppendChild(parent);
     row = xmlDoc.CreateElement("Flag");
     parent.AppendChild(row);
     element = xmlDoc.CreateElement("FlagValue");
     element.InnerText = ".";
     row.AppendChild(element);
     element = xmlDoc.CreateElement("FlagMeaning");
     element.InnerText = "Missing value";
     row.AppendChild(element);
     System.DateTime dtGMT;
     System.DateTime dtSite;
     sParts = sLines[1].Split(',');
     i = slFields.IndexOfValue("Year");
     dtSite = DateTime.Parse("1/1/" + sParts[i]);
     i = slFields.IndexOfValue("JD");
     dtSite = dtSite.AddDays(Convert.ToDouble(sParts[i]) - 1);
     i = slFields.IndexOfValue("Hour");
     dtSite = dtSite.AddHours(Convert.ToDouble(sParts[i]));
     i = slFields.IndexOfValue("Minute");
     dtSite = dtSite.AddMinutes(Convert.ToDouble(sParts[i]));
     i = slFields.IndexOfValue("GMT_year");
     dtGMT = DateTime.Parse("1/1/" + sParts[i]);
     i = slFields.IndexOfValue("GMT_jd");
     dtGMT = dtGMT.AddDays(Convert.ToDouble(sParts[i]) - 1);
     i = slFields.IndexOfValue("GMT_hour");
     dtGMT = dtGMT.AddHours(Convert.ToDouble(sParts[i]));
     i = slFields.IndexOfValue("GMT_min");
     dtGMT = dtGMT.AddMinutes(Convert.ToDouble(sParts[i]));
     element = xmlDoc.CreateElement("GmtOffsetHours");
     element.InnerText = Convert.ToString(dtSite.Subtract(dtGMT).TotalHours);
     metadata.AppendChild(element);
     element = xmlDoc.CreateElement("ErrorDescription");
     metadata.AppendChild(element);
     for (int i2 = 0; i2 <= VariableCodes.Length - 1; i2++)
     {
         for (int k = 0; k <= slFields.Count - 1; k++)
         {
             if (Convert.ToString(slFields.GetByIndex(k)) == Convert.ToString(VariableCodes[i2]))
             {
                 found = xmlDoc;
             }
         }
         if (found == null)
         {
             throw new Exception("Variable " + VariableCodes[i2] + " not recorded at this site");
         }
     }
     int paramCount = VariableCodes.Length;
     int recordCount = 0;
     for (int k = sLines.Length - 1; k >= 1; k--)
     {
         sParts = sLines[k].Split(',');
         if (sParts.Length > 1)
         {
             recordCount = k;
             break;
         }
     }
     if (recordCount == 0)
     {
         throw new Exception("No time series values returned for site " + SiteCodeTS);
     }
     string[,] sValues = new string[paramCount, recordCount];
     string[] sTimes = new string[recordCount];
     for (int k = 1; k <= recordCount; k++)
     {
         sParts = sLines[k].Split(',');
         i = slFields.IndexOfValue("Year");
         dtSite = DateTime.Parse("1/1/" + sParts[i]);
         i = slFields.IndexOfValue("JD");
         dtSite = dtSite.AddDays(Convert.ToDouble(sParts[i]) - 1);
         i = slFields.IndexOfValue("Hour");
         dtSite = dtSite.AddHours(Convert.ToDouble(sParts[i]));
         i = slFields.IndexOfValue("Minute");
         dtSite = dtSite.AddMinutes(Convert.ToDouble(sParts[i]));
         sTimes[k - 1] = dtSite.ToShortDateString() + " " + dtSite.ToShortTimeString();
         for (int l = 0; l <= paramCount - 1; l++)
         {
             i = slFields.IndexOfValue(VariableCodes[l]);
             sValues[l, k - 1] = sParts[i].Trim();
         }
     }
     XmlElement timeseries;
     for (int l = 0; l <= paramCount - 1; l++)
     {
         timeseries = xmlDoc.CreateElement("TimeSeries");
         root.AppendChild(timeseries);
         timeseries.InnerXml = metadata.InnerXml;
         element = xmlDoc.CreateElement("VariableCode");
         element.InnerText = VariableCodes[l];
         timeseries.AppendChild(element);
         element = xmlDoc.CreateElement("Units");
         i = slFields.IndexOfValue(VariableCodes[l].Trim());
         element.InnerText = slUnits.GetByIndex(i).ToString();
         timeseries.AppendChild(element);
         parent = xmlDoc.CreateElement("Records");
         timeseries.AppendChild(parent);
         for (int k = 0; k <= recordCount - 1; k++)
         {
             row = xmlDoc.CreateElement("Record");
             parent.AppendChild(row);
             element = xmlDoc.CreateElement("DateTime");
             element.InnerText = sTimes[k];
             row.AppendChild(element);
             element = xmlDoc.CreateElement("Value");
             element.InnerText = sValues[l, k];
             row.AppendChild(element);
         }
     }
     return xmlDoc;
 }
コード例 #11
0
        public EPoint GetUpperPowerTextureSize(EPoint a_size)
        {
            EPoint sizeReturn = new EPoint();
            SortedList aAllowedSizes = new SortedList();
            int n = 4;
            for (int i = 0; i < 10; i++)
            {
                aAllowedSizes.Add(n,i);
                n*=2;
            }

            int nVal = a_size.X;
            for (int i = 0; i < 2; i++)
            {
                aAllowedSizes.Add(nVal, -1);
                int nIndex = aAllowedSizes.IndexOfValue(-1);
                aAllowedSizes.RemoveAt(nIndex);
                if (nIndex > aAllowedSizes.Count)
                    nIndex--;
                nVal = Convert.ToInt32(aAllowedSizes.GetKey(nIndex));
                if (i == 0)
                    sizeReturn.X = nVal;
                else
                    sizeReturn.Y = nVal;

                nVal = a_size.Y;
            }
            return sizeReturn;
        }
コード例 #12
0
ファイル: SortedList.cs プロジェクト: yonder/mono
 public virtual int IndexOf(object value)
 {
     return(host.IndexOfValue(value));
 }
コード例 #13
0
    /**
     * Checks if connection to the current address is optimal. 
     * Scores can vary over time, and there might be "tight" race for the optimal.
     * We may end up in a situation that we are trimming a connection that is not optimal, even 
     * though the penalty for not using the optimal is marginal. The following algorithm
     * checks that the current selection is in the top-percentile and also the penalty for not
     * using the current optimal is marginal. 
     * @param curr_address address of the current connection target. 
     * @param score_table candidate addresses sorted by scores.
     * @param max_rank maximum rank within the score table, beyond which connection 
     *                 is treated suboptimal.
     */
    protected bool IsConnectionOptimal(Address curr_address, SortedList score_table, int max_rank) {
      if (score_table.Count == 0) {
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Not sufficient scores available to determine optimality: {1}.", 
                                          _node.Address, curr_address));
        }
        return true;
      }
            
      bool optimal = false; //if shortcut is optimal.
      bool doubtful = false; //if there is doubt on optimality of this connection.
      int curr_rank = score_table.IndexOfValue(curr_address);
      if (curr_rank == -1) {
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, No score available for current: {1}.", 
                                          _node.Address, curr_address));
        }
        
        //doubtful case
        doubtful = true;
      } else if (curr_rank == 0) {
        //definitely optimal
        optimal = true;
      } else if (curr_rank <= max_rank) {
        //not the minimum, but still in top percentile.
        double penalty = (double) score_table.GetKey(curr_rank)/(double) score_table.GetKey(0);
        if (LogEnabled) {
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Penalty for using current: {1} penalty: {2}).", 
                                          _node.Address, curr_address, penalty));
        }

        //we allow for 10 percent penalty for not using the optimal
        if (penalty < 1.1 ) {
          optimal = true;
        }
      } else {
        if (LogEnabled) {        
          ProtocolLog.Write(ProtocolLog.SCO, 
                            String.Format("SCO local: {0}, Current: {1} too poorly ranked: {2}.", 
                                  _node.Address, curr_address, curr_rank));
        }
      }

      /** 
       * If we are doubtful about the current selection, we will continue to treat it
       * optimal for sometime.
       */
      string log = null;
      lock(_sync) {
        if (optimal) {
          //clear the entry
          _doubts_table.Remove(curr_address);
        } 
        else if (doubtful) { //if we have doubt about the selection
          //make sure that we are not being to generous
          if (!_doubts_table.ContainsKey(curr_address)) {
            _doubts_table[curr_address] = 1;
          } 
          int idx = (int) _doubts_table[curr_address];
          if (idx < MAX_DOUBT_BENEFITS) {
            _doubts_table[curr_address] = idx + 1;
            log = String.Format("SCO local: {0}, Giving benfit: {1} of doubt for current: {2}.", 
                                       _node.Address, idx, curr_address);
            optimal = true;
          } else {
            log = String.Format("SCO local: {0}, Reached quota: {1} on doubts for current: {2}.", 
                                _node.Address, idx, curr_address);
          }
        }
        
        //all efforts to make the connection look optimal have failed
        if (!optimal) {
          //clear the entry
          _doubts_table.Remove(curr_address);          
        }
      } //end of lock
      if (LogEnabled) {
        ProtocolLog.Write(ProtocolLog.SCO, log);
      }
      return optimal;
    }
コード例 #14
0
 internal int IndexOf(GridItem grid_item)
 {
     return(list.IndexOfValue(grid_item));
 }
コード例 #15
0
ファイル: XmlWriter.cs プロジェクト: ChrisMoreton/Test3
		private void WritePenElement(System.Xml.XmlWriter writer,
			FlowChartX.Pen pen, string element, SortedList brushes)
		{
			if(pen == null)
				return;

			writer.WriteStartElement(element);

			if(pen.Brush != null)
			{
				int bi = brushes.IndexOfValue(pen.Brush);

				writer.WriteStartElement("Brush");
				writer.WriteAttributeString("Id",
					XmlConvert.FromInt32((int)brushes.GetKey(bi)));
				writer.WriteEndElement();
			}

			writer.WriteElementString("Color",
				XmlConvert.FromColor(pen.Color));

			if(pen.CompoundArray != null)
			{
				WriteFloatArrayElement(writer, pen.CompoundArray,
					"CompoundArray", "Pos");
			}

			writer.WriteElementString("DashOffset",
				XmlConvert.FromSingle(pen.DashOffset));

			if(pen.DashPattern != null)
			{
				WriteFloatArrayElement(writer, pen.DashPattern,
					"DashPattern", "Pos");
			}

			writer.WriteElementString("DashStyle",
				pen.DashStyle.ToString());

			writer.WriteElementString("LineJoint",
				pen.LineJoin.ToString());

			writer.WriteElementString("MiterLimit",
				XmlConvert.FromSingle(pen.MiterLimit));

			writer.WriteElementString("Width",
				XmlConvert.FromSingle(pen.Width));

			writer.WriteEndElement();
		}
コード例 #16
0
ファイル: XmlWriter.cs プロジェクト: ChrisMoreton/Test3
		private void WriteBrushElement(System.Xml.XmlWriter writer,
			FlowChartX.Brush brush, SortedList brushes)
		{
			if(brush == null)
				return;

			int ix = brushes.IndexOfValue(brush);
			if(ix < 0)
				throw new Exception(
					"Brush not found in the brush list!");

			writer.WriteStartElement("Brush");
			writer.WriteAttributeString("Id",
				XmlConvert.FromInt32((int)brushes.GetKey(ix)));

			if(brush.GetType().Equals(typeof(FlowChartX.SolidBrush)))
			{
				FlowChartX.SolidBrush bb =
					(FlowChartX.SolidBrush)brush;

				writer.WriteAttributeString("Type", "Solid");

				writer.WriteElementString("Color",
					XmlConvert.FromColor(bb.Color));
			}
			else if(brush.GetType().Equals(typeof(FlowChartX.HatchBrush)))
			{
				FlowChartX.HatchBrush bb =
					(FlowChartX.HatchBrush)brush;

				writer.WriteAttributeString("Type", "Hatch");

				writer.WriteElementString("ForeColor",
					XmlConvert.FromColor(bb.ForegroundColor));
				writer.WriteElementString("BackColor",
					XmlConvert.FromColor(bb.BackgroundColor));
				writer.WriteElementString("Style",
					bb.HatchStyle.ToString());
			}
			else if(brush.GetType().Equals(typeof(FlowChartX.LinearGradientBrush)))
			{
				FlowChartX.LinearGradientBrush bb =
					(FlowChartX.LinearGradientBrush)brush;

				writer.WriteAttributeString("Type", "Gradient");

				// Write angle
				writer.WriteElementString("Angle",
					XmlConvert.FromSingle(bb.Angle));

				// Write blend pattern
				if(bb.Blend != null)
				{
					writer.WriteStartElement("Blend");

					WriteFloatArrayElement(writer, bb.Blend.Positions,
						"Positions", "Pos");
					WriteFloatArrayElement(writer, bb.Blend.Factors,
						"Factors", "Fac");

					writer.WriteEndElement();
				}

				// Write linear colors
				writer.WriteElementString("Color1",
					XmlConvert.FromColor(bb.LinearColors[0]));
				writer.WriteElementString("Color2",
					XmlConvert.FromColor(bb.LinearColors[1]));

				// Write interpolation colors
				if(bb.InterpolationColor != null)
				{
					writer.WriteStartElement("ColorBlend");

					WriteFloatArrayElement(writer, bb.InterpolationColor.Positions,
						"Positions", "Pos");
					writer.WriteStartElement("Colors");
					writer.WriteAttributeString("Count",
						XmlConvert.FromInt32(bb.InterpolationColor.Colors.Length));
					for(int j = 0; j < bb.InterpolationColor.Colors.Length; j++)
					{
						Color c = (Color)
							bb.InterpolationColor.Colors.GetValue(j);
						writer.WriteElementString("Color",
							XmlConvert.FromColor(c));
					}
					writer.WriteEndElement();

					writer.WriteEndElement();
				}
			}
			else if(brush.GetType().Equals(typeof(FlowChartX.TextureBrush)))
			{
				FlowChartX.TextureBrush bb =
					(FlowChartX.TextureBrush)brush;

				writer.WriteAttributeString("Type", "Texture");

				writer.WriteElementString("WrapMode",
					bb.WrapMode.ToString());
				writer.WriteElementString("Image",
					Version >= 4 ? XmlConvert.FromImageV4(bb.Image) :
						XmlConvert.FromImage(bb.Image));
			}

			writer.WriteEndElement();
		}
コード例 #17
0
ファイル: XmlWriter.cs プロジェクト: ChrisMoreton/Test3
		private void WriteBrushRefElement(System.Xml.XmlWriter writer,
			FlowChartX.Brush brush, string element, SortedList brushes)
		{
			writer.WriteStartElement(element);
			if(brush != null)
			{
				int bi = brushes.IndexOfValue(brush);

				writer.WriteAttributeString("Id",
					XmlConvert.FromInt32((int)brushes.GetKey(bi)));
			}
			else
			{
				writer.WriteAttributeString("Id", "-1");
			}
			writer.WriteEndElement();
		}
コード例 #18
0
ファイル: SortedList.cs プロジェクト: ForNeVeR/pnet
 public int IndexOf(Object value)
 {
     return(list.IndexOfValue(value));
 }
コード例 #19
0
ファイル: AuthorityForm.aspx.cs プロジェクト: chanhan/Project
        private string CreateFunctionList(string strFunctionList, string strFunctionListed, string strAuthorized)
        {
            string SValue = "";
               //     if ((strFunctionList.Length <= 0) || !strAuthorized.Equals("Y"))
                if ((strFunctionList.Length <= 0))

            {
                return SValue;
            }
            if (strFunctionListed.Length > 0)
            {
                int i;
                SortedList SortedFunctionListed = new SortedList();
                string[] arrB = strFunctionListed.Split(new char[] { ',' });
                for (i = 0; i < arrB.Length; i++)
                {
                    SortedFunctionListed.Add(SortedFunctionListed.Count, arrB[i]);
                }
                string[] arrA = strFunctionList.Split(new char[] { ',' });
                for (i = 0; i < arrA.Length; i++)
                {
                    if (SortedFunctionListed.IndexOfValue(arrA[i].ToString()) >= 0)
                    {
                        SValue = SValue + "<font color=red>" + arrA[i].ToString() + "</font>,";
                    }
                    else
                    {
                        SValue = SValue + "<font color=grey>" + arrA[i].ToString() + "</font>,";
                    }
                }
                return ("(" + SValue.TrimEnd(new char[] { ',' }) + ")");
            }
            return ("(<font color=grey>" + strFunctionList.TrimEnd(new char[] { ',' }) + "</font>)");
        }
コード例 #20
0
	public void TestIndexOfValue() {
		SortedList sl1 = new SortedList(24);
		string s=null;
		for (int i = 0; i < 50; i++) {
			s=string.Format("{0:D2}", i); 
			sl1.Add("kala "+s,100+i*i);
		}
		for (int i = 0; i < 50; i++) {
			s=string.Format("{0:D2}", i+50); 
			sl1.Add("kala "+s,100+i*i);
		}
		AssertEquals("sl.IndexOfValue: does not return -1 for non-existing value(1)", -1, sl1.IndexOfValue(102));
		AssertEquals("sl.IndexOfValue: does not return -1 for non-existing value(2)", -1, sl1.IndexOfValue(null));
		for (int i=0; i<50; i++) {
			AssertEquals("sl.IndexOfValue: incorrect index key", i, sl1.IndexOfValue(100+i*i));
		}
	}
コード例 #21
0
ファイル: IndexOfValueTests.cs プロジェクト: johnhhm/corefx
        public void TestIndexOfValueBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            //

            SortedList sl2 = null;

            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            string s1 = null;
            string s2 = null;
            string s3 = null;
            string s4 = null;

            int i = 0;
            int j = 0;
            //
            // 	Constructor: Create SortedList using this as IComparer and default settings.
            //
            sl2 = new SortedList(this);

            //  Verify that the SortedList is not null.
            Assert.NotNull(sl2);

            //  Verify that the SortedList is empty.
            Assert.Equal(0, sl2.Count);

            //  with null - should return -1
            // null val
            j = sl2.IndexOfValue((string)null);
            Assert.Equal(-1, j);

            //  invalid val - should return -1
            j = sl2.IndexOfValue("No_Such_Val");
            Assert.Equal(-1, j);

            // null is a valid value
            sl2.Add("Key_0", null);
            j = sl2.IndexOfValue(null);
            Assert.NotEqual(-1, j);

            // first occurrence check
            sl2.Add("Key_1", "Val_Same");
            sl2.Add("Key_2", "Val_Same");

            j = sl2.IndexOfValue("Val_Same");
            Assert.Equal(1, j);

            sl2.Clear();

            //   Testcase: add few key-val pairs
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

            //
            //   Testcase: test IndexOfVal 
            //
            for (i = 0; i < sl2.Count; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_"); //key
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_"); //value
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                //  now use IndexOfKey and IndexOfVal to obtain the same object and check
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object
                s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object
                Assert.True(s3.Equals(s4));

                // now Get using the index obtained thru IndexOfKey () and compare it with s2
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1));
                Assert.True(s3.Equals(s2));
            }

            //
            // Remove a key and then check
            //
            sblMsg.Length = 0;
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            sl2.Remove(s1); //removes "Key_50"
            j = sl2.IndexOfValue(s1);
            Assert.Equal(-1, j);
        }
コード例 #22
0
ファイル: GetByIndexITests.cs プロジェクト: johnhhm/corefx
        public void TestGetByIndexBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            //

            SortedList sl2 = null;

            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            string s1 = null;
            string s2 = null;
            string s3 = null;
            string s4 = null;

            int i = 0;
            //
            // 	Constructor: Create SortedList using this as IComparer and default settings.
            //
            sl2 = new SortedList(this);

            //  Verify that the SortedList is not null.
            Assert.NotNull(sl2);

            //  Verify that the SortedList is empty.
            Assert.Equal(0, sl2.Count);

            //   Testcase: Boundary - invalid index
            Assert.Throws<ArgumentOutOfRangeException>(() =>
                             {
                                 s3 = (string)sl2.GetByIndex(-1);    // index == -ve
                             }
            );

            Assert.Throws<ArgumentOutOfRangeException>(() =>
                             {
                                 s3 = (string)sl2.GetByIndex(0); // index == sl2.GetCount ()
                             }
            );

            //   Testcase: add few key-val pairs
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

            //
            //   Testcase: test Get (Object)
            //
            for (i = 0; i < sl2.Count; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_"); //key
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_"); //value
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                //  now use IndexOfKey and IndexOfVal to obtain the same object and check
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object
                s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object
                Assert.True(s3.Equals(s4));

                //  now Get using the index obtained thru IndexOfKey () and compare it with s2
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1));
                Assert.True(s3.Equals(s2));
            }

            //
            // Remove a key and then check
            //
            sblMsg.Length = 0;
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            sl2.Remove(s1); //removes "Key_50"
            int j = sl2.IndexOfKey(s1);
            Assert.Equal(-1, j);

            Assert.Throws<ArgumentOutOfRangeException>(() =>
                             {
                                 s3 = (string)sl2.GetByIndex(j); // j = -1 //means the key is not found
                             }
            );

            Assert.Throws<ArgumentOutOfRangeException>(() =>
                             {
                                 s3 = (string)sl2.GetByIndex(sl2.Count);
                             }
            );

            Assert.Throws<ArgumentOutOfRangeException>(() =>
                             {
                                 s3 = (string)sl2.GetByIndex(sl2.Count + 1);
                             }
            );
        }
コード例 #23
0
		private TreeNode SetupMetadataFilesNode(TreeNode projectNode) {
			
			TreeNode metadataFilesNode = GetContextNode(_project.MetadataFiles, tvwProject.Nodes);
			SortedList sortedItems = new SortedList();
			
			if (metadataFilesNode == null) {
				metadataFilesNode = projectNode.Nodes.Add("Metadata Files");
			}
			
			//TreeNode metadataFilesNode = projectNode.Nodes.Add("Metadata Files");
			metadataFilesNode.ImageIndex = Images.Indexes.FolderOpen;
			metadataFilesNode.SelectedImageIndex = Images.Indexes.FolderOpen;
			metadataFilesNode.Tag = _project.MetadataFiles;
			//metadataFilesNode.Nodes.Clear();
			
			foreach (MetadataFile file in _project.MetadataFiles) {
				TreeNode node = GetContextNode(file, metadataFilesNode.Nodes);
				if (node == null) {
					node = new TreeNode();
				}
//				try 
//				{
					node.Tag = file;
					node.Text = file.Name;
					if (File.Exists(file.FullPath) && !sortedItems.ContainsKey(node.Text))
					{
						sortedItems.Add(node.Text, node);
						node.ImageIndex = Images.Indexes.DocumentText;
						node.SelectedImageIndex = Images.Indexes.DocumentText;
					}
					else
					{
						if (sortedItems.ContainsKey(node.Text))
						{
							node.Text = file.Name + " [duplicate 1]" + ERROR_MESSAGE_1;
						}
						else
						{
							node.Text = file.Name + ERROR_MESSAGE_1;
						}
						int i = 1;
						while (sortedItems.ContainsKey(node.Text))
						{
							node.Text = file.Name + string.Format(" [duplicate {0}]", i++) + ERROR_MESSAGE_1;
						}
						sortedItems.Add(node.Text, node);
						node.ImageIndex = Images.Indexes.Delete;
						node.SelectedImageIndex = Images.Indexes.Delete;
					}
//				}
//				catch
//				{
//					if (node == null)
//						node = new TreeNode(file.Name);
//				}
			}
			if (Directory.Exists(_project.GetFullMetadataPath())) 
			{
				string[] files = Directory.GetFiles(_project.GetFullMetadataPath(), "*.xml");
				foreach (string file in files) 
				{
					if (!_project.MetadataFiles.Contains(file)) 
					{
						TreeNode node = new TreeNode(Path.GetFileName(file));
						node.ImageIndex = Images.Indexes.DocumentText + Images.Count;
						node.SelectedImageIndex = Images.Indexes.DocumentText + Images.Count;
						node.Tag = new MetadataFilePlaceholder(Path.GetFileName(file), file);
						sortedItems.Add(Path.GetFileName(file), node);
					}
				}
			}
			for (int i = metadataFilesNode.Nodes.Count - 1; i >= 0; i--)
			{
				TreeNode node = metadataFilesNode.Nodes[i];
				if (sortedItems.IndexOfValue(node) < 0)
				{
					metadataFilesNode.Nodes.Remove(node);
				}
			}
//			foreach (TreeNode node in metadataFilesNode.Nodes)
//			{
//				if (
//					node.Tag != null && node.Tag is MetadataFile &&
//					!_project.MetadataFiles.Contains((MetadataFile) node.Tag)) 
//				{
//					node.Remove();
//				}
//			}
			foreach (DictionaryEntry entry in sortedItems)
			{
				TreeNode node = (TreeNode)entry.Value;
				int index = metadataFilesNode.Nodes.IndexOf(node);
				if (index >= 0 && index != sortedItems.IndexOfValue(node))
				{
					metadataFilesNode.Nodes.Remove(node);
				}
				TreeNode contextNode = GetContextNode(node.Tag, metadataFilesNode.Nodes);
				if (contextNode == null)
				{
					metadataFilesNode.Nodes.Insert(sortedItems.IndexOfValue(node), node);
				}
				if (node.Text.IndexOf("ERROR LOADING FILE") > 0)
					node.Parent.Expand();	
			}
			
			return metadataFilesNode;
		}