GetKey() public method

public GetKey ( int index ) : Object
index int
return Object
コード例 #1
0
        /// <summary>
        /// Returns a portion of the list whose keys are greater that the lowerLimit parameter less than the upperLimit parameter.
        /// </summary>
        /// <param name="l">The list where the portion will be extracted.</param>
        /// <param name="limit">The start element of the portion to extract.</param>
        /// <param name="limit">The end element of the portion to extract.</param>
        /// <returns>The portion of the collection.</returns>
        public static System.Collections.SortedList SubMap(System.Collections.SortedList list, System.Object lowerLimit, System.Object upperLimit)
        {
            System.Collections.Comparer   comparer = System.Collections.Comparer.Default;
            System.Collections.SortedList newList  = new System.Collections.SortedList();

            if (list != null)
            {
                if ((list.Count > 0) && (!(lowerLimit.Equals(upperLimit))))
                {
                    int index = 0;
                    while (comparer.Compare(list.GetKey(index), lowerLimit) < 0)
                    {
                        index++;
                    }

                    for (; index < list.Count; index++)
                    {
                        if (comparer.Compare(list.GetKey(index), upperLimit) >= 0)
                        {
                            break;
                        }

                        newList.Add(list.GetKey(index), list[list.GetKey(index)]);
                    }
                }
            }

            return(newList);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: ruarrimactire/Hodei
        static void Main(string[] args)
        {
            SortedList traductor = new SortedList();
            traductor.Add("{", "begin");
            traductor.Add("}", "begin");
            traductor.Add("WriteLine", "WriteLn");
            traductor.Add("ReadLine", "ReadLn");
            traductor.Add("void", "procedure");
            traductor.Add("Console", "");

            //StreamReader fichero_origen;
            //fichero_origen = File.OpenText("prueba.cs");
            List<string> lista = File.ReadAllLines("prueba.cs").ToList();
            //fichero_origen.Close();
            string itemaux = "";
            foreach (string item in lista)
            {
                itemaux = item;
                for (int i = 0; i < traductor.Count; i++)
                {
                    if (item.Contains(traductor.GetKey(i).ToString()))
                        itemaux = item.Replace(traductor.GetKey(i).ToString(), traductor.GetByIndex(i).ToString());
                }
                Console.WriteLine(itemaux);
            }
        }
コード例 #3
0
ファイル: PdfFlattenVisitor.cs プロジェクト: GorelH/PdfSharp
    internal override void VisitDocumentElements(DocumentElements elements)
    {
      SortedList splitParaList = new SortedList();

      for (int idx = 0; idx < elements.Count; ++idx)
      {
        Paragraph paragraph = elements[idx] as Paragraph;
        if (paragraph != null)
        {
          Paragraph[] paragraphs = paragraph.SplitOnParaBreak();
          if (paragraphs != null)
            splitParaList.Add(idx, paragraphs);
        }
      }

      int insertedObjects = 0;
      for (int idx = 0; idx < splitParaList.Count; ++idx)
      {
        int insertPosition = (int)splitParaList.GetKey(idx);
        Paragraph[] paragraphs = (Paragraph[])splitParaList.GetByIndex(idx);
        foreach (Paragraph paragraph in paragraphs)
        {
          elements.InsertObject(insertPosition + insertedObjects, paragraph);
          ++insertedObjects;
        }
        elements.RemoveObjectAt(insertPosition + insertedObjects);
        --insertedObjects;
      }
    }
コード例 #4
0
ファイル: ArraysAlgo.cs プロジェクト: zhouhufeng/Algo
 // use a max heap (priority queue) of size k
 // (C# doesn't provide priority queue, use SortedList instead)
 public static int KthSmallest(int[] a, int k)
 {
     SortedList list = new SortedList();
     int m = a.Length - k + 1;
     for (int i = 0; i < m; i++)
         list.Add(a[i], null);
     for (int i = m; i < a.Length; i++)
     {
         if ((int)list.GetKey(0) < a[i])
         {
             list.RemoveAt(0);
             list.Add(a[i], null);
         }
     }
     return (int)list.GetKey(0);
 }
コード例 #5
0
        /// <summary>
        /// Returns a list of data source names from the local machine.
        /// </summary>
        public SortedList GetAllDataSourceNames()
        {
            // Get the list of user DSN's first.
            System.Collections.SortedList dsnList = GetUserDataSourceNames();

            // Get list of System DSN's and add them to the first list.
            System.Collections.SortedList systemDsnList = GetSystemDataSourceNames();
            for (int i = 0; i < systemDsnList.Count; i++)
            {
                string         sName = systemDsnList.GetKey(i) as string;
                DataSourceType type  = (DataSourceType)systemDsnList.GetByIndex(i);
                try
                {
                    // This dsn to the master list
                    dsnList.Add(sName, type);
                }
                catch
                {
                    // An exception can be thrown if the key being added is a duplicate so
                    // we just catch it here and have to ignore it.
                }
            }

            return(dsnList);
        }
コード例 #6
0
        /// <summary>
        /// Returns a portion of the list whose keys are less than the limit object parameter.
        /// </summary>
        /// <param name="l">The list where the portion will be extracted.</param>
        /// <param name="limit">The end element of the portion to extract.</param>
        /// <returns>The portion of the collection whose elements are less than the limit object parameter.</returns>
        public static System.Collections.SortedList HeadMap(System.Collections.SortedList l, System.Object limit)
        {
            System.Collections.Comparer   comparer = System.Collections.Comparer.Default;
            System.Collections.SortedList newList  = new System.Collections.SortedList();

            for (int i = 0; i < l.Count; i++)
            {
                if (comparer.Compare(l.GetKey(i), limit) >= 0)
                {
                    break;
                }

                newList.Add(l.GetKey(i), l[l.GetKey(i)]);
            }

            return(newList);
        }
コード例 #7
0
 public virtual Object this[int index] {
     get {
         return(sortedList.GetKey(index));
     }
     set {
         throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
     }
 }
コード例 #8
0
 public virtual object this [int index] {
     get {
         return(host.GetKey(index));
     }
     set {
         throw new NotSupportedException("attempt to modify a key");
     }
 }
コード例 #9
0
 public virtual Object this[int index] {
     get {
         return(sortedList.GetKey(index));
     }
     set {
         throw new NotSupportedException("NotSupported_KeyCollectionSet");
     }
 }
コード例 #10
0
        /// <summary>
        /// The main entry point of the application - does all the work, really.
        /// </summary>
        public static void Main()
        {
            SortedList table = new SortedList();
            string fileData = string.Empty;

            Console.WriteLine("This program counts how many times each word occurs in a file.");
            Console.Write("Enter the filename of the file to read from:\n > ");
            string filename = Console.ReadLine();
            while (string.IsNullOrEmpty(filename))
            {
                Console.Write("You cannot enter a blank path name - try again:\n > ");
                filename = Console.ReadLine();
            }

            // Try to access the file and bail out if an error occurred
            try
            {
                fileData = File.ReadAllText(filename);
            }
            catch
            {
                Console.WriteLine("File was not accessible. Please make sure it exists and you have appropriate permission to read it.");
                return;
            }

            // Get the file contents, convert to lowercase and remove all non-alpha and non-space characters,
            // then get a raw array (still contains duplicates) of all the words
            string[] rawWordArray = WordCountExampleProgram.GetWordsArray(fileData.ToLower());

            // For each for in the array...
            for (int i = 0; i < rawWordArray.Length; i++)
            {
                if (!table.ContainsKey(rawWordArray[i]))
                {
                    // If the table does not already contain the key, add it to the list with a count of 1
                    table.Add(rawWordArray[i], 1);
                }
                else
                {
                    // Otherwise it was already in the table, increment its previous count by one
                    table[rawWordArray[i]] = Convert.ToInt32(table[rawWordArray[i]]) + 1;
                }
            }

            // Make a variable to count total words
            int totalWords = 0;

            // Print out the key and value of each along with some headers
            Console.WriteLine("\nWord" + string.Empty.PadRight(50 - "Word".Length, ' ') + "Count\n" + string.Empty.PadRight(50 + "Count".Length, '-'));
            for (int i = 0; i < table.Count; i++)
            {
                int value = Convert.ToInt32(table.GetByIndex(i));
                totalWords += value;
                Console.WriteLine(String.Format("{0,-50}{1}", table.GetKey(i), value));
            }

            Console.WriteLine("{0,-50}{1}\n", "TOTAL", totalWords);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: oblivious/Oblivious
 public static void PrintKeysAndValues(SortedList myList)
 {
     Console.WriteLine("\t-KEY-\t-VALUE-");
     for (int i = 0; i < myList.Count; i++)
     {
         Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i));
     }
     Console.WriteLine();
 }
コード例 #12
0
        public void SortedList()
        {
            var list = new SortedList();
            list.Add(5, "Matteo");
            list.Add(4, DateTime.UtcNow);
            list.Add(1, "Pierangeli");

            var firstPosition = list.GetKey(0);
            Assert.That(list[firstPosition], Is.EqualTo("Pierangeli"));
        }
コード例 #13
0
ファイル: SortedList.cs プロジェクト: theolivenbaum/h5
 public virtual object this[int index]
 {
     get
     {
         return(sortedList.GetKey(index));
     }
     set
     {
         throw new NotSupportedException();
     }
 }
コード例 #14
0
ファイル: SortedList.cs プロジェクト: moayyaed/runtime
 public object?this[int index]
 {
     get
     {
         return(sortedList.GetKey(index));
     }
     set
     {
         throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
     }
 }
コード例 #15
0
ファイル: SortedList.cs プロジェクト: ForNeVeR/pnet
 public Object this[int index]
 {
     get
     {
         return(list.GetKey(index));
     }
     set
     {
         throw new InvalidOperationException
                   (_("Invalid_ReadOnly"));
     }
 }
コード例 #16
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)
				{
				}
			}
		}
コード例 #17
0
        public void DisplayEmployeesNameAge()
        {
            System.Collections.SortedList nameAge = new System.Collections.SortedList();
            nameAge.Add("Alicia", 30);
            nameAge.Add("Mike", 29);
            nameAge.Add("Adam", 22);
            nameAge.Add("Andrew", 39);


            for (int i = 0; i < nameAge.Count; i++)
            {
                Console.WriteLine("{0}: {1}", nameAge.GetKey(i), nameAge.GetByIndex(i));
            }
        }
コード例 #18
0
 static public int GetKey(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         System.Int32 a1;
         checkType(l, 2, out a1);
         var ret = self.GetKey(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #19
0
        public void fun3()
        {
            SortedList s1 = new SortedList();
            s1.Add(9, 'a');
            s1.Add(5, 'f');
            s1.Add(7, 'h');

            Console.WriteLine(s1.GetKey(0));
            Console.WriteLine(s1.GetByIndex(0));

            foreach (DictionaryEntry de in s1)
            {
                Console.WriteLine("key ={0} value = {1}", de.Key, de.Value);
            }
        }
コード例 #20
0
ファイル: SupportClass.cs プロジェクト: karino2/wikipediaconv
    public static System.Collections.SortedList TailMap(System.Collections.SortedList list, System.Object limit)
    {
        System.Collections.Comparer   comparer = System.Collections.Comparer.Default;
        System.Collections.SortedList newList  = new System.Collections.SortedList();

        if (list != null)
        {
            if (list.Count > 0)
            {
                int index = 0;
                while (comparer.Compare(list.GetKey(index), limit) < 0)
                {
                    index++;
                }

                for (; index < list.Count; index++)
                {
                    newList.Add(list.GetKey(index), list[list.GetKey(index)]);
                }
            }
        }

        return(newList);
    }
コード例 #21
0
ファイル: Program.cs プロジェクト: anuragbhd/code
        static void Main(string[] args)
        {
            SortedList mySL = new SortedList();
            mySL.Add("One", "1");
            mySL.Add("Two", "2");
            mySL.Add("Three", "3");

            // Result will be displayed in sorted order as all keys are auto stored in sorted order
            System.Console.WriteLine("KEY\tVALUE");
            System.Console.WriteLine("---\t-----");
            for (int i = 0; i < mySL.Count; i++)
            {
                System.Console.WriteLine("{0}\t{1}", mySL.GetKey(i), mySL.GetByIndex(i));
            }
            System.Console.WriteLine("\nCapacity of this SortedList: {0}", mySL.Capacity);
            System.Console.WriteLine("Does this SortedList contain \"One\" as key: {0}", mySL.Contains("One"));
            System.Console.WriteLine("Number of objects presently in this SortedList: {0}", mySL.Count);
            System.Console.ReadLine();
        }
コード例 #22
0
ファイル: frmMain_wh.cs プロジェクト: EdgarEDT/myitoppsp
        void tlVectorControl1_RightClick(object sender, ItopVector.DrawArea.SvgElementSelectedEventArgs e)
        {
            sel_sym = "";
            sel_start_point = "";
            try {
                if (csOperation == CustomOperation.OP_MeasureDistance) {
                    tlVectorControl1.Operation = ToolOperation.Select;
                    contextMenuStrip1.Hide();
                    return;
                }
                //tlVectorControl1.DocumentSize = new SizeF(3170f, 2540f);
                //MessageBox.Show(MapType);
                tmLineConnect.Visible = false;
                SvgElementCollection elements = tlVectorControl1.SVGDocument.SelectCollection;
                if (elements.Count == 2) {
                    Polyline pl1 = elements[0] as Polyline;
                    Polyline pl2 = elements[1] as Polyline;
                    if (pl1 != null && pl2 != null && pl1.GetAttribute("IsLead") != "" && pl2.GetAttribute("IsLead") != "") {

                        tmLineConnect.Visible = true;
                    }
                }
                if (MapType == "接线图") {
                    tip.Hide();
                    if (getlayer(SvgDocument.currentLayer, "背景层", tlVectorControl1.SVGDocument.getLayerList())) {
                        contextMenuStrip1.Enabled = false;
                    } else {
                        contextMenuStrip1.Enabled = true;
                    }

                    if (tlVectorControl1.SVGDocument.CurrentElement == null ||
                       tlVectorControl1.SVGDocument.CurrentElement.GetType().ToString() != "ItopVector.Core.Figure.Use") {
                        moveMenuItem.Visible = false;
                        jxtToolStripMenuItem.Visible = false;
                        w3MenuItem.Visible = false;

                    } else {
                        if (tlVectorControl1.SVGDocument.CurrentElement.GetAttribute("xlink:href").Contains("Substation")) {
                            moveMenuItem.Visible = true;
                            jxtToolStripMenuItem.Visible = true;
                            w3MenuItem.Visible = true;
                        }
                    }
                    if (show3d == 0) {
                        w3MenuItem.Visible = false;
                    }
                    if (tlVectorControl1.SVGDocument.CurrentElement == null &&
                      tlVectorControl1.SVGDocument.CurrentElement.GetType().ToString() != "ItopVector.Core.Figure.RectangleElement" &&
                      tlVectorControl1.SVGDocument.CurrentElement.GetType().ToString() != "ItopVector.Core.Figure.Polygon") {
                        printToolStripMenuItem.Visible = false;
                        toolDel.Visible = false;
                        SubToolStripMenuItem.Visible = false;
                    } else {
                        printToolStripMenuItem.Visible = true;
                        toolDel.Visible = true;
                        SubToolStripMenuItem.Visible = false;
                        saveImg.Visible=true;

                    }
                    if (tlVectorControl1.SVGDocument.CurrentElement != null && tlVectorControl1.SVGDocument.CurrentElement.GetType().ToString() == "ItopVector.Core.Figure.Polyline") {
                        mUpdateMenuItem.Visible = true;
                    } else {
                        mUpdateMenuItem.Visible = false;
                    }
                    string guid = Guid.NewGuid().ToString();
                    if (tlVectorControl1.Operation == ToolOperation.LeadLine && linekey != "") {
                        string str = "";

                        LineList1 line1 = new LineList1();
                        line1.UID = Guid.NewGuid().ToString();
                        line1.LineEleID = tlVectorControl1.SVGDocument.CurrentElement.ID;
                        line1.PointNum = ((Polyline)(tlVectorControl1.SVGDocument.CurrentElement)).Points.Length - 2;
                        line1.Coefficient = (decimal)(1.02);
                        line1.Length = TLMath.getPolylineLength(((Polyline)(tlVectorControl1.SVGDocument.CurrentElement)), Convert.ToDecimal(tlVectorControl1.ScaleRatio));
                        line1.Length2 = TLMath.getPolylineLength(((Polyline)(tlVectorControl1.SVGDocument.CurrentElement)), Convert.ToDecimal(tlVectorControl1.ScaleRatio)) * Convert.ToDecimal(1.02);
                        PointF[] pnt = ((Polyline)(tlVectorControl1.SVGDocument.CurrentElement)).Points;
                        if (pnt.Length < 3) return;
                        for (int i = 0; i < pnt.Length; i++) {
                            double ang = TLMath.getLineAngle(pnt[i], pnt[i + 1], pnt[i + 2]);
                            if (ang * 57.3 > 60) {
                                MessageBox.Show("线路转角不能大于60度。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                tlVectorControl1.Delete();
                                return;
                            }
                            str = str + "第" + (i + 1) + "转角:" + Convert.ToDouble(ang * 57.3).ToString("##.##") + "度。\r\n";
                            if (i == pnt.Length - 3) {
                                break;
                            }
                        }
                        line1.TurnAngle = str;
                        line1.col1 = linekey;
                        frmInputDialog input = new frmInputDialog();
                        if (input.ShowDialog() == DialogResult.OK) {
                            line1.LineName = input.InputStr;
                            Services.BaseService.Create<LineList1>(line1);
                        } else {
                            tlVectorControl1.Delete();
                        }
                        linekey = "";

                    }
                    if (tlVectorControl1.Operation == ToolOperation.InterEnclosure && !SubPrint) {

                        System.Collections.SortedList list = new SortedList();
                        decimal s = 0;
                        ItopVector.Core.SvgElementCollection selCol = tlVectorControl1.SVGDocument.SelectCollection;
                        if (selCol.Count > 1) {
                            decimal ViewScale = 1;
                            string str_Scale = tlVectorControl1.SVGDocument.getViewScale();
                            if (str_Scale != "") {
                                ViewScale = Convert.ToDecimal(str_Scale);
                            }
                            string str_remark = "";
                            string str_selArea = "";
                            //string Elements = "";
                            Hashtable SelAreaCol = new Hashtable();
                            this.Cursor = Cursors.WaitCursor;
                            int t = 0;
                        Lab001:
                            t = t + 1;
                            XmlElement poly1 = (XmlElement)selCol[selCol.Count - t];
                            if (poly1.GetType().FullName != "ItopVector.Core.Figure.Polygon") {
                                // selCol.Remove(selCol[selCol.Count-1]);
                                goto Lab001;
                            }
                            frmWaiting wait = new frmWaiting();
                            wait.Show(this);
                            wait.Refresh();

                            GraphicsPath gr1 = new GraphicsPath();
                            //gr1.AddRectangle(TLMath.getRectangle(poly1));
                            gr1.AddPolygon(TLMath.getPolygonPoints(poly1));
                            gr1.CloseFigure();

                            for (int i = 0; i < selCol.Count - 1; i++) {
                                if (selCol[i].GetType().FullName == "ItopVector.Core.Figure.Polygon") {

                                    string IsArea = ((XmlElement)selCol[i]).GetAttribute("IsArea");
                                    if (IsArea != "") {
                                        XmlElement polyn = (XmlElement)selCol[i];
                                        GraphicsPath gr2 = new GraphicsPath();
                                        //gr2.AddRectangle(TLMath.getRectangle(polyn));
                                        gr2.AddPolygon(TLMath.getPolygonPoints(polyn));
                                        gr2.CloseFigure();
                                        Region region = new Region(gr1);
                                        region.Intersect(gr2);

                                        RectangleF rect = new RectangleF();
                                        rect = tlVectorControl1.SelectedRectangle(region);

                                        decimal sub_s = TLMath.getInterPolygonArea(region, rect, ViewScale);
                                        sub_s = TLMath.getNumber2(sub_s, tlVectorControl1.ScaleRatio);
                                        SelAreaCol.Add(polyn.GetAttribute("id"), sub_s);
                                        glebeProperty _gleProp = new glebeProperty();
                                        _gleProp.EleID = polyn.GetAttribute("id");
                                        _gleProp.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                                        IList gList = Services.BaseService.GetList("SelectglebePropertyByEleID", _gleProp);

                                        if (gList.Count > 0) {
                                            _gleProp = (glebeProperty)gList[0];
                                            list.Add(_gleProp.UseID, sub_s.ToString("#####.####"));
                                            str_selArea = str_selArea + _gleProp.EleID + "," + sub_s.ToString("#####.####") + ";";
                                            //str_remark = str_remark + "地块" + _gleProp.UseID + "选中面积为:" + sub_s.ToString() + "\r\n";
                                            s += sub_s;
                                        }
                                    }
                                }
                                if (selCol[i].GetType().FullName == "ItopVector.Core.Figure.Use") {
                                    XmlElement e1 = (XmlElement)selCol[i];
                                    string str_id = e1.GetAttribute("id");

                                    substation _sub1 = new substation();
                                    _sub1.EleID = str_id;
                                    _sub1.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                                    _sub1 = (substation)Services.BaseService.GetObject("SelectsubstationByEleID", _sub1);
                                    if (_sub1 != null) {
                                        _sub1.glebeEleID = guid;
                                        Services.BaseService.Update("Updatesubstation", _sub1);
                                    }

                                }

                            }
                            decimal nullpoly = TLMath.getNumber2(TLMath.getPolygonArea(TLMath.getPolygonPoints(poly1), 1), tlVectorControl1.ScaleRatio) - s;

                            for (int j = 0; j < list.Count; j++) {
                                if (Convert.ToString(list.GetByIndex(j)) != "") {
                                    if (Convert.ToDecimal(list.GetByIndex(j)) < 1) {
                                        str_remark = str_remark + "地块" + list.GetKey(j).ToString() + "选中面积为:" + "0" + list.GetByIndex(j).ToString() + "(KM²)\r\n";
                                    } else {
                                        str_remark = str_remark + "地块" + list.GetKey(j).ToString() + "选中面积为:" + list.GetByIndex(j).ToString() + "(KM²)\r\n";
                                    }
                                }
                            }
                            XmlElement x1 = poly1;// (XmlElement)selCol[selCol.Count - 1];

                            gPro.UID = guid;
                            gPro.EleID = x1.GetAttribute("id");
                            gPro.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                            gPro.ParentEleID = "0";
                            if (s != 0) {
                                gPro.Area = Convert.ToDecimal(s.ToString("#####.####"));
                            } else {
                                gPro.Area = 0;
                            }
                            gPro.SelSonArea = str_selArea;

                            if (nullpoly < 1) {
                                gPro.ObligateField10 = "0" + nullpoly.ToString("#####.####");
                            } else {
                                gPro.ObligateField10 = nullpoly.ToString("#####.####");
                            }

                            str_remark = str_remark + "\r\n 空白区域面积" + gPro.ObligateField10 + "(KM²)\r\n";
                            if (str_remark != "") {
                                str_remark = str_remark.Substring(0, str_remark.Length - 2);
                            }

                            gPro.Remark = str_remark;
                            wait.Close();
                            this.Cursor = Cursors.Default;
                            if (s < 1) {
                                MessageBox.Show("选中区域面积:" + "0" + s.ToString("#####.####") + "(KM²)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            } else {
                                MessageBox.Show("选中区域面积:" + s.ToString("#####.####") + "(KM²)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }

                            Services.BaseService.Create<glebeProperty>(gPro);

                            IDictionaryEnumerator ISelList = SelAreaCol.GetEnumerator();
                            while (ISelList.MoveNext()) {
                                glebeProperty sub_gle = new glebeProperty();
                                sub_gle.EleID = ISelList.Key.ToString();
                                sub_gle.ParentEleID = gPro.EleID;
                                sub_gle.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                                Services.BaseService.Update("UpdateglebePropertySelArea", sub_gle);
                            }

                            tlVectorControl1.SVGDocument.SelectCollection.Clear();
                            tlVectorControl1.SVGDocument.CurrentElement = (SvgElement)x1;
                        }
                        SubPrint = false;
                    }
                    if (tlVectorControl1.CurrentOperation == ToolOperation.InterEnclosure && SubPrint) {
                        //ItopVector.Core.SvgElementCollection selCol = tlVectorControl1.SVGDocument.SelectCollection;
                        //if(selCol.Count>2){
                        //    XmlElement selArea = (SvgElement)selCol[selCol.Count - 1];

                        //    GraphicsPath gr1 = new GraphicsPath();
                        //    gr1.AddPolygon(TLMath.getPolygonPoints(selArea));
                        //    gr1.CloseFigure();
                        //    RectangleF rect= gr1.GetBounds();

                        //    SvgDocument _doc = new SvgDocument();
                        //    string svgtxt = "<?xml version=\"1.0\" encoding=\"utf-8\"?><svg id=\"svg\" width=\""+rect.Width+"\" height=\""+rect.Height+"\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:itop=\"http://www.Itop.com/itop\">";

                        //    for (int n = 0; n < selCol.Count-1;n++ )
                        //    {
                        //        //_doc.AppendChild((XmlNode)selCol[n]);
                        //        svgtxt=svgtxt+((XmlElement)selCol[n]).OuterXml+"\r\n";
                        //    }
                        //    svgtxt = svgtxt + "</svg>";
                        //    _doc.LoadXml(svgtxt);
                        //    frmSubPrint s = new frmSubPrint();
                        //    s.Show();
                        //    s.Open(_doc, rect);
                        ItopVector.Core.SvgElementCollection selCol = tlVectorControl1.SVGDocument.SelectCollection;
                        XmlElement x1 = (XmlElement)selCol[selCol.Count - 1];
                        tlVectorControl1.SVGDocument.SelectCollection.Clear();
                        tlVectorControl1.SVGDocument.CurrentElement = (SvgElement)x1;
                        SubPrint = false;
                        //}
                    }
                    if (tlVectorControl1.Operation == ToolOperation.Enclosure) {

                        string Elements = "";
                        ItopVector.Core.SvgElementCollection selCol = tlVectorControl1.SVGDocument.SelectCollection;

                        for (int i = 0; i < selCol.Count - 1; i++) {
                            XmlElement e1 = (XmlElement)selCol[i];
                            Elements = Elements + "'" + e1.GetAttribute("id") + "',";
                        }
                        if (Elements.Length > 0) {
                            Elements = Elements.Substring(0, Elements.Length - 1);
                        }
                        XmlElement x1 = (XmlElement)selCol[selCol.Count - 1];

                        gPro.UID = Guid.NewGuid().ToString();
                        gPro.EleID = x1.GetAttribute("id");

                        gPro.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                        gPro.SonUid = Elements;
                        Services.BaseService.Create<glebeProperty>(gPro);

                        tlVectorControl1.SVGDocument.SelectCollection.Clear();
                        tlVectorControl1.SVGDocument.CurrentElement = (SvgElement)x1;

                    }
                    if (tlVectorControl1.CurrentOperation == ToolOperation.LeadLine) {
                        sgt1.Visible = false;
                    }
                }
            } catch (Exception e1) {
                MessageBox.Show(e1.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tlVectorControl1.SVGDocument.SelectCollection.Clear();
            } finally {
                tlVectorControl1.Operation = ToolOperation.Select;
                tlVectorControl1.Operation = ToolOperation.FreeTransform;

            }
        }
コード例 #23
0
        private ArrayList calculateSpline(SortedList points)
        {
            int n = points.Count - 1;
            double[] x = new double[n + 1];
            double[] a = new double[n + 1];
            double[] b = new double[n];
            double[] d = new double[n];
            double[] h = new double[n];
            double[] alpha = new double[n];
            double[] c = new double[n + 1];
            double[] l = new double[n + 1];
            double[] mu = new double[n + 1];
            double[] z = new double[n + 1];
            ArrayList spline = new ArrayList();

            for (int i = 0; i <= n; i++)
            {
                x[i] = Convert.ToDouble(points.GetKey(i));
                a[i] = Convert.ToDouble(points.GetByIndex(i));
            }

            for (int i = 0; i <= n - 1; i++)
            {
                h[i] = x[i + 1] - x[i];
            }

            for (int i = 1; i <= n - 1; i++)
            {
                alpha[i] = 3 / h[i] * (a[i + 1] - a[i]) - 3 / h[i - 1] * (a[i] - a[i - 1]);
            }

            l[0] = 1;
            mu[0] = z[0] = 0;

            for (int i = 1; i <= n - 1; i++)
            {
                l[i] = 2 * (x[i + 1] - x[i - 1]) - h[i - 1] * mu[i - 1];
                mu[i] = h[i] / l[i];
                z[i] = (alpha[i] - h[i - 1] * z[i - 1]) / l[i];
            }

            l[n] = 1;
            z[n] = c[n] = 0;

            for (int j = n - 1; j >= 0; j--)
            {
                c[j] = z[j] - mu[j] * c[j + 1];
                b[j] = (a[j + 1] - a[j]) / h[j] - (h[j] * (c[j + 1] + 2 * c[j])) / 3;
                d[j] = (c[j + 1] - c[j]) / (3 * h[j]);
            }

            for (int i = 0; i <= n - 1; i++)
            {
                spline.Add(new double[] { a[i], b[i], c[i], d[i], x[i] });
            }

            return spline;
        }
コード例 #24
0
ファイル: XmlReader.cs プロジェクト: ChrisMoreton/Test3
		public void Read(System.Xml.XmlReader reader)
		{
			// Disable auto-routing for a while
			_diagram.DontRouteForAwhile = true;

			_diagram.ClearAll();

			// Read while <Diagram> reached
			while (reader.Read())
				if (reader.Name == "Diagram")
					break;

			if (reader.Name != "Diagram")
				throw new InvalidFormatException("Invalid FlowChart document");

			// Check version
			_version = 1;
			if (reader.HasAttributes)
				_version = XmlConvert.ToInt32(reader.GetAttribute("Version"));

			// Read the brushes
			SortedList brushes = new SortedList();
			Brush brush;
			int count;
			int i;
			int id = 0;
			string type;
			int d;

			ReadMandatory(reader, "Brushes",
				"Brushes element missing or invalid");
			count = XmlConvert.ToInt32(
				reader.GetAttribute("Count"));
			for(i = 0; i < count; i++)
			{
				ReadMandatory(reader, "Brush",
					"Unrecognized brush token");

				id = XmlConvert.ToInt32(
					reader.GetAttribute("Id"));
				type = reader.GetAttribute("Type");

				brush = null;

				switch(type)
				{
					case "Solid":
					{
						d = reader.Depth;
						string name;
						while(true)
						{
							// Read element
							reader.Read();
							if(reader.Depth == d)
								break;

							name = reader.Name;
							// Read the value
							reader.Read();

							if(name == "Color")
							{
								Color c = XmlConvert.ToColor(reader.Value);
								brush = new FlowChartX.SolidBrush(c);
							}

							// Read the closing element
							reader.Read();
						}
					}
						break;
					case "Gradient":
					{
						d = reader.Depth;
						float angle = 0;
						Blend blend = null;
						Color c1 = Color.Black, c2 = Color.White;
						ColorBlend cblend = null;
						while(true)
						{
							// Read element
							reader.Read();
							if(reader.Depth == d)
								break;

							switch (reader.Name)
							{
								case "Angle":
									// Read the value
									reader.Read();
									angle = XmlConvert.ToSingle(reader.Value);
									break;
								case "Blend":
								{
									// Read positions
									reader.Read();
									float[] pos = ReadFloatArrayElement(reader);
									// Read factors
									reader.Read();
									float[] fac = ReadFloatArrayElement(reader);

									if(pos.Length != fac.Length)
										throw new InvalidFormatException(
											"Factors and positions in a gradient brush " +
											"have different lengths");

									blend = new Blend();
									blend.Positions = pos;
									blend.Factors = fac;
								}
									break;
								case "Color1":
									// Read the value
									reader.Read();
									c1 = XmlConvert.ToColor(reader.Value);
									break;
								case "Color2":
									// Read the value
									reader.Read();
									c2 = XmlConvert.ToColor(reader.Value);
									break;
								case "ColorBlend":
								{
									// Read positions
									reader.Read();
									float[] pos = ReadFloatArrayElement(reader);
									// Read colors
									reader.Read();
									Color[] colors = ReadColorArrayElement(reader);

									cblend = new ColorBlend();
									cblend.Positions = pos;
									cblend.Colors = colors;
								}
									break;
							}

							// Read the closing element
							reader.Read();
						}

						brush = new FlowChartX.LinearGradientBrush(c1, c2);
						((LinearGradientBrush)brush).Angle = angle;
						((LinearGradientBrush)brush).Blend = blend;
						((LinearGradientBrush)brush).InterpolationColor = cblend;
					}
						break;
					case "Texture":
					{
						d = reader.Depth;
						string name;
						WrapMode wm = WrapMode.Tile;
						Image img = null;
						while(true)
						{
							// Read element
							reader.Read();
							if(reader.Depth == d)
								break;

							name = reader.Name;
							// Read the value
							reader.Read();

							switch(name)
							{
								case "WrapMode":
									wm = (WrapMode)XmlConvert.ToEnum(
										typeof(WrapMode), reader.Value);
									break;
								case "Image":
									img = _version >= 4 ? XmlConvert.ToImageV4(reader.Value) :
										XmlConvert.ToImage(reader.Value);
									break;
							}

							// Read the closing element
							reader.Read();

							if (img != null)
								brush = new FlowChartX.TextureBrush(img, wm);
						}
					}
						break;
					case "Hatch":
					{
						d = reader.Depth;
						string name;
						Color fore = Color.Black, back = Color.White;
						HatchStyle style = HatchStyle.ForwardDiagonal;
						while(true)
						{
							// Read element
							reader.Read();
							if(reader.Depth == d)
								break;

							name = reader.Name;
							// Read the value
							reader.Read();

							switch(name)
							{
								case "ForeColor":
									fore = XmlConvert.ToColor(reader.Value);
									break;
								case "BackColor":
									back = XmlConvert.ToColor(reader.Value);
									break;
								case "Style":
									style = (HatchStyle)XmlConvert.ToEnum(
										typeof(HatchStyle), reader.Value);
									break;
							}

							// Read the closing element
							reader.Read();

							brush = new FlowChartX.HatchBrush(
								style, fore, back);
						}
					}
						break;
				}

				if(!brushes.Contains(id) && brush != null)
					brushes.Add(id, brush);
			}

			// Read the brushes closing element
			if(count > 0)
				reader.Read();

			ReadMandatory(reader, "Environment",
				"Environment element missing or invalid");

			// Read all appearance properties
			ReadMandatory(reader, "Appearance",
				"Appearance element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Appearance section");

			// Read all bahaviour properties
			ReadMandatory(reader, "Behaviour",
				"Behaviour element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Behaviour section");

			// Read all default properties
			ReadMandatory(reader, "Defaults",
				"Defaults element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Defaults section");

			// Read default brushes and pens
			ReadMandatory(reader, "DefaultsGDI",
				"DefaultsGDI element missing or invalid");
			d = reader.Depth;
			while(true)
			{
				// Read starting tag
				reader.Read();
				if(reader.Depth == d)
					break;

				switch (reader.Name)
				{

					case "BoxBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						_diagram.BoxBrush = (FlowChartX.Brush)brushes[id];
						break;

					case "TableBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						_diagram.TableBrush = (FlowChartX.Brush)brushes[id];
						break;
/*
					case "TableCaptionBackBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						_diagram.TableCaptionBackBrush = (FlowChartX.Brush)brushes[id];
						break;
*/
					case "ArrowBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						_diagram.ArrowBrush = (FlowChartX.Brush)brushes[id];
						break;

					case "BackBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						_diagram.BackBrush = (FlowChartX.Brush)brushes[id];
						break;

					case "ExteriorBrush":
						id = XmlConvert.ToInt32(
							reader.GetAttribute("Id"));
						if (id == -1)
							_diagram.ExteriorBrush = null;
						else
							_diagram.ExteriorBrush = (FlowChartX.Brush)brushes[id];
						break;

					case "BoxPen":
						_diagram.BoxPen.Brush = null; // force release
						_diagram.BoxPen = (FlowChartX.Pen)
							ReadPenElement(reader, brushes);
						break;

					case "TablePen":
						_diagram.TablePen.Brush = null; // force release
						_diagram.TablePen = (FlowChartX.Pen)
							ReadPenElement(reader, brushes);
						break;

					case "ArrowPen":
						_diagram.ArrowPen.Brush = null; // force release
						_diagram.ArrowPen = (FlowChartX.Pen)
							ReadPenElement(reader, brushes);
						break;

				}
			}

			// Read all grid properties
			ReadMandatory(reader, "Grid",
				"Grid element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Grid section");

			// Read all layout properties
			ReadMandatory(reader, "Layout",
				"Layout element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Layout section");

			// Read all miscellaneous properties
			ReadMandatory(reader, "Miscellaneous",
				"Miscellaneous element missing or invalid");
			if(!ReadProperties(reader, _diagram, reader.Depth + 1))
				throw new InvalidFormatException("Unexpected " +
					"EOF in the Miscellaneous section");

			// Read the Environment closing element
			reader.Read();


			// Proceed to diagram objects //
			Box b;
			ControlHost h;
			Arrow a;
			Table t;
			Group g;
			object from, to;
			PointCollection points = new PointCollection(0);
			int idFrom, idTo, idArrow;
			int rowFrom, rowTo;
			int row, col;
			SortedList objects = new SortedList();
			SortedList zOrder = new SortedList();
			SortedList controlZOrder = new SortedList();
			int zIndex;
			id = 0;

			// Read boxes info
			ReadMandatory(reader, "Boxes",
				"Boxes element missing or invalid");
			count = XmlConvert.ToInt32(reader.GetAttribute("Count"));
			int brushId = -1;
			FlowChartX.Pen pen = null;
			FlowChartX.Pen headPen = null;
			for(i = 0; i < count; i++)
			{
				// Read the starting element
				ReadMandatory(reader, "Box",
					"Unrecognized box token");

				id = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				zIndex = XmlConvert.ToInt32(reader.GetAttribute("ZIndex"));
				b = _diagram.CreateBox(0, 0, 1, 1);
				objects.Add(id, b);
				zOrder.Add(zIndex, b);

				// Read the shape
				string shape;
				reader.Read();
				if(!reader.IsEmptyElement)
				{
					reader.Read();
					shape = reader.Value;
					reader.Read();
				}
				else
				{
					shape = "Rectangle";
				}

				BoxStyle style = BoxStyle.Rectangle;
				switch(shape)
				{
					case "RoundRectangle":
						style = BoxStyle.RoundedRectangle;
						break;
					default:
						// Assume it is a complex shape
						style = BoxStyle.Shape;
						break;
				}
				b.Style = style;
				if(style == BoxStyle.Shape)
					b.Shape = ShapeTemplate.FromId(shape);

				// Read brush
				reader.Read();
				if (reader.GetAttribute("Id") != null)
					brushId = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				else
					brushId = -1;
				// Read the pen
				reader.Read();
				pen = ReadPenElement(reader, brushes);

				if(!ReadProperties(reader, b, reader.Depth))
					throw new InvalidFormatException(
						"Unexpected EOF while parsing box info. Box: " +
						i.ToString());

				// Set brush and pen
				if(brushId != -1)
					b.Brush = (FlowChartX.Brush)brushes[brushId];
				if(pen != null)
					b.Pen = pen;
			}

			// Read boxes closing element
			if(count > 0)
				reader.Read();

			// Read control hosts
			if (_version >= 3)
			{
				string assemblyName;
				string typeName;
				ReadMandatory(reader, "ControlHosts",
					"ControlHosts element missing or invalid");
				count = XmlConvert.ToInt32(reader.GetAttribute("Count"));

				for (i = 0; i < count; i++)
				{
					// Read the host element
					ReadMandatory(reader, "Host",
						"Host element missing or invalid");

					id = XmlConvert.ToInt32(reader.GetAttribute("Id"));
					zIndex = XmlConvert.ToInt32(reader.GetAttribute("ZIndex"));
					assemblyName = reader.GetAttribute("ControlAssembly");
					typeName = reader.GetAttribute("ControlType");
					int controlZIndex = XmlConvert.ToInt32(reader.GetAttribute("ControlZIndex"));

					// Create the control host and add it to the diagram
					h = _diagram.CreateControlHost(0, 0, 1, 1);
					objects.Add(id, h);
					zOrder.Add(zIndex, h);
					controlZOrder.Add(controlZIndex, h.Control);

					// Read brush
					reader.Read();
					if(reader.GetAttribute("Id") != null)
						brushId = XmlConvert.ToInt32(reader.GetAttribute("Id"));
					else
						brushId = -1;
					// Read the pen
					reader.Read();
					pen = ReadPenElement(reader, brushes);

					if (typeName != "" && assemblyName != "")
					{
						System.Type controlType = Utilities.getLoadedType(typeName, assemblyName);
						if (controlType == null)
							throw new FileLoadException("Cannot load hosted control of type " + typeName);
						ConstructorInfo ctorInfo = controlType.GetConstructor(System.Type.EmptyTypes);
						// Instantiate
						h.Control = (System.Windows.Forms.Control)ctorInfo.Invoke(null);

						// Read control properties
						BinaryFormatter fmt = new BinaryFormatter();
						fmt.Binder = new DeserializationHack();
						ReadControlProperties(reader, h.Control, fmt);
					}
					else
					{
						h.Control = null;
					}

					// Read properties
					if (!ReadProperties(reader, h, reader.Depth))
						throw new InvalidFormatException(
							"Unexpected EOF while parsing control host info. ControlHost: " +
							i.ToString());

					// Set brush and pen
					if (brushId != -1)
						h.Brush = (FlowChartX.Brush)brushes[brushId];
					if (pen != null)
						h.Pen = pen;
				}

				// Update the z-indices of the contained controls
				foreach (System.Windows.Forms.Control control in controlZOrder.Values)
					control.BringToFront();

				// Read control hosts closing element
				if(count > 0)
					reader.Read();
			}

			// Read tables info
			ReadMandatory(reader, "Tables",
				"Tables element missing or invalid");
			count = XmlConvert.ToInt32(reader.GetAttribute("Count"));
			for(i = 0; i < count; i++)
			{
				// Read the table element
				ReadMandatory(reader, "Table",
					"Unrecognized table token");

				id = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				zIndex = XmlConvert.ToInt32(reader.GetAttribute("ZIndex"));
				t = _diagram.CreateTable(0, 0, 1, 1);
				objects.Add(id, t);
				zOrder.Add(zIndex, t);

				t.RowCount = XmlConvert.ToInt32(reader.GetAttribute("Rows"));
				t.ColumnCount = XmlConvert.ToInt32(reader.GetAttribute("Columns"));

				// Read cell data
				ReadMandatory(reader, "Data",
					"Data element missing or invalid");
				d = reader.Depth;
				row = 0;
				col = 0;
				if(!reader.IsEmptyElement)
				{
					while(true)
					{
						reader.Read();
						if(d == reader.Depth)
							break;

						// Read brush in V5
						if (_version >= 5)
						{
							reader.Read();
							int bid = -1;
							if (reader.GetAttribute("Id") != null)
								bid = XmlConvert.ToInt32(reader.GetAttribute("Id"));
							if (bid != -1)
								t[col, row].Brush = (FlowChartX.Brush)brushes[bid];
							else
								t[col, row].Brush = null;

							ReadProperties(reader, t[col, row], reader.Depth);
						}
						else
						{
							ReadProperties(reader, t[col, row], reader.Depth + 1);
						}

						col++;
						if(col >= t.ColumnCount)
						{
							col = 0;
							row++;
						}
					}
				}

				// Read row data
				ReadMandatory(reader, "Rows",
					"Rows element missing or invalid");
				d = reader.Depth;
				row = 0;
				if(!reader.IsEmptyElement)
				{
					while(true)
					{
						reader.Read();
						if(d == reader.Depth)
							break;

						ReadProperties(reader, t.Rows[row], reader.Depth + 1);
						row++;
					}
				}

				// Read column data
				ReadMandatory(reader, "Columns",
					"Columns element missing or invalid");
				d = reader.Depth;
				col = 0;
				if(!reader.IsEmptyElement)
				{
					while(true)
					{
						reader.Read();
						if(d == reader.Depth)
							break;

						ReadProperties(reader, t.Columns[col], reader.Depth + 1);
						col++;
					}
				}

				// Read brush
				reader.Read();
				if (reader.GetAttribute("Id") != null)
					brushId = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				else
					brushId = -1;

				// Read the caption brush
				int captionBrushId = -1;
				if (_version >= 10)
				{
					reader.Read();
					if (reader.GetAttribute("Id") != null)
						captionBrushId = XmlConvert.ToInt32(reader.GetAttribute("Id"));
					else
						captionBrushId = -1;
				}

				// Read the pen
				reader.Read();
				pen = ReadPenElement(reader, brushes);

				// Read table properties
				if(!ReadProperties(reader, t, reader.Depth))
					throw new InvalidFormatException(
						"Unexpected EOF while parsing table info. Table: " +
						i.ToString());

				// Set brush and pen
				if (brushId != -1)
					t.Brush = (FlowChartX.Brush)brushes[brushId];
				if (captionBrushId != -1)
					t.CaptionBackBrush = (FlowChartX.Brush)brushes[captionBrushId];
				if (pen != null)
					t.Pen = pen;
			}

			// Read tables closing element
			if(count > 0)
				reader.Read();

			if (_version >= 7)
			{
				ReadMandatory(reader, "Containers",
					"Containers element missing or invalid");

				int ccount = XmlConvert.ToInt32(reader.GetAttribute("Count"));

				if (ccount > 0)
				{
					int cdepth = reader.Depth;
					while (true)
					{
						reader.Read();
						if (reader.Depth == cdepth)
							break;
					}
				}
			}

			// Read arrows info
			ReadMandatory(reader, "Arrows",
				"Arrows element missing or invalid");
			count = XmlConvert.ToInt32(reader.GetAttribute("Count"));
			for(i = 0; i < count; i++)
			{
				// Read the arrow element
				ReadMandatory(reader, "Arrow",
					"Unrecognized arrow token");

				// Read the origin and destination indices
				idFrom = XmlConvert.ToInt32(reader.GetAttribute("From"));
				idTo = XmlConvert.ToInt32(reader.GetAttribute("To"));
				idArrow = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				zIndex = XmlConvert.ToInt32(reader.GetAttribute("ZIndex"));

				try
				{
					rowFrom = XmlConvert.ToInt32(reader.GetAttribute("RowFrom"));
				}
				catch
				{
					rowFrom = -1;
				}
				try
				{
					rowTo = XmlConvert.ToInt32(reader.GetAttribute("RowTo"));
				}
				catch
				{
					rowTo = -1;
				}

				if (idTo == -1 || idFrom == -1)
				{
					if (idTo == -1 && idFrom != -1)
					{
						from = objects[idFrom];

						Node nodeFrom = from as Node;

						// Temporarily turn allow arrows off
						bool allowIn = nodeFrom.AllowIncomingArrows;
						bool allowOut = nodeFrom.AllowOutgoingArrows;

						nodeFrom.AllowIncomingArrows = true;
						nodeFrom.AllowOutgoingArrows = true;

						a = _diagram.CreateArrow(nodeFrom, PointF.Empty);

						nodeFrom.AllowIncomingArrows = allowIn;
						nodeFrom.AllowOutgoingArrows = allowOut;
					}
					else if (idTo != -1 && idFrom == -1)
					{
						to = objects[idTo];

						Node nodeTo = to as Node;

						// Temporarily turn allow arrows off
						bool allowIn = nodeTo.AllowIncomingArrows;
						bool allowOut = nodeTo.AllowOutgoingArrows;

						nodeTo.AllowIncomingArrows = true;
						nodeTo.AllowOutgoingArrows = true;

						a = _diagram.CreateArrow(PointF.Empty, (Node)to);

						nodeTo.AllowIncomingArrows = allowIn;
						nodeTo.AllowOutgoingArrows = allowOut;
					}
					else
					{
						a = _diagram.CreateArrow(PointF.Empty, PointF.Empty);
					}
				}
				else
				{
					from = objects[idFrom];
					to = objects[idTo];

					Node nodeFrom = from as Node;
					Node nodeTo = to as Node;

					// Temporarily turn allow arrows off
					bool fromAllowIn = nodeFrom.AllowIncomingArrows;
					bool fromAllowOut = nodeFrom.AllowOutgoingArrows;
					bool toAllowIn = nodeTo.AllowIncomingArrows;
					bool toAllowOut = nodeTo.AllowOutgoingArrows;

					nodeFrom.AllowIncomingArrows = true;
					nodeFrom.AllowOutgoingArrows = true;
					nodeTo.AllowIncomingArrows = true;
					nodeTo.AllowOutgoingArrows = true;

					if(rowFrom == -1 && rowTo == -1)
					{
						a = _diagram.CreateArrow((Node)from, (Node)to);
					}
					else if(rowFrom != -1 && rowTo == -1)
					{
						a = _diagram.CreateArrow((Table)from, rowFrom, (Node)to);
					}
					else if(rowFrom == -1 && rowTo != -1)
					{
						a = _diagram.CreateArrow((Node)from, (Table)to, rowTo);
					}
					else
					{
						a = _diagram.CreateArrow((Table)from, rowFrom,
							(Table)to, rowTo);
					}

					nodeFrom.AllowIncomingArrows = fromAllowIn;
					nodeFrom.AllowOutgoingArrows = fromAllowOut;
					nodeTo.AllowIncomingArrows = toAllowIn;
					nodeTo.AllowOutgoingArrows = toAllowOut;
				}

				// Read the control points
				ReadMandatory(reader, "Data",
					"Data element missing or invalid");
				d = reader.Depth;
				float x, y;
				points.Clear();
				while(true)
				{
					// Read the point
					reader.Read();

					if(reader.Depth == d)
						break;

					x = XmlConvert.ToSingle(reader.GetAttribute("X"));
					y = XmlConvert.ToSingle(reader.GetAttribute("Y"));

					points.Add(new PointF(x, y));
				}

				// Read brush
				reader.Read();
				if(reader.GetAttribute("Id") != null)
					brushId = XmlConvert.ToInt32(reader.GetAttribute("Id"));
				else
					brushId = -1;
				// Read the pen
				reader.Read();
				pen = ReadPenElement(reader, brushes);
				// Read head pen
				if (_version > 1)
				{
					reader.Read();
					headPen = ReadPenElement(reader, brushes);
				}

				// Read the properties
				if(!ReadProperties(reader, a, reader.Depth))
					throw new InvalidFormatException(
						"Unexpected EOF while parsing arrow info. Arrow: " +
						i.ToString());

				// Set again segment count, because
				// if the arrow is routed, settings
				// segment count through SegmentCount property
				// won't have any effect
				if (a.Style == ArrowStyle.Bezier)
					a.InternalSegmentCount = (short)((points.Count - 1) / 3);
				else
					a.InternalSegmentCount = (short)(points.Count - 1);

				// Set the control points
				for(int p = 0; p < points.Count; p++)
					a.ControlPoints[p] = points[p];
				a.UpdateFromPoints();

				// Set brush and pen
				if(brushId != -1)
					a.Brush = (FlowChartX.Brush)brushes[brushId];
				if(pen != null)
					a.Pen = pen;
				if (headPen != null)
					a.HeadPen = headPen;

				objects.Add(idArrow, a);
				zOrder.Add(zIndex, a);
			}

			// Read arrows closing element
			if(count > 0)
				reader.Read();


			// Adjust z-order
			for(i = 0; i < zOrder.Count; i++)
			{
				ChartObject obj = (ChartObject)zOrder.GetByIndex(i);
				obj.ZIndex = (int)zOrder.GetKey(i);
			}


			// Read groups
			ReadMandatory(reader, "Groups",
				"Groups element missing or invalid");
			count = XmlConvert.ToInt32(reader.GetAttribute("Count"));
			for(i = 0; i < count; i++)
			{
				// Read the group element
				ReadMandatory(reader, "Group",
					"Unrecognized group token");

				// Read the main object
				reader.Read();
				id = XmlConvert.ToInt32(reader.GetAttribute("Id"));

				g = _diagram.CreateGroup((ChartObject)objects[id]);

				// Read group's visibility
				reader.Read();
				reader.Read();
				g.Visible = XmlConvert.ToBoolean(reader.Value.ToLower());
				reader.Read();

				// Read AutoDeleteItems flag
				if (_version >= 7)
				{
					reader.Read();
					reader.Read();
					g.AutoDeleteItems = XmlConvert.ToBoolean(reader.Value.ToLower());
					reader.Read();
				}

				// Read Expandable flag
				if (_version >= 8)
				{
					reader.Read();
					reader.Read();
					g.Expandable = XmlConvert.ToBoolean(reader.Value.ToLower());
					reader.Read();
				}

				// Read FollowMasterRotation flag
				if (_version >= 9)
				{
					reader.Read();
					reader.Read();
					g.FollowMasterRotation = XmlConvert.ToBoolean(reader.Value.ToLower());
					reader.Read();
				}

				reader.Read(); // read Tag or Attachments
				if (reader.Name == "Tag")
				{
					if (_options.CustomTagSerialization)
					{
						if(DeserializeTag != null)
						{
							SerializeTagArgs args = new SerializeTagArgs(g, null, reader);
							DeserializeTag(this, args);
						}
					}
					else
					{
						// Read the value
						reader.Read();

						if(DeserializeTag != null)
						{
							SerializeTagArgs args = new SerializeTagArgs(g);
							args.Representation = reader.Value;
							DeserializeTag(this, args);
						}
					}

					// Read the closing Tag element
					reader.Read();

					// Read the Attachments
					reader.Read();
				}

				// Process attachments
				int acount = XmlConvert.ToInt32(reader.GetAttribute("Count"));
				int ai;
				int adata;
				Node node;
				float al, at, ar, ab;
				AttachTo atype;
				for(ai = 0; ai < acount; ai++)
				{
					// Read attachment element
					reader.Read();

					// Read data
					reader.Read();
					reader.Read();
					adata = XmlConvert.ToInt32(reader.Value);
					reader.Read();

					// Read object
					reader.Read();
					reader.Read();
					node = (Node)objects[XmlConvert.ToInt32(reader.Value)];
					reader.Read();

					// Read percents
					reader.Read();
					al = XmlConvert.ToSingle(reader.GetAttribute("Left"));
					at = XmlConvert.ToSingle(reader.GetAttribute("Top"));
					ar = XmlConvert.ToSingle(reader.GetAttribute("Right"));
					ab = XmlConvert.ToSingle(reader.GetAttribute("Bottom"));

					// Read type
					reader.Read();
					reader.Read();
					atype = (AttachTo)XmlConvert.ToEnum(
						typeof(AttachTo), reader.Value);
					reader.Read();

					switch(atype)
					{
						case AttachTo.ArrowPoint:
							g.AttachToArrowPoint(node, adata);
							break;
						case AttachTo.ArrowSegment:
							g.AttachToArrowSegment(node, adata);
							break;
						case AttachTo.FixedCorner:
							g.AttachToCorner(node, adata);
							break;
						case AttachTo.Proportional:
							g.AttachProportional(node, al, at, ar, ab);
							break;
						case AttachTo.LongestHSegment:
							g.AttachToLongestHSegment(node);
							break;
						case AttachTo.SideMiddle:
							g.AttachToSideMiddle(node, adata);
							break;
					}

					// Read attachment closing element
					reader.Read();
				}

				// Read attachments' closing element
				if(acount > 0)
					reader.Read();

				// Read the group closing element
				reader.Read();
			}

			// Read groups closing element
			reader.Read();

			// Read diagram closing element
			reader.Read();

			foreach (ChartObject obj in _diagram.Objects)
				obj.onLoad();

			// Note: If exception is thrown this
			// flag will remain raised
			_diagram.DontRouteForAwhile = false;
		}
コード例 #25
0
ファイル: Simulator.cs プロジェクト: xujyan/brunet
    public void TestConTable() {
      SortedList list = new SortedList();
      for (int i = 0; i < 10; i++) {
	AHAddress address = new AHAddress(new RNGCryptoServiceProvider());
	SimNode node = new SimNode(address, NatType.Public, 0);
	list[address] = node;
      }
      SimNode n0 = (SimNode) list.GetByIndex(0);
      for (int i = 1; i < 10; i++) {
	SimNode n = (SimNode) list.GetByIndex(i);
	n0.AddConnection(n, (i%2 == 0)?ConType.Near:ConType.Shortcut);
      }
      Assert.AreEqual(n0.ConnectionTable.GetConnections(ConType.Near).Count, 4);
      Assert.AreEqual(n0.ConnectionTable.GetConnections(ConType.Shortcut).Count, 5);
      Assert.AreEqual(n0.ConnectionTable.GetAllConnections().Count, 9);      

      //make sure all connections are sorted in n0 table
      ArrayList n0_con = n0.ConnectionTable.GetAllConnections();
      for (int i = 0; i < n0_con.Count; i++) {
	AHAddress target = (AHAddress) n0_con[i];
	SimNode n = (SimNode) list.GetByIndex(i+1);
	Assert.AreEqual(target, n.LocalAddress);
      }
      //connection table is sorted (fine);
      SimNode n5 = (SimNode) list.GetByIndex(5);
      int idx = n0.ConnectionTable.IndexOf(n5.LocalAddress);
      Assert.IsTrue(idx > 0);
      Assert.AreEqual(idx, 4);


      idx = n0.ConnectionTable.IndexOf(n0.LocalAddress);
      Assert.IsTrue(idx < 0);
      idx = ~idx;
      Assert.IsTrue(idx == 0);

      for (int trials = 0; trials < 100; trials++) {
	AHAddress test_address = new AHAddress(new RNGCryptoServiceProvider());
	SimNode test_node = new SimNode(test_address, NatType.Public, 0);
	list[test_address] = test_node;
	int test_idx = list.IndexOfKey(test_address);
	//address of this newly generated address
	idx = n0.ConnectionTable.IndexOf(test_address);
	Assert.IsTrue(idx < 0);
	idx = ~idx;
	if (test_idx == 0) {
	  Assert.IsTrue(idx == 0);	
	} else {
	  Assert.IsTrue(idx == test_idx - 1);
	}
	list.Remove(test_address);
      }

      //do some unit tests for LeftInclusiveCount and RightInclusiveCount;
      for (int i = 1; i < 10; i++) {
	Assert.AreEqual(i-1, n0.ConnectionTable.LeftInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));
	//Console.WriteLine(n0.ConnectionTable.RightInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));	
	Assert.AreEqual(list.Count - i - 1, n0.ConnectionTable.RightInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));


      }

      

    }
コード例 #26
0
        private int Save5000GuideAsXML(bool shareReceived, bool showHDTV)
        {
            XmlTextWriter writer = new XmlTextWriter(this.guideXMLFile, Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            writer.WriteStartElement("result");
            int[] numArray = new int[] { 0, 0 };
            FileStream stream = File.OpenRead(this.guideFile);
            byte[] array = new byte[(int) stream.Length];
            stream.Read(array, 0, (int) stream.Length);
            stream.Close();
            bool flag = true;
            SortedList categoryList = new SortedList();
            categoryList = this.Build5000Categories(array);
            writer.WriteStartElement("category-list");
            for (int i = 0; i < categoryList.Count; i++)
            {
                writer.WriteStartElement("category");
                writer.WriteAttributeString("categoryID", null, categoryList.GetKey(i).ToString());
                writer.WriteAttributeString("categoryName", null, categoryList.GetByIndex(i).ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            SortedList list2 = new SortedList();
            list2 = this.Build5000Channels(array, categoryList);
            writer.WriteStartElement("channel-list");
            try
            {
                int num2 = 0;
                int length = array.Length;
                int num4 = length - (840 + (0x2c8 * ReplayHelper.ReplayByteToInt(array, 0x10, 4)));
                byte[] destinationArray = new byte[num4];
                byte[] buffer3 = new byte[0x200];
                Array.Copy(array, 840 + (0x2c8 * ReplayHelper.ReplayByteToInt(array, 0x10, 4)), destinationArray, 0, num4);
                byte[] buffer4 = null;
                byte[] buffer5 = null;
                byte[] buffer6 = null;
                for (int j = 0; (num4 - (0x200 * j)) >= 0x200; j++)
                {
                    string text5;
                    Array.Copy(destinationArray, 0x200 * j, buffer3, 0, 0x200);
                    DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, 0);
                    long num6 = ReplayHelper.ReplayByteToLong(buffer3, 120, 4);
                    int num7 = 0;
                    if ((num6 & 0x40) > 0)
                    {
                        num7 += 4;
                    }
                    if ((num6 & 0x20) > 0)
                    {
                        num7 += 8;
                    }
                    int num8 = ReplayHelper.ReplayByteToInt(buffer3, 0, 4);
                    int num9 = ReplayHelper.ReplayByteToInt(buffer3, 4, 4);
                    buffer4 = new byte[ReplayHelper.ReplayByteToInt(buffer3, 140, 1) - 1];
                    buffer5 = new byte[ReplayHelper.ReplayByteToInt(buffer3, 0x8d, 1) - 1];
                    buffer6 = new byte[ReplayHelper.ReplayByteToInt(buffer3, 0x8e, 1) - 1];
                    int qualityCode = ReplayHelper.ReplayByteToInt(buffer3, 12, 4);
                    string quality = this.GetQuality(qualityCode);
                    int num11 = ReplayHelper.ReplayByteToInt(buffer3, 0x188, 4);
                    int num12 = num11 / 60;
                    if ((num11 % 60) >= 30)
                    {
                        num12++;
                    }
                    string text2 = num12.ToString();
                    int num13 = ReplayHelper.ReplayByteToInt(buffer3, 0x7c, 4);
                    int num14 = ReplayHelper.ReplayByteToInt(buffer3, 380, 4);
                    int num15 = ReplayHelper.ReplayByteToInt(buffer3, 0x184, 4);
                    string text3 = time.AddSeconds((double) num13).ToString("yyyy-MM-dd HH:mm:ss.000", DateTimeFormatInfo.InvariantInfo);
                    Array.Copy(buffer3, 0x94 + num7, buffer4, 0, buffer4.Length);
                    Array.Copy(buffer3, ((0x94 + num7) + buffer4.Length) + 1, buffer5, 0, buffer5.Length);
                    Array.Copy(buffer3, ((((0x94 + num7) + buffer4.Length) + 1) + buffer5.Length) + 1, buffer6, 0, buffer6.Length);
                    ReplayChannelGuide guide = (ReplayChannelGuide) list2[num8];
                    string channelTitle = guide.channelTitle;
                    switch (guide.channelType)
                    {
                        case 1:
                            text5 = "Recurring";
                            break;

                        case 2:
                            text5 = "Theme";
                            break;

                        case 3:
                            text5 = "Single";
                            break;

                        case 4:
                            text5 = "Zone";
                            break;

                        default:
                            text5 = "";
                            break;
                    }
                    int channelCategory = guide.channelCategory;
                    string channelCatName = guide.channelCatName;
                    string text7 = ReplayHelper.ReplaceUTF8InString(this.encoding.GetString(buffer4));
                    string text8 = ReplayHelper.ReplaceUTF8InString(this.encoding.GetString(buffer6));
                    string text9 = ReplayHelper.ReplaceUTF8InString(this.encoding.GetString(buffer5));
                    if (shareReceived || ((num14 == 0) && (num15 < 15)))
                    {
                        if (num8 != num2)
                        {
                            if (flag)
                            {
                                flag = false;
                            }
                            else
                            {
                                writer.WriteEndElement();
                            }
                            writer.WriteStartElement("channel");
                            writer.WriteAttributeString("title", null, channelTitle);
                            writer.WriteAttributeString("channelID", null, num8.ToString());
                            writer.WriteAttributeString("channelType", null, text5);
                            writer.WriteAttributeString("categoryID", null, channelCategory.ToString());
                            writer.WriteAttributeString("categoryName", null, channelCatName);
                            guide.channelDone = true;
                        }
                        writer.WriteStartElement("show");
                        if (shareReceived && (num14 != 0))
                        {
                            writer.WriteAttributeString("title", null, text7);
                        }
                        else if (text5.Equals("Single") || text5.Equals("Recurring"))
                        {
                            writer.WriteAttributeString("title", null, channelTitle);
                        }
                        else
                        {
                            writer.WriteAttributeString("title", null, text7);
                        }
                        writer.WriteAttributeString("description", null, text8);
                        if (!showHDTV && text9.StartsWith("(HDTV) "))
                        {
                            text9 = text9.Remove(0, 7);
                        }
                        if (text9.Equals(""))
                        {
                            if (text8.Equals(""))
                            {
                                writer.WriteAttributeString("episodeTitle", null, text7);
                            }
                            else
                            {
                                if (text8.Length > 0x23)
                                {
                                    text8 = text8.Substring(0, 0x20);
                                    if (text8.LastIndexOf(" ") >= 0)
                                    {
                                        text8 = text8.Substring(0, text8.LastIndexOf(" ")) + "...";
                                    }
                                }
                                writer.WriteAttributeString("episodeTitle", null, text8);
                            }
                        }
                        else
                        {
                            writer.WriteAttributeString("episodeTitle", null, text9);
                        }
                        writer.WriteAttributeString("startTimeGMT", null, text3);
                        writer.WriteAttributeString("durationInMinutes", null, text2);
                        writer.WriteAttributeString("quality", null, quality);
                        writer.WriteAttributeString("showID", null, num9.ToString());
                        writer.WriteEndElement();
                    }
                    num2 = num8;
                }
                if (!flag)
                {
                    writer.WriteEndElement();
                }
                IList keyList = list2.GetKeyList();
                for (int k = 0; k < list2.Count; k++)
                {
                    string text11;
                    ReplayChannelGuide guide2 = (ReplayChannelGuide) list2[keyList[k]];
                    string text10 = guide2.channelTitle;
                    switch (guide2.channelType)
                    {
                        case 1:
                            text11 = "Recurring";
                            break;

                        case 2:
                            text11 = "Theme";
                            break;

                        case 3:
                            text11 = "Single";
                            break;

                        case 4:
                            text11 = "Zone";
                            break;

                        default:
                            text11 = "";
                            break;
                    }
                    int num18 = guide2.channelCategory;
                    string text12 = guide2.channelCatName;
                    if (!guide2.channelDone)
                    {
                        writer.WriteStartElement("channel");
                        writer.WriteAttributeString("title", null, text10);
                        writer.WriteAttributeString("channelID", null, keyList[k].ToString());
                        writer.WriteAttributeString("channelType", null, text11);
                        writer.WriteAttributeString("categoryID", null, num18.ToString());
                        writer.WriteAttributeString("categoryName", null, text12);
                        writer.WriteEndElement();
                    }
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            catch (Exception exception)
            {
                ReplayLogger.Log("Save5000GuideAsXML Exception" + exception.ToString());
                if (!flag)
                {
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.Flush();
                writer.Close();
                return -1;
            }
            writer.Flush();
            writer.Close();
            return 1;
        }
コード例 #27
0
ファイル: GetKeyTests.cs プロジェクト: johnhhm/corefx
        public void TestGetKeyBasic()
        {
            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;

            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: GetKey - key at index 0 , ArgExc expected
            Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                    sl2.GetKey(0);
                });

            //   Testcase: GetKey - null val, should pass
            sl2["first key"] = (string)null;
            Assert.Equal(1, sl2.Count);

            //   Testcase: vanila Set
            sl2.Clear();
            //   Testcase: add key-val pairs
            for (i = 0; i < 50; 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);
            }

            //
            //   now get their keys using GetKey
            //
            for (i = 0; i < 50; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();
                Assert.True(((string)sl2.GetKey(sl2.IndexOfKey(s1))).Equals(s1));
            }

            Assert.Equal(50, sl2.Count);
        }
コード例 #28
0
ファイル: PlotSurface2D.cs プロジェクト: ratiel/Vindictus
        /// <summary>
        /// Draw the the PlotSurface2D and all contents [axes, drawables, and legend] on the
        /// supplied graphics surface.
        /// </summary>
        /// <param name="g">The graphics surface on which to draw.</param>
        /// <param name="bounds">A bounding box on this surface that denotes the area on the
        /// surface to confine drawing to.</param>
        public void Draw(Graphics g, Rectangle bounds)
        {
            // determine font sizes and tick scale factor.
            float scale = DetermineScaleFactor(bounds.Width, bounds.Height);

            // if there is nothing to plot, return.
            if (drawables_.Count == 0)
            {
                // draw title
                float x_center = (bounds.Left + bounds.Right) / 2.0f;
                float y_center = (bounds.Top + bounds.Bottom) / 2.0f;
                Font  scaled_font;
                if (AutoScaleTitle)
                {
                    scaled_font = Utils.ScaleFont(titleFont_, scale);
                }
                else
                {
                    scaled_font = titleFont_;
                }
                g.DrawString(title_, scaled_font, titleBrush_, new PointF(x_center, y_center), titleDrawFormat_);

                return;
            }

            // determine the [non physical] axes to draw based on the axis properties set.
            Axis xAxis1 = null;
            Axis xAxis2 = null;
            Axis yAxis1 = null;
            Axis yAxis2 = null;

            DetermineAxesToDraw(out xAxis1, out xAxis2, out yAxis1, out yAxis2);

            // apply scale factor to axes as desired.

            if (xAxis1.AutoScaleTicks)
            {
                xAxis1.TickScale = scale;
            }
            if (xAxis1.AutoScaleText)
            {
                xAxis1.FontScale = scale;
            }
            if (yAxis1.AutoScaleTicks)
            {
                yAxis1.TickScale = scale;
            }
            if (yAxis1.AutoScaleText)
            {
                yAxis1.FontScale = scale;
            }
            if (xAxis2.AutoScaleTicks)
            {
                xAxis2.TickScale = scale;
            }
            if (xAxis2.AutoScaleText)
            {
                xAxis2.FontScale = scale;
            }
            if (yAxis2.AutoScaleTicks)
            {
                yAxis2.TickScale = scale;
            }
            if (yAxis2.AutoScaleText)
            {
                yAxis2.FontScale = scale;
            }

            // determine the default physical positioning of those axes.
            PhysicalAxis pXAxis1 = null;
            PhysicalAxis pYAxis1 = null;
            PhysicalAxis pXAxis2 = null;
            PhysicalAxis pYAxis2 = null;

            DeterminePhysicalAxesToDraw(
                bounds, xAxis1, xAxis2, yAxis1, yAxis2,
                out pXAxis1, out pXAxis2, out pYAxis1, out pYAxis2);

            float oldXAxis2Height = pXAxis2.PhysicalMin.Y;

            // Apply axes constraints
            for (int i = 0; i < axesConstraints_.Count; ++i)
            {
                ((AxesConstraint)axesConstraints_[i]).ApplyConstraint(
                    pXAxis1, pYAxis1, pXAxis2, pYAxis2);
            }

            /////////////////////////////////////////////////////////////////////////
            // draw legend if have one.
            // Note: this will update axes if necessary.

            Point legendPosition = new Point(0, 0);

            if (legend_ != null)
            {
                legend_.UpdateAxesPositions(
                    pXAxis1, pYAxis1, pXAxis2, pYAxis2,
                    drawables_, scale, padding_, bounds,
                    out legendPosition);
            }

            float newXAxis2Height = pXAxis2.PhysicalMin.Y;

            float titleExtraOffset = oldXAxis2Height - newXAxis2Height;

            // now we are ready to define the bounding box for the plot area (to use in clipping
            // operations.
            plotAreaBoundingBoxCache_ = new Rectangle(
                Math.Min(pXAxis1.PhysicalMin.X, pXAxis1.PhysicalMax.X),
                Math.Min(pYAxis1.PhysicalMax.Y, pYAxis1.PhysicalMin.Y),
                Math.Abs(pXAxis1.PhysicalMax.X - pXAxis1.PhysicalMin.X + 1),
                Math.Abs(pYAxis1.PhysicalMin.Y - pYAxis1.PhysicalMax.Y + 1)
                );
            bbXAxis1Cache_ = pXAxis1.GetBoundingBox();
            bbXAxis2Cache_ = pXAxis2.GetBoundingBox();
            bbYAxis1Cache_ = pYAxis1.GetBoundingBox();
            bbYAxis2Cache_ = pYAxis2.GetBoundingBox();

            // Fill in the background.
            if (plotBackColor_ != null)
            {
                g.FillRectangle(
                    new System.Drawing.SolidBrush((Color)plotBackColor_),
                    (Rectangle)plotAreaBoundingBoxCache_);
            }
            else if (plotBackBrush_ != null)
            {
                g.FillRectangle(
                    plotBackBrush_.Get((Rectangle)plotAreaBoundingBoxCache_),
                    (Rectangle)plotAreaBoundingBoxCache_);
            }
            else if (plotBackImage_ != null)
            {
                g.DrawImage(
                    Utils.TiledImage(plotBackImage_, new Size(
                                         ((Rectangle)plotAreaBoundingBoxCache_).Width,
                                         ((Rectangle)plotAreaBoundingBoxCache_).Height)),
                    (Rectangle)plotAreaBoundingBoxCache_);
            }

            // draw title
            float xt = (pXAxis2.PhysicalMax.X + pXAxis2.PhysicalMin.X) / 2.0f;
            float yt = bounds.Top + padding_ - titleExtraOffset;
            Font  scaledFont;

            if (AutoScaleTitle)
            {
                scaledFont = Utils.ScaleFont(titleFont_, scale);
            }
            else
            {
                scaledFont = titleFont_;
            }
            g.DrawString(title_, scaledFont, titleBrush_, new PointF(xt, yt), titleDrawFormat_);

            //count number of new lines in title.
            int nlCount = 0;

            for (int i = 0; i < title_.Length; ++i)
            {
                if (title_[i] == '\n')
                {
                    nlCount += 1;
                }
            }

            SizeF s = g.MeasureString(title_, scaledFont);

            bbTitleCache_ = new Rectangle((int)(xt - s.Width / 2), (int)(yt), (int)(s.Width), (int)(s.Height) * (nlCount + 1));

            // draw drawables..
            System.Drawing.Drawing2D.SmoothingMode smoothSave = g.SmoothingMode;

            g.SmoothingMode = smoothingMode_;

            bool legendDrawn = false;

            for (int i_o = 0; i_o < ordering_.Count; ++i_o)
            {
                int    i      = (int)ordering_.GetByIndex(i_o);
                double zOrder = (double)ordering_.GetKey(i_o);
                if (zOrder > legendZOrder_)
                {
                    // draw legend.
                    if (!legendDrawn && legend_ != null)
                    {
                        legend_.Draw(g, legendPosition, drawables_, scale);
                        legendDrawn = true;
                    }
                }

                IDrawable     drawable = (IDrawable)drawables_[i];
                XAxisPosition xap      = (XAxisPosition)xAxisPositions_[i];
                YAxisPosition yap      = (YAxisPosition)yAxisPositions_[i];

                PhysicalAxis drawXAxis;
                PhysicalAxis drawYAxis;

                if (xap == XAxisPosition.Bottom)
                {
                    drawXAxis = pXAxis1;
                }
                else
                {
                    drawXAxis = pXAxis2;
                }

                if (yap == YAxisPosition.Left)
                {
                    drawYAxis = pYAxis1;
                }
                else
                {
                    drawYAxis = pYAxis2;
                }

                // set the clipping region.. (necessary for zoom)
                g.Clip = new Region((Rectangle)plotAreaBoundingBoxCache_);
                // plot.
                drawable.Draw(g, drawXAxis, drawYAxis);
                // reset it..
                g.ResetClip();
            }

            if (!legendDrawn && legend_ != null)
            {
                legend_.Draw(g, legendPosition, drawables_, scale);
            }

            // cache the physical axes we used on this draw;
            pXAxis1Cache_ = pXAxis1;
            pYAxis1Cache_ = pYAxis1;
            pXAxis2Cache_ = pXAxis2;
            pYAxis2Cache_ = pYAxis2;

            g.SmoothingMode = smoothSave;

            // now draw axes.
            Rectangle axisBounds;

            pXAxis1.Draw(g, out axisBounds);
            pXAxis2.Draw(g, out axisBounds);
            pYAxis1.Draw(g, out axisBounds);
            pYAxis2.Draw(g, out axisBounds);

#if DEBUG_BOUNDING_BOXES
            g.DrawRectangle(new Pen(Color.Orange), (Rectangle)bbXAxis1Cache_);
            g.DrawRectangle(new Pen(Color.Orange), (Rectangle)bbXAxis2Cache_);
            g.DrawRectangle(new Pen(Color.Orange), (Rectangle)bbYAxis1Cache_);
            g.DrawRectangle(new Pen(Color.Orange), (Rectangle)bbYAxis2Cache_);
            g.DrawRectangle(new Pen(Color.Red, 5.0F), (Rectangle)plotAreaBoundingBoxCache_);
            //if(this.ShowLegend)g.DrawRectangle( new Pen(Color.Chocolate, 3.0F), (Rectangle) bbLegendCache_);
            g.DrawRectangle(new Pen(Color.DeepPink, 2.0F), (Rectangle)bbTitleCache_);
#endif
        }
コード例 #29
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;
    }
コード例 #30
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();
		}
コード例 #31
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();
		}
コード例 #32
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();
		}
コード例 #33
0
ファイル: CDataOperator.cs プロジェクト: jquery2005/GMIS
        /// <summary>
        /// 获取定位的Sql语句
        /// </summary>
        /// <returns></returns>
        public string GetWhereSql(SortedList LocateList)
        {
            string tempWhereSql;

            try
            {
                if (LocateList.GetByIndex(0) == null)
                {
                    return "";
                }
                else
                {
                    tempWhereSql = " where ";
                    for (int i = 0; i <= LocateList.Count - 1; i++)
                    {
                        string ValueSql;

                        ValueSql = GetSqlByValueType(LocateList.GetByIndex(i));
                        tempWhereSql = tempWhereSql + LocateList.GetKey(i) + "=" + ValueSql + " and ";
                    }

                    tempWhereSql = tempWhereSql.Substring(0, tempWhereSql.Length - 4);
                    return tempWhereSql;
                }
            }
            catch
            {
                return "";
            }
        }//GetWhereSql
コード例 #34
0
 private XmlElement BuildVariableElement(string VariableCode, XmlDocument SiteDoc, XmlDocument TargetDoc, bool IncludeVariableDetails, bool IncludeSites, bool IncludeSiteDetails)
 {
     XmlElement variable;
     variable = TargetDoc.CreateElement("Variable");
     utils.AddChildElement(variable, "VariableCode", VariableCode);
     if (!(IncludeVariableDetails) & !(IncludeSites))
     {
         return variable;
     }
     if (IncludeVariableDetails)
     {
         utils.AddChildElement(variable, "VariableName");
         utils.AddChildElement(variable, "Units");
         utils.AddChildElement(variable, "VariableDescription", SiteDoc.SelectSingleNode("//VariableDescription").InnerText);
     }
     XmlElement sites;
     string query;
     query = "//Variable[VariableCode='" + VariableCode + "']";
     XmlNodeList nodes = SiteDoc.SelectNodes(query);
     if (nodes.Count == 0)
     {
         throw new Exception("No variables found for the given variable code");
     }
     SortedList slNames = new SortedList();
     SortedList slUnits = new SortedList();
     string units;
     string name;
     XmlElement element;
     XmlElement parent;
     foreach (XmlElement var in nodes)
     {
         element = var.SelectSingleNode("VariableName") as XmlElement;
         name = "";
         if (!(element == null))
         {
             name = element.InnerText;
             if (name != "")
             {
                 if (!(slNames.ContainsKey(name)))
                 {
                     slNames.Add(name, name);
                 }
             }
         }
         element = var.SelectSingleNode("Units") as XmlElement;
         units = "";
         if (!(element == null))
         {
             units = element.InnerText;
             if (units != "")
             {
                 if (!(slUnits.ContainsKey(units)))
                 {
                     slUnits.Add(units, units);
                 }
             }
         }
         if (IncludeSites)
         {
             sites = TargetDoc.CreateElement("Sites");
             variable.AppendChild(sites);
             XmlElement site = TargetDoc.CreateElement("Site");
             sites.AppendChild(site);
             parent = var.ParentNode.ParentNode as XmlElement;
             utils.AddChildElement(site, "SiteCode", parent.SelectSingleNode("SiteCode").InnerText);
             if (IncludeSiteDetails)
             {
                 element = parent.SelectSingleNode("SiteName") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "SiteName", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "SiteName", "");
                 }
                 element = parent.SelectSingleNode("State") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "State", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "State", "");
                 }
                 element = parent.SelectSingleNode("Latitude") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "Latitude", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "Latitude", "");
                 }
                 element = parent.SelectSingleNode("Longitude") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "Longitude", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "Longitude", "");
                 }
                 element = parent.SelectSingleNode("StartTSDate") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "StartTSDate", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "StartTSDate", "");
                 }
                 element = parent.SelectSingleNode("EndTSDate") as XmlElement;
                 if (!(element == null))
                 {
                     utils.AddChildElement(site, "EndTSDate", element.InnerText);
                 }
                 else
                 {
                     utils.AddChildElement(site, "EndTSDate", "");
                 }
                 utils.AddChildElement(site, "VariableName", name);
                 utils.AddChildElement(site, "Units", units);
             }
             sites.SetAttribute("count", sites.SelectNodes("Site").Count.ToString());
         }
     }
     if (IncludeVariableDetails)
     {
         units = "";
         for (int i = 0; i <= slUnits.Count - 1; i++)
         {
             if (units.Length == 0)
             {
                 units = slUnits.GetKey(i).ToString();
             }
             else
             {
                 units += "; " + slUnits.GetKey(i);
             }
         }
         variable.SelectSingleNode("Units").InnerText = units;
         name = "";
         for (int i = 0; i <= slNames.Count - 1; i++)
         {
             if (name.Length == 0)
             {
                 name = slNames.GetKey(i).ToString();
             }
             else
             {
                 name += "; " + slNames.GetKey(i);
             }
         }
         variable.SelectSingleNode("VariableName").InnerText = name;
     }
     return variable;
 }
コード例 #35
0
ファイル: CtrlSvgView_wh.cs プロジェクト: EdgarEDT/myitoppsp
        void tlVectorControl1_RightClick(object sender, ItopVector.DrawArea.SvgElementSelectedEventArgs e)
        {
            if (MapType == "接线图") {
                tip.Hide();
                contextMenuStrip1.Show(e.Mouse.X, e.Mouse.Y);
                if (getlayer(SvgDocument.currentLayer, "背景层", tlVectorControl1.SVGDocument.getLayerList())) {
                    contextMenuStrip1.Enabled = false;
                } else {
                    contextMenuStrip1.Enabled = true;
                }

                if (tlVectorControl1.SVGDocument.CurrentElement == null ||
                   tlVectorControl1.SVGDocument.CurrentElement.GetType().ToString() != "ItopVector.Core.Figure.Use") {

                    jxtMenuItem.Visible = false;
                } else {
                    if (tlVectorControl1.SVGDocument.CurrentElement.GetAttribute("xlink:href").Contains("Substation")) {

                        jxtMenuItem.Visible = true;
                    }
                }
                if (tlVectorControl1.Operation == ToolOperation.InterEnclosure) {
                    System.Collections.SortedList list = new SortedList();
                    glebeProperty gPro = new glebeProperty();
                    decimal s = 0;
                    ItopVector.Core.SvgElementCollection selCol = tlVectorControl1.SVGDocument.SelectCollection;
                    if (selCol.Count > 1) {
                        decimal ViewScale = 1;
                        string str_Scale = tlVectorControl1.SVGDocument.getViewScale();
                        if (str_Scale != "") {
                            ViewScale = Convert.ToDecimal(str_Scale);
                        }
                        string str_remark = "";
                        string str_selArea = "";
                        //string Elements = "";
                        Hashtable SelAreaCol = new Hashtable();
                        this.Cursor = Cursors.WaitCursor;
                        int t = 0;
                    Lab001:
                        t = t + 1;
                        XmlElement poly1 = (XmlElement)selCol[selCol.Count - t];
                        if (poly1.GetType().FullName != "ItopVector.Core.Figure.Polygon") {
                            // selCol.Remove(selCol[selCol.Count-1]);
                            goto Lab001;
                        }
                        frmWaiting wait = new frmWaiting();
                        wait.Show(this);
                        wait.Refresh();

                        GraphicsPath gr1 = new GraphicsPath();
                        //gr1.AddRectangle(TLMath.getRectangle(poly1));
                        gr1.AddPolygon(TLMath.getPolygonPoints(poly1));
                        gr1.CloseFigure();

                        for (int i = 0; i < selCol.Count - 1; i++) {
                            if (selCol[i].GetType().FullName == "ItopVector.Core.Figure.Polygon") {

                                string IsArea = ((XmlElement)selCol[i]).GetAttribute("IsArea");
                                if (IsArea != "") {
                                    XmlElement polyn = (XmlElement)selCol[i];
                                    GraphicsPath gr2 = new GraphicsPath();
                                    //gr2.AddRectangle(TLMath.getRectangle(polyn));
                                    gr2.AddPolygon(TLMath.getPolygonPoints(polyn));
                                    gr2.CloseFigure();
                                    Region region = new Region(gr1);
                                    region.Intersect(gr2);

                                    RectangleF rect = new RectangleF();
                                    rect = tlVectorControl1.SelectedRectangle(region);

                                    decimal sub_s = TLMath.getInterPolygonArea(region, rect, ViewScale);
                                    sub_s = TLMath.getNumber2(sub_s, tlVectorControl1.ScaleRatio);
                                    SelAreaCol.Add(polyn.GetAttribute("id"), sub_s);
                                    glebeProperty _gleProp = new glebeProperty();
                                    _gleProp.EleID = polyn.GetAttribute("id");
                                    _gleProp.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                                    IList gList = Services.BaseService.GetList("SelectglebePropertyByEleID", _gleProp);

                                    if (gList.Count > 0) {
                                        _gleProp = (glebeProperty)gList[0];
                                        list.Add(_gleProp.UseID, sub_s.ToString("#####.####"));
                                        str_selArea = str_selArea + _gleProp.EleID + "," + sub_s.ToString("#####.####") + ";";
                                        //str_remark = str_remark + "地块" + _gleProp.UseID + "选中面积为:" + sub_s.ToString() + "\r\n";
                                        s += sub_s;
                                    }
                                }
                            }
                            //if (selCol[i].GetType().FullName == "ItopVector.Core.Figure.Use")
                            //{
                            //    XmlElement e1 = (XmlElement)selCol[i];
                            //    string str_id = e1.GetAttribute("id");

                            //    substation _sub1 = new substation();
                            //    _sub1.EleID = str_id;
                            //    _sub1.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                            //    _sub1 = (substation)Services.BaseService.GetObject("SelectsubstationByEleID", _sub1);
                            //    if (_sub1 != null)
                            //    {
                            //        _sub1.glebeEleID = guid;
                            //        Services.BaseService.Update("Updatesubstation", _sub1);
                            //    }

                            //}

                        }
                        decimal nullpoly = TLMath.getNumber2(TLMath.getPolygonArea(TLMath.getPolygonPoints(poly1), 1), tlVectorControl1.ScaleRatio) - s;

                        for (int j = 0; j < list.Count; j++) {
                            if (Convert.ToString(list.GetByIndex(j)) != "") {
                                if (Convert.ToDecimal(list.GetByIndex(j)) < 1) {
                                    str_remark = str_remark + "地块" + list.GetKey(j).ToString() + "选中面积为:" + "0" + list.GetByIndex(j).ToString() + "(KM²)\r\n";
                                } else {
                                    str_remark = str_remark + "地块" + list.GetKey(j).ToString() + "选中面积为:" + list.GetByIndex(j).ToString() + "(KM²)\r\n";
                                }
                            }
                        }
                        XmlElement x1 = poly1;// (XmlElement)selCol[selCol.Count - 1];

                        gPro.UID = Guid.NewGuid().ToString();
                        gPro.EleID = x1.GetAttribute("id");
                        gPro.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                        gPro.ParentEleID = "0";
                        if (s != 0) {
                            gPro.Area = Convert.ToDecimal(s.ToString("#####.####"));
                        } else {
                            gPro.Area = 0;
                        }
                        gPro.SelSonArea = str_selArea;

                        if (nullpoly < 1) {
                            gPro.ObligateField10 = "0" + nullpoly.ToString("#####.####");
                        } else {
                            gPro.ObligateField10 = nullpoly.ToString("#####.####");
                        }

                        str_remark = str_remark + "\r\n 空白区域面积" + gPro.ObligateField10 + "(KM²)\r\n";
                        if (str_remark != "") {
                            str_remark = str_remark.Substring(0, str_remark.Length - 2);
                        }

                        gPro.Remark = str_remark;
                        wait.Close();
                        this.Cursor = Cursors.Default;
                        if (s < 1) {
                            MessageBox.Show("选中区域面积:" + "0" + s.ToString("#####.####") + "(KM²)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        } else {
                            MessageBox.Show("选中区域面积:" + s.ToString("#####.####") + "(KM²)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                        Services.BaseService.Create<glebeProperty>(gPro);

                        IDictionaryEnumerator ISelList = SelAreaCol.GetEnumerator();
                        while (ISelList.MoveNext()) {
                            glebeProperty sub_gle = new glebeProperty();
                            sub_gle.EleID = ISelList.Key.ToString();
                            sub_gle.ParentEleID = gPro.EleID;
                            sub_gle.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid;
                            Services.BaseService.Update("UpdateglebePropertySelArea", sub_gle);
                        }

                        tlVectorControl1.SVGDocument.SelectCollection.Clear();
                        tlVectorControl1.SVGDocument.CurrentElement = (SvgElement)x1;
                    }
                    // SubPrint = false;
                }
            } else {
                contextMenuStrip1.Enabled = false;
            }
        }
コード例 #36
0
ファイル: Utilities.cs プロジェクト: davelondon/dontstayin
        public static ListItem[] EnumToListItemArray(Type enumType, bool addBlankListItem, bool sortAlphabetically)
        {
            List<ListItem> listItems = new List<ListItem>();
            if (addBlankListItem)
            {
                listItems.Add(new ListItem("", ""));
            }
            Array enumValues = Enum.GetValues(enumType);

            if (sortAlphabetically)
            {
                SortedList enumSortedList = new SortedList();
                foreach (object value in enumValues)
                {
                    enumSortedList.Add(value.ToString(), (int)value);
                }
                
                for(int i=0; i < enumSortedList.Count; i++)
                {
                    listItems.Add(new ListItem(Utilities.CamelCaseToString(enumSortedList.GetKey(i).ToString()), (enumSortedList[enumSortedList.GetKey(i)]).ToString()));
                }
            }
            else
            {
                foreach (object value in enumValues)
                {
                    listItems.Add(new ListItem(Utilities.CamelCaseToString(value.ToString()), ((int)value).ToString()));
                }
            }
            return listItems.ToArray();
        }
コード例 #37
0
        /// <summary>The copy tool strip menu item_ click.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyForm win = null;

            try
            {
                DataGridView grid = (DataGridView)_resultsTabControl.SelectedTab.Controls[0];

                if (grid.SelectedCells.Count == 0)
                {
                    return;
                }

                win = new CopyForm();

                if (win.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                SortedList headers = new SortedList();
                SortedList rows = new SortedList();

                string delimiter = win.Delimiter;
                string line = string.Empty;

                for (int i = 0; i < grid.SelectedCells.Count; i++)
                {
                    DataGridViewCell cell = grid.SelectedCells[i];
                    DataGridViewColumn col = cell.OwningColumn;

                    if (!headers.ContainsKey(col.Index))
                    {
                        headers.Add(col.Index, col.Name);
                    }

                    if (!rows.ContainsKey(cell.RowIndex))
                    {
                        rows.Add(cell.RowIndex, cell.RowIndex);
                    }
                }

                if (win.IncludeHeaders)
                {
                    for (int i = 0; i < headers.Count; i++)
                    {
                        line += (string)headers.GetByIndex(i);
                        if (i != headers.Count)
                        {
                            line += delimiter;
                        }
                    }

                    line += "\r\n";
                }

                for (int i = 0; i < rows.Count; i++)
                {
                    DataGridViewRow row = grid.Rows[(int)rows.GetKey(i)];
                    DataGridViewCellCollection cells = row.Cells;

                    for (int j = 0; j < headers.Count; j++)
                    {
                        DataGridViewCell cell = cells[(int)headers.GetKey(j)];

                        if (cell.Selected)
                        {
                            line += cell.Value;
                        }

                        if (j != (headers.Count - 1))
                        {
                            line += delimiter;
                        }
                    }

                    line += "\r\n";
                }

                if (!string.IsNullOrEmpty(line))
                {
                    Clipboard.Clear();
                    Clipboard.SetText(line);

                    _hostWindow.SetStatus(this, "Selected data has been copied to your clipboard");
                }
            }
            finally
            {
                if (win != null)
                {
                    win.Dispose();
                }
            }
        }
コード例 #38
0
ファイル: SortedList.cs プロジェクト: yonder/mono
 public override Object GetKey(int index)
 {
     lock (host.SyncRoot) {
         return(host.GetKey(index));
     }
 }
コード例 #39
0
ファイル: CDataOperator.cs プロジェクト: jquery2005/GMIS
        } //InsertOneRec

        /// <summary>
        /// 修改一条记录
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="FieldValueList"></param>
        /// <returns></returns>
        public bool ModifyOneRec(string TableName, SortedList FieldValueList, SortedList PrimaryKeyList)
        {
            System.Data.SqlClient.SqlConnection conn;
            System.Data.SqlClient.SqlDataAdapter dbAdpter;  //数据适配器
            System.Data.SqlClient.SqlCommand dbCommand;  //数据操作命令
            System.Data.SqlClient.SqlCommandBuilder dbCommandBuilder; //提供自动生成表单的命令方法

            string WhereSql;

            WhereSql = this.GetWhereSql(PrimaryKeyList);

            conn = new SqlConnection(mConnectInfo);
            dbCommand = new SqlCommand();
            dbCommand.CommandText = "select * from " + TableName + WhereSql;
            dbCommand.Connection = conn;

            dbAdpter = new SqlDataAdapter(dbCommand);

            dbCommandBuilder = new SqlCommandBuilder(dbAdpter);

            DataTable dt = new DataTable(); ;

            try
            {
                conn.Open(); //建立数据库连接
                dbAdpter.Fill(dt);

                string FieldName;
                object FieldValue;

                //赋新值
                DataRow dr;
                for (int k = 0; k <= dt.Rows.Count - 1; k++)
                {
                    dr = dt.Rows[k];
                    for (int i = 0; i <= FieldValueList.Count - 1; i++)
                    {
                        FieldName = FieldValueList.GetKey(i).ToString();
                        FieldValue = FieldValueList.GetByIndex(i);
                        if (FieldValue == null) FieldValue = Convert.DBNull;
                        dr[FieldName] = FieldValue;
                        System.Diagnostics.Debug.WriteLine(FieldName + "=" + FieldValue);
                    }
                }

                dbAdpter.Update(dt);
                return true;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                throw new Exception("ModifyOneRec:" + ee.Message);
            }
            finally
            {
                conn.Close();
            }
        }//ModifyOneRec
コード例 #40
0
	// Get a value from the environment.
	public static String Environ(int Expression)
			{
			#if !ECMA_COMPAT
				SortedList list = new SortedList
					(Environment.GetEnvironmentVariables());
				if(Expression > 0 && Expression <= list.Count)
				{
					String key = (list.GetKey(Expression - 1) as String);
					if(key != null)
					{
						String value = (list[key] as String);
						if(value != null)
						{
							return key + "=" + value;
						}
					}
				}
			#endif
				return String.Empty;
			}
コード例 #41
0
ファイル: sortedlist.cs プロジェクト: SSCLI/sscli_20021101
 public override Object GetKey(int index)
 {
     lock (_root) {
         return(_list.GetKey(index));
     }
 }
コード例 #42
0
ファイル: CDataOperator.cs プロジェクト: jquery2005/GMIS
        } //AddOneRec

        /// <summary>
        /// 插入一条记录
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="FieldValueList"></param>
        /// <param name="LocatList"></param>
        /// <param name="BeforeID"></param>
        /// <returns></returns>
        public bool InsertOneRec(string TableName, SortedList FieldValueList, SortedList LocatList, long BeforeID, out bool ModifyOtherID)
        {
            SqlConnection conn; //数据库连接
            SqlDataAdapter dbAdpter;  //数据适配器
            SqlCommand dbCommand;  //数据操作命令
            SqlCommandBuilder dbCommandBuilder; //提供自动生成表单的命令方法
            SqlTransaction MyTransaction = null;  //事务定义

            string WhereSql;
            string LocateStr;
            long CurID = 0;
            string tempIDName;
            tempIDName = TableName.ToUpper() + "ID";

            WhereSql = this.GetWhereSql(LocatList);

            conn = new SqlConnection(mConnectInfo);
            dbCommand = new SqlCommand();
            dbCommand.Connection = conn;

            DataTable dt = new DataTable();
            ModifyOtherID = false;

            try
            {
                conn.Open(); //建立数据库连接

                MyTransaction = conn.BeginTransaction(); //开始事务
                dbCommand.Transaction = MyTransaction;

                //1.设置原来的所有记录为历史记录ZC9993='00'
                LocateStr = "Update " + TableName + " set ZC9993='00' " + WhereSql;
                dbCommand.CommandText = LocateStr;
                dbCommand.ExecuteNonQuery();

                //2.若插入的ID大于当前的ID,则将当前及其后的ID加100
                CurID = Convert.ToInt64(FieldValueList[tempIDName]);
                if (CurID >= BeforeID)
                {
                    LocateStr = "Update " + TableName + " set " + tempIDName + "=" + tempIDName + " + 100 " + WhereSql + " and " + tempIDName + ">=" + BeforeID;
                    dbCommand.CommandText = LocateStr;
                    dbCommand.ExecuteNonQuery();

                    ModifyOtherID = true; //修改其他ID标志位
                }

                //3.添加的记录的标志位ZC9993='10'
                LocateStr = "select * from " + TableName + WhereSql;
                dbCommand.CommandText = LocateStr;
                dbAdpter = new SqlDataAdapter(dbCommand);
                dbCommandBuilder = new SqlCommandBuilder(dbAdpter);

                dbAdpter.Fill(dt);

                string FieldName;
                object FieldValue;

                //赋新值
                DataRow dr = dt.NewRow();

                for (int i = 0; i <= FieldValueList.Count - 1; i++)
                {
                    FieldName = FieldValueList.GetKey(i).ToString();
                    FieldValue = FieldValueList.GetByIndex(i);
                    dr[FieldName] = FieldValue;
                }

                //新记录的标志位为10
                if (FieldValueList.ContainsKey("ZC9993"))
                {
                    dr["ZC9993"] = "10";
                }

                //添加一条记录
                dt.Rows.Add(dr);

                dbAdpter.Update(dt);

                //提交事务
                MyTransaction.Commit();

                return true;
            }
            catch (System.Data.SqlClient.SqlException ee)
            {
                MyTransaction.Rollback(); //事务回滚 
                ModifyOtherID = false;
                throw new Exception("InsertRecInMainSet:" + ee.Message);
            }
            finally
            {
                conn.Close();
            }
        } //InsertOneRec
コード例 #43
0
        /// <summary>
        /// 导出数据行
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="drSource"></param>
        /// <param name="currentExcelRow"></param>
        /// <param name="excelSheet"></param>
        /// <param name="excelWorkBook"></param>
        protected static void InsertCell(DataTable dtSource, DataRow drSource, NPOI.SS.UserModel.IRow currentExcelRow, NPOI.SS.UserModel.ISheet excelSheet, HSSFWorkbook excelWorkBook, NPOI.SS.UserModel.ICellStyle cellStyle_DateTime)
        {
            for (int cellIndex = 0; cellIndex < _listColumnsName.Count; cellIndex++)
            {
                //列名称
                string columnsName = _listColumnsName.GetKey(cellIndex).ToString();
                NPOI.SS.UserModel.ICell newCell = null;
                System.Type             rowType = drSource[columnsName].GetType();
                string drValue = drSource[columnsName].ToString().Trim();
                switch (rowType.ToString())
                {
                case "System.String":    //字符串类型
                    drValue = drValue.Replace("&", "&");
                    drValue = drValue.Replace(">", ">");
                    drValue = drValue.Replace("<", "<");
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(drValue);
                    break;

                case "System.DateTime":    //日期类型
                    DateTime dateV;
                    DateTime.TryParse(drValue, out dateV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(dateV);

                    //格式化显示
                    newCell.CellStyle = cellStyle_DateTime;

                    break;

                case "System.Boolean":    //布尔型
                    bool boolV = false;
                    bool.TryParse(drValue, out boolV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(boolV);
                    break;

                case "System.Int16":    //整型
                case "System.Int32":
                case "System.Int64":
                case "System.Byte":
                    int intV = 0;
                    int.TryParse(drValue, out intV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(intV.ToString());
                    break;

                case "System.Decimal":    //浮点型
                case "System.Double":
                    double doubV = 0;
                    double.TryParse(drValue, out doubV);
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(doubV);
                    break;

                case "System.DBNull":    //空值处理
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue("");
                    break;

                case "System.Guid":    //空值处理
                    newCell = currentExcelRow.CreateCell(cellIndex);
                    newCell.SetCellValue(drValue);
                    break;

                default:
                    throw (new Exception(rowType.ToString() + ":类型数据无法处理!"));
                }
            }
        }
コード例 #44
0
        private void OrdenarLista(ref ListBox listBox)
        {
            SortedList itens = new SortedList();

            foreach (ListItem item in listBox.Items)
            {
                itens.Add(item.Text, item);
            }

            listBox.Items.Clear();

            for (int cont = 0; cont < itens.Count; cont++)
            {
                listBox.Items.Add((ListItem)itens[itens.GetKey(cont)]);
            }
        }
コード例 #45
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();
		}
コード例 #46
0
 ///<summary>
 ///Uses the HelperClass to determine Active Directory server names.
 ///</summary>
 ///<returns>void</returns>
 ///<remarks>Builds dialog box of servers</remarks>
 private void CreateServerList(string servermask)
 {
     this.lb_FileSystemOptions.Items.Clear();
     clb_FileInfo.Items.Clear();
     SortedList sl = new SortedList();
     try
     {
         ActiveDirectoryListHelper hp = new ActiveDirectoryListHelper(this.serverLDAPloc);
         sl = hp.GetServerList(servermask);
     }
     catch (Exception e)
     {
         UpdateStatusStrip("Error retrieving server list");
         string mess = string.Format("{0} Exception caught", e);
         MessageBox.Show(mess, "Error in Profile Delete",
         MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     for (int i = 0; i < sl.Count; i++)
     {
         lb_FileSystemOptions.Items.Add(sl.GetKey(i));
     }
     UpdateStatusStrip(sl.Count + " Servers found");
 }