Contains() public method

public Contains ( Object key ) : bool
key Object
return bool
コード例 #1
0
        /// <summary>
        /// Gets MX records from answer collection and ORDERS them by preference.
        /// NOTE: Duplicate preference records are appended to end. 
        /// </summary>
        /// <returns></returns>
        internal MX_Record[] GetMxRecordsFromAnswers()
        {
            MX_Record[] retVal = null;

            try
            {
                SortedList mx            = new SortedList();
                ArrayList  duplicateList = new ArrayList();
                foreach(Dns_Answer answer in m_Answers){
                    if(answer.QTYPE == QTYPE.MX){
                        MX_Record mxRec = (MX_Record)answer.RecordObj;

                        if(!mx.Contains(mxRec.Preference)){
                            mx.Add(mxRec.Preference,mxRec);
                        }
                        else{
                            duplicateList.Add(mxRec);
                        }
                    }
                }

                MX_Record[] mxBuff = new MX_Record[mx.Count + duplicateList.Count];
                mx.Values.CopyTo(mxBuff,0);
                duplicateList.CopyTo(mxBuff,mx.Count);
                retVal = mxBuff;
            }
            catch{
            }

            return retVal;
        }
コード例 #2
0
 //return how closely an input string resembles a single memory entry
 protected int calculateMatchRate(ArrayList input, ArrayList memory)
 {
     int matchRate = 0;
     IEnumerator i = input.GetEnumerator();
     IEnumerator m = memory.GetEnumerator();
     while(i.MoveNext())
     {
         while(m.MoveNext())
         {
             SortedList isNewWord = new SortedList();
             string cc = (string)i.Current;
             string bb = (string)m.Current;
             cc.ToLower();
             bb.ToLower();
             //mehrfachwertung für ein wort vermeiden z.b. eine 3 für 3x "ich"
             if(!isNewWord.Contains(bb))
             {
                 isNewWord.Add(bb, bb);
                 if(cc == bb)
                 {
                     matchRate++;
                 }
             }
             isNewWord.Clear();
         }
     }
     return matchRate;
 }
コード例 #3
0
        private void RefreshRelatoriosPadrao()
        {
            System.Windows.Forms.ListViewItem lviItem;
            System.Collections.SortedList     sortLstRelatoriosPadrao = new System.Collections.SortedList();

            m_lvPadrao.Columns[0].Width = m_lvPadrao.Width - 20;

            m_lvPadrao.Items.Clear();

            // Ordenando e Dividindo os Relatorios
            mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow dtrwRelatorio;
            for (int nCont = 0; nCont < m_typDatSetTbRelatoriosPadrao.tbRelatorios.Rows.Count; nCont++)
            {
                dtrwRelatorio = (mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow)m_typDatSetTbRelatoriosPadrao.tbRelatorios.Rows[nCont];
                if (dtrwRelatorio.nIdRelatorio < 1)
                {                 // Padrao
                    if (!sortLstRelatoriosPadrao.Contains(dtrwRelatorio.strNomeRelatorio))
                    {
                        sortLstRelatoriosPadrao.Add(dtrwRelatorio.strNomeRelatorio, dtrwRelatorio);
                    }
                }
            }

            // Inserindo os Relatorios na Lista View
            for (int nCont = 0; nCont < sortLstRelatoriosPadrao.Count; nCont++)
            {
                dtrwRelatorio = (mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow)sortLstRelatoriosPadrao.GetByIndex(nCont);
                lviItem       = m_lvPadrao.Items.Add(dtrwRelatorio.strNomeRelatorio);
                lviItem.Tag   = dtrwRelatorio.nIdRelatorio;
                lviItem.Font  = new System.Drawing.Font(lviItem.Font, System.Drawing.FontStyle.Bold);
            }
        }
コード例 #4
0
        private void RefreshRelatoriosNormal()
        {
            System.Windows.Forms.ListViewItem lviItem;
            System.Collections.SortedList     sortLstRelatorios = new System.Collections.SortedList();

            m_lvCriados.Columns[0].Width = m_lvCriados.Width - 20;

            m_lvCriados.Items.Clear();

            // Ordenando e Dividindo os Relatorios
            mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow dtrwRelatorio;
            for (int nCont = 0; nCont < m_typDatSetTbRelatorios.tbRelatorios.Rows.Count; nCont++)
            {
                dtrwRelatorio = (mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow)m_typDatSetTbRelatorios.tbRelatorios.Rows[nCont];
                if (dtrwRelatorio.nIdRelatorio > 0 && dtrwRelatorio.nIdExportador == m_nIdExportador)
                {                 // Normal
                    if (!sortLstRelatorios.Contains(dtrwRelatorio.strNomeRelatorio))
                    {
                        sortLstRelatorios.Add(dtrwRelatorio.strNomeRelatorio, dtrwRelatorio);
                    }
                }
            }

            // Inserindo os Relatorios na Lista View
            for (int nCont = 0; nCont < sortLstRelatorios.Count; nCont++)
            {
                dtrwRelatorio = (mdlDataBaseAccess.Tabelas.XsdTbRelatorios.tbRelatoriosRow)sortLstRelatorios.GetByIndex(nCont);
                lviItem       = m_lvCriados.Items.Add(dtrwRelatorio.strNomeRelatorio);
                lviItem.Tag   = dtrwRelatorio.nIdRelatorio;
            }
        }
コード例 #5
0
        public void TestGetIsSynchronizedBasic()
        {
            SortedList slst1;
            string strValue;

            Task[] workers;
            Action ts1;
            int iNumberOfWorkers = 3;

            // Vanila test case - Synchronized returns an IList that is thread safe
            // We will try to test this by getting a number of threads to write some items
            // to a synchronized IList
            slst1 = new SortedList();
            _slst2 = SortedList.Synchronized(slst1);

            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => AddElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            //checking time
            Assert.Equal(_slst2.Count, _iNumberOfElements * iNumberOfWorkers);

            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                for (int j = 0; j < _iNumberOfElements; j++)
                {
                    strValue = "Thread worker " + i + "_" + j;
                    Assert.True(_slst2.Contains(strValue), "Error, Expected value not returned, " + strValue);
                }
            }

            // We can't make an assumption on the order of these items though
            //now we are going to remove all of these
            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => RemoveElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            Assert.Equal(0, _slst2.Count);

            // we will check IsSynchronized now
            Assert.False(slst1.IsSynchronized);
            Assert.True(_slst2.IsSynchronized);
        }
コード例 #6
0
 // name - имя инф. элемента
 // listIE - список сущ. инф. элементов
 private Element CreateIE(string name, SortedList allIE)
 {
     Element ie = null;
     if (!allIE.Contains(name))
     {
         ie = new Element(name);
         allIE.Add(name, ie);
     }
     else ie = (Element)allIE[name];
     return ie;
 }
コード例 #7
0
ファイル: SynchronizedTests.cs プロジェクト: johnhhm/corefx
        public void TestSynchronizedBasic()
        {
            SortedList slst1;
            String strValue;

            Task[] workers;
            Action ts1;
            Int32 iNumberOfWorkers = 3;

            slst1 = new SortedList();
            _slst2 = SortedList.Synchronized(slst1);

            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => AddElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            //checking time

            Assert.Equal(_slst2.Count, _iNumberOfElements * iNumberOfWorkers);


            for (int i = 0; i < iNumberOfWorkers; i++)
            {
                for (int j = 0; j < _iNumberOfElements; j++)
                {
                    strValue = "Thread worker " + i + "_" + j;

                    Assert.True(_slst2.Contains(strValue), "Error, Expected value not returned, " + strValue);
                }
            }

            //I dont think that we can make an assumption on the order of these items though
            //now we are going to remove all of these
            workers = new Task[iNumberOfWorkers];
            for (int i = 0; i < workers.Length; i++)
            {
                var name = "Thread worker " + i;
                ts1 = new Action(() => RemoveElements(name));
                workers[i] = Task.Run(ts1);
            }

            Task.WaitAll(workers);

            Assert.Equal(0, _slst2.Count);
            Assert.False(slst1.IsSynchronized);
            Assert.True(_slst2.IsSynchronized);
        }
コード例 #8
0
 public static string GetBDFDP(string key)
 {
     if (!_loaded)
     {
         //DeclareTypes(pathBDFDP, _nameBDFDP);
         DeclareTypes();
     }
     if (_nameBDFDP.Contains(key))
     {
         return((string)_nameBDFDP[key]);
     }
     else
     {
         return("");
     }
 }
コード例 #9
0
 static public int Contains(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         System.Object a1;
         checkType(l, 2, out a1);
         var ret = self.Contains(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #10
0
 public static string GetIdCV(string key)
 {
     if (_nameCV.Count == 0)
     {
         DeclareTypesCV();
     }
     if (_nameCV.Contains(key))
     {
         return((string)_nameCV[key]);
     }
     else
     {
         return("");
     }
 }
コード例 #11
0
        public void TestGetIsReadOnlyBasic()
        {
            String strValue;
            SortedList dic1;

            dic1 = new SortedList();
            for (int i = 0; i < 10; i++)
            {
                strValue = "String_" + i;
                dic1.Add(i, strValue);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.True(dic1.Contains(i));
            }

            //we'll do the ReadOnly test
            Assert.False(dic1.IsReadOnly);

            //we'll make sure by doing a modifiable things!!
            dic1.Remove(0);
            Assert.False(dic1.Contains(0));
        }
コード例 #12
0
ファイル: TaskStaticInfo.cs プロジェクト: windygu/ger20160318
 public static Type GetTaskType(string keyTask)
 {
     if (_classtypes.Count == 0)
     {
         DeclareTypes();
     }
     if (_classtypes.Contains(keyTask))
     {
         return((Type)_classtypes[keyTask]);
     }
     else
     {
         return(null);
     }
 }
コード例 #13
0
ファイル: mcMainForm.cs プロジェクト: rburchell/obsidian
        public mcServer AddServer()
        {
            mcServer Server = new mcServer();

            System.Random Rnd = new Random();

            /*
             * generate a random key.
             * this should break out eventually.
             */
            for (;;)
            {
                //100 chars should be sufficient entropy ;)...
                Server.HashKey = Server.HashKey + Rnd.Next(500000).ToString();
                if (!Servers.Contains(Server.HashKey))
                {
                    //we have generated a unique hashkey
                    Server.ServerPage.MyNode.Tag = Server.HashKey;
                    TreeNode lvi = new      TreeNode("My Status");
                    lvi.Tag = Server.HashKey;
                    tvcWindows.Nodes.Add(lvi);
                    Server.ServerPage.MyNode = lvi;

                    lvi     = new TreeNode("My Channels");
                    lvi.Tag = Server.HashKey;
                    Server.ServerPage.MyNode.Nodes.Add(lvi);
                    Server.ServerPage.ChannelsNode = lvi;

                    lvi     = new TreeNode("My Messages");
                    lvi.Tag = Server.HashKey;
                    Server.ServerPage.MyNode.Nodes.Add(lvi);
                    Server.ServerPage.MessagesNode = lvi;

                    lvi     = new TreeNode("My Buddies");
                    lvi.Tag = Server.HashKey;
                    Server.ServerPage.MyNode.Nodes.Add(lvi);
                    Server.ServerPage.BuddiesNode = lvi;

                    Servers.Add(Server.HashKey, Server);

                    this.tvcWindows.ExpandAll();

                    //fix: select this Server as active.
                    this.tvcWindows_AfterSelect(this, new TreeViewEventArgs(Server.ServerPage.MyNode, TreeViewAction.ByMouse));
                    return(Server);
                }
            }
        }
コード例 #14
0
        public static IDictionary BuildTextCache( TreeNode[] array )
        {
            IDictionary dict = new SortedList();

              foreach( TreeNode node in array )
              {
            if( dict.Contains( node.Text ) == false )
            {
              dict[ node.Text ] = new ArrayList();
            }

            ((IList)dict[ node.Text ]).Add( node );
              }

              return dict;
        }
コード例 #15
0
        /// <summary>
        /// Build TreeNodes caches for fast find and update
        /// </summary>
        public static IDictionary BuildTagsCache( TreeNode[] array )
        {
            IDictionary dict = new SortedList();

              foreach( TreeNode node in array )
              {
            int indexTag = ( node.Tag == null ) ? -1 : node.Tag.GetHashCode();

            if( dict.Contains( indexTag ) == false )
            {
              dict[ indexTag ] = new ArrayList();
            }

            ((IList)dict[ indexTag ]).Add( node );
              }

              return dict;
        }
コード例 #16
0
ファイル: IsSimpleOp.cs プロジェクト: xuchuansheng/GenXSource
		/// <summary>
		/// Tests if MultiPoint is simple.
		/// </summary>
		/// <param name="mp">Geometry to test.  Must be of type MultiPoint.</param>
		/// <returns>Returns True if geometry is simple.</returns>
		/// <remarks>A MultiPoint is simple if and only if it has no repeated points.</remarks>
		public bool IsSimple( MultiPoint mp )
		{
			if ( mp.IsEmpty() )
			{
				return true;
			}
			SortedList points = new SortedList();
			for ( int i = 0; i < mp.GetNumGeometries(); i++ ) 
			{
				Point pt = (Point) mp.GetGeometryN( i );
				Coordinate p = pt.GetCoordinate();
				if ( points.Contains( p ) )
				{
					return false;
				}
				points.Add( p, p );
			} //for ( int i = 0; i < mp.NumGeometries; i++ )
			return true;
		} // public bool IsSimple( MultiPoint mp )
コード例 #17
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();
        }
コード例 #18
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// A message handler for when the user releases the mouse button over the font image
        /// </summary>
        ///////////////////////////////////////////////////////////////////////////////////////////
        private void pictureBoxZoomFontImage_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // We are only handling left click right now
            if (e.Button != MouseButtons.Left)
            {
                return;
            }

            // If we are setting a glyph
            if (m_IsDraggingGlyph)
            {
                // Make sure the rectangle has positive values to be safe
                if (m_DraggingGlyphRect.Width < 0)
                {
                    m_DraggingGlyphRect.X     = m_DraggingGlyphRect.X + m_DraggingGlyphRect.Width;
                    m_DraggingGlyphRect.Width = (0 - m_DraggingGlyphRect.Width) + 1;
                }

                // Store the rectangle
                char curChar = (char)m_CurUnicodeChar;
                if (m_AddedChars.Contains(curChar))
                {
                    m_AddedChars[curChar] = m_DraggingGlyphRect;
                }
                else
                {
                    m_AddedChars.Add(curChar, m_DraggingGlyphRect);
                    labelFontChars.Text += curChar;
                }
                m_IsDraggingGlyph = false;

                // Step to the next character
                IncrementCurCharacter();
            }

            // We can't be dragging anymore
            m_DraggingStripIndex = -1;
            m_IsDraggingGlyph    = false;

            // Redraw
            pictureBoxZoomFontImage.Refresh();
        }
コード例 #19
0
 private void CandidateTest(Element ie, int index, SortedList subject, SortedList candidate)
 {
     if (subject.Contains(ie.Name)) return;
     if (!candidate.Contains(ie.Name))
     {
         // Если ie еще нет в списке кандидатов
         IE_Index ie_index = new IE_Index(ie);
         ie_index.Index.Add(index, 0);
         candidate.Add(ie.Name, ie_index);
     }
     else
     {
         // Если ie уже существует в списке кандидатов
         IE_Index ie_index = ((IE_Index)candidate[ie.Name]);
         // Проверяем не было ли ie с таким же инексом 
         // (т.е. не встречали ли мы его в данном индексе потока)
         if (!ie_index.Index.Contains(index))
             ie_index.Index.Add(index, 0);
     }
 }
コード例 #20
0
ファイル: StringUtil.cs プロジェクト: vardars/ci-factory
 public static string JoinUnique(string delimiter, params string[][] fragmentArrays)
 {
     SortedList list = new SortedList();
     foreach (string[] fragmentArray in fragmentArrays)
     {
         foreach (string fragment in fragmentArray)
         {
             if (! list.Contains(fragment))
                 list.Add(fragment, fragment);
         }
     }
     StringBuilder buffer = new StringBuilder();
     foreach (string value in list.Values)
     {
         if (buffer.Length > 0)
         {
             buffer.Append(delimiter);
         }
         buffer.Append(value);
     }
     return buffer.ToString();
 }
コード例 #21
0
ファイル: Differ.cs プロジェクト: Jeremiahf/wix3
        private RowCollection CompareTables(Output targetOutput, Table targetTable, Table updatedTable, out TableOperation operation)
        {
            RowCollection rows = new RowCollection();
            operation = TableOperation.None;

            // dropped tables
            if (null == updatedTable ^ null == targetTable)
            {
                if (null == targetTable)
                {
                    operation = TableOperation.Add;
                    rows.AddRange(updatedTable.Rows);
                }
                else if (null == updatedTable)
                {
                    operation = TableOperation.Drop;
                }
            }
            else // possibly modified tables
            {
                SortedList updatedPrimaryKeys = new SortedList();
                SortedList targetPrimaryKeys = new SortedList();

                // compare the table definitions
                if (0 != targetTable.Definition.CompareTo(updatedTable.Definition))
                {
                    // continue to the next table; may be more mismatches
                    this.OnMessage(WixErrors.DatabaseSchemaMismatch(targetOutput.SourceLineNumbers, targetTable.Name));
                }
                else
                {
                    this.IndexPrimaryKeys(targetTable, targetPrimaryKeys, updatedTable, updatedPrimaryKeys);

                    // diff the target and updated rows
                    foreach (DictionaryEntry targetPrimaryKeyEntry in targetPrimaryKeys)
                    {
                        string targetPrimaryKey = (string)targetPrimaryKeyEntry.Key;
                        bool keepRow = false;
                        RowOperation rowOperation = RowOperation.None;

                        Row compared = this.CompareRows(targetTable, targetPrimaryKeyEntry.Value as Row, updatedPrimaryKeys[targetPrimaryKey] as Row, out rowOperation, out keepRow);

                        if (keepRow)
                        {
                            rows.Add(compared);
                        }
                    }

                    // find the inserted rows
                    foreach (DictionaryEntry updatedPrimaryKeyEntry in updatedPrimaryKeys)
                    {
                        string updatedPrimaryKey = (string)updatedPrimaryKeyEntry.Key;

                        if (!targetPrimaryKeys.Contains(updatedPrimaryKey))
                        {
                            Row updatedRow = (Row)updatedPrimaryKeyEntry.Value;

                            updatedRow.Operation = RowOperation.Add;
                            updatedRow.SectionId = sectionDelimiter + updatedRow.SectionId;
                            rows.Add(updatedRow);
                        }
                    }
                }
            }

            return rows;
        }
コード例 #22
0
        public static void Generate()
        {
            // Check if the unicode files exist
            {
                FileInfo f1 = new FileInfo("CompositionExclusions.txt");
                FileInfo f2 = new FileInfo("UnicodeData.txt");
                bool tmpBool;
                if (File.Exists(f1.FullName))
                    tmpBool = true;
                else
                    tmpBool = Directory.Exists(f1.FullName);
                bool tmpBool2;
                if (File.Exists(f2.FullName))
                    tmpBool2 = true;
                else
                    tmpBool2 = Directory.Exists(f2.FullName);
                if (!tmpBool || !tmpBool2)
                {
                    Console.WriteLine("Unable to find UnicodeData.txt or CompositionExclusions.txt.");
                    Console.WriteLine("Please download the latest version of these file from:");
                    Console.WriteLine("http://www.unicode.org/Public/UNIDATA/");
                    System.Environment.Exit(1);
                }
            }

            ArrayList exclusions = new ArrayList();
            {
                StreamReader r = new StreamReader("CompositionExclusions.txt", System.Text.Encoding.Default);
                string line;
                while (null != (line = r.ReadLine()))
                {
                    line = stripComment(line);
                    line = line.Trim();
                    if (line.Length == 0)
                    {
                        // Empty line
                    }
                    else if (line.Length == 4)
                    {
                        exclusions.Add(line);
                    }
                    else
                    {
                        // Skip code points > 0xffff
                    }
                }
                r.Close();
            }

            // Read UnicodeData

            SortedList canonical = new SortedList();
            SortedList compatibility = new SortedList();
            SortedList combiningClasses = new SortedList();
            {
                StreamReader r = new StreamReader("UnicodeData.txt", Encoding.Default);
                string line;
                while (null != (line = r.ReadLine()))
                {
                    line = stripComment(line);
                    line = line.Trim();

                    if (line.Length == 0)
                    {
                        // Empty line
                    }
                    else
                    {
                        string[] f = split(line, ';');

                        if (f[0].Length == 4)
                        {
                            if (!f[5].Equals(""))
                            {
                                if (isCompatibilityMapping(f[5]))
                                {
                                    compatibility[f[0]] = stripCompatibilityTag(f[5]);
                                }
                                else
                                {
                                    compatibility[f[0]] = f[5];
                                    if (!exclusions.Contains(f[0]))
                                    {
                                        canonical[f[0]] = f[5];
                                    }
                                }
                            }
                            if (!f[3].Equals("0"))
                            {
                                //UPGRADE_TODO: Method 'java.lang.Integer.parseInt' was converted to 'System.Convert.ToInt32' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                                combiningClasses[(int)System.Convert.ToInt32(f[0], 16)] = f[3];
                            }
                        }
                        else
                        {
                            // Skip code points > 0xffff
                        }
                    }
                }
                r.Close();
            }

            // Recursively apply compatibility mappings
            while (true)
            {
                bool replaced = false;

                IEnumerator i = new HashSet(compatibility.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)compatibility[k];

                    string d = decompose(v, compatibility);
                    if (!d.Equals(v))
                    {
                        replaced = true;
                        compatibility[k] = d;
                    }
                }

                if (!replaced)
                {
                    break;
                }
            }

            // Eliminate duplicate mappings
            SortedList compatibilityKeys = new SortedList();
            ArrayList compatibilityMappings = new ArrayList();
            {
                IEnumerator i = new HashSet(compatibility.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)compatibility[k];

                    int index = compatibilityMappings.IndexOf(v);
                    if (index == -1)
                    {
                        index = compatibilityMappings.Count;
                        compatibilityMappings.Add(v);
                    }
                    compatibilityKeys[k] = (int)index;
                }
            }

            // Create composition tables
            SortedList firstMap = new SortedList();
            SortedList secondMap = new SortedList();
            {
                IEnumerator i = new HashSet(canonical.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)canonical[k];

                    string[] s = split(v, ' ');

                    if (s.Length == 2)
                    {
                        // If both characters have the same combining class, they
                        // won't be combined (in the sequence AB, B is blocked from
                        // A if both have the same combining class)
                        string cc1 = (string)combiningClasses[(int)System.Convert.ToInt32(s[0], 16)];
                        string cc2 = (string)combiningClasses[(int)System.Convert.ToInt32(s[1], 16)];
                        if (cc1 != null || (cc1 != null && cc1.Equals(cc2)))
                        {
                            // Ignore this composition
                            // TODO check this
                            //i.remove();
                            canonical.Remove(k);
                            continue;
                        }

                        if (firstMap.ContainsKey(s[0]))
                        {
                            int c = (int)firstMap[s[0]];
                            firstMap[s[0]] = (int)(c + 1);
                        }
                        else
                        {
                            firstMap[s[0]] = 1;
                        }

                        if (secondMap.ContainsKey(s[1]))
                        {
                            int c = (int)secondMap[s[1]];
                            secondMap[s[1]] = (int)(c + 1);
                        }
                        else
                        {
                            secondMap[s[1]] = 1;
                        }
                    }
                    else if (s.Length > 2)
                    {
                        Console.WriteLine("? wrong canonical mapping for " + k);
                        System.Environment.Exit(1);
                    }
                }
            }

            SortedList singleFirstComposition = new SortedList();
            SortedList singleSecondComposition = new SortedList();
            SortedList complexComposition = new SortedList();

            int composeLookupMax = 0;
            {
                IEnumerator i = new HashSet(canonical.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string) i.Current;
                    string v = (string) canonical[k];

                    string[] s = split(v, ' ');

                    if (s.Length == 2)
                    {
                        // TODO, check this
                        int first = 0;
                        if(firstMap.Contains(s[0]))
                            first = (int) firstMap[s[0]];

                        int second = 0;
                        if (secondMap.Contains(s[1]))
                            second = (int) secondMap[s[1]];
                        // TODO, check this

                        if (first == 1)
                        {
                            singleFirstComposition[s[0]] = new string[] { s[1], k };
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[0], 16));
                        }
                        else if (second == 1)
                        {
                            singleSecondComposition[s[1]] = new string[] { s[0], k };
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[1], 16));
                        }
                        else
                        {
                            if (complexComposition.ContainsKey(s[0]))
                            {
                                SortedList m = (SortedList)complexComposition[s[0]];
                                if (m.ContainsKey(s[1]))
                                {
                                    Console.WriteLine("? ambiguous canonical mapping for " + s[0]);
                                    System.Environment.Exit(1);
                                }
                                m[s[1]] = k;
                            }
                            else
                            {
                                SortedList m = new SortedList();
                                m[s[1]] = k;
                                complexComposition[s[0]] = m;
                            }
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[0], 16));
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[1], 16));
                        }
                    }
                }
            }

            Console.WriteLine("Generating CombiningClass.cs file...");

            // Dump combining classes
            {
                StreamWriter w = new StreamWriter("CombiningClass.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class CombiningClass");
                w.WriteLine("{");
                w.WriteLine("\tpublic static readonly int[,] c = new int[,] {");
                System.Text.StringBuilder index = new System.Text.StringBuilder();

                int count = 0;

                for (int i = 0; i < 256; i++)
                {
                    bool empty = true;

                    StringBuilder page = new StringBuilder();
                    page.Append("    { /* Page " + i + " */");

                    for (int j = 0; j < 256; j++)
                    {
                        int c = (int)((i << 8) + j);
                        string cc = (string)combiningClasses[c];

                        if (0 == (j & 31))
                        {
                            page.Append("\r\n      ");
                        }
                        if (cc == null)
                        {
                            page.Append("0, ");
                        }
                        else
                        {
                            page.Append(cc + ", ");
                            empty = false;
                        }
                    }
                    page.Append("\r\n    },");

                    index.Append("    ");

                    if (!empty)
                    {
                        w.WriteLine(page.ToString());
                        index.Append(count++);
                        index.Append(",\r\n");
                    }
                    else
                    {
                        index.Append("-1,\r\n");
                    }
                }
                w.WriteLine("  };\r\n");

                w.WriteLine("\tpublic static readonly int[] i = new int[] {");
                w.Write(index.ToString());
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating DecompositionKeys.cs file...");

            // Dump compatibility decomposition
            {
                StreamWriter w = new StreamWriter("DecompositionKeys.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class DecompositionKeys");
                w.WriteLine("{");

                w.WriteLine("\tpublic static readonly int[] k = new int[] {");
                IEnumerator i = new HashSet(compatibilityKeys.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    int index = ((int)compatibilityKeys[k]);
                    w.WriteLine("    '\\u" + k + "', " + index + ",");
                }
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating DecompositionMappings.cs file...");

            {
                StreamWriter w = new StreamWriter("DecompositionMappings.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class DecompositionMappings");
                w.WriteLine("{");
                w.WriteLine("\tpublic static readonly string[] m = new string[] {");
                IEnumerator i = compatibilityMappings.GetEnumerator();
                while (i.MoveNext())
                {
                    string m = (string)i.Current;
                    w.WriteLine("    \"" + toString(m) + "\",");
                }
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating Composition.cs file...");

            // Dump canonical composition
            {
                StreamWriter w = new StreamWriter("Composition.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class Composition");
                w.WriteLine("{");

                IEnumerator i;
                int index = 0;

                SortedList indices = new SortedList();

                i = new HashSet(complexComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string s0 = (string)i.Current;
                    indices[(int)System.Convert.ToInt32(s0, 16)] = (int)index;
                    index++;
                }

                int multiSecondStart = index;
                w.WriteLine("\t/* jagged Array */");
                w.WriteLine("\tpublic static readonly char[][] multiFirst = new char[][] {");
                //w.WriteLine("  public final static char[][] multiFirst = new char[][] {");
                i = new HashSet(complexComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string s0 = (string)i.Current;
                    SortedList m = (SortedList)complexComposition[s0];

                    SortedList line = new SortedList();
                    int maxIndex = 1;

                    System.Collections.IEnumerator i2 = new HashSet(m.Keys).GetEnumerator();
                    while (i2.MoveNext())
                    {
                        string s1 = (string)i2.Current;
                        string k = (string)m[s1];

                        int s1i = (int)System.Convert.ToInt32(s1, 16);

                        if (!indices.ContainsKey(s1i))
                        {
                            indices[s1i] = (int)index;
                            index++;
                        }
                        line[indices[s1i]] = k;
                        maxIndex = System.Math.Max(maxIndex, ((int)indices[s1i]));
                    }

                    w.Write("\tnew char[] { ");
                    for (int j = multiSecondStart; j <= maxIndex; j++)
                    {
                        if (line.ContainsKey((int)j))
                        {
                            string s = (string)line[(int)j];
                            w.Write("'" + toString(s) + "', ");
                        }
                        else
                        {
                            //w.Write("       0, ");
                            w.Write("'" + toString("0000") + "', ");
                        }
                    }
                    w.WriteLine("},");
                }
                w.WriteLine("  };");

                int singleFirstStart = index;

                w.WriteLine("\tpublic static readonly char[,] singleFirst = new char[,] {");
                i = new HashSet(singleFirstComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string[] v = ((string[])singleFirstComposition[k]);
                    w.WriteLine("    { '" + toString(v[0]) + "', '" + toString(v[1]) + "' },");

                    if (indices.ContainsKey((int)System.Convert.ToInt32(k, 16)))
                    {
                        Console.WriteLine(k + " already indexed!");
                    }

                    indices[(int)System.Convert.ToInt32(k, 16)] = (int)index;
                    index++;
                }
                w.WriteLine("  };");

                int singleSecondStart = index;

                w.WriteLine("\tpublic static readonly char[,] singleSecond = new char[,] {");
                i = new HashSet(singleSecondComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string[] v = ((string[])singleSecondComposition[k]);
                    w.WriteLine("    { '" + toString(v[0]) + "', '" + toString(v[1]) + "' },");

                    indices[(int)System.Convert.ToInt32(k, 16)] = (int)index;
                    index++;
                }
                w.WriteLine("  };");

                w.WriteLine("\tpublic static readonly int multiSecondStart = " + multiSecondStart + ";");
                w.WriteLine("\tpublic static readonly int singleFirstStart = " + singleFirstStart + ";");
                w.WriteLine("\tpublic static readonly int singleSecondStart = " + singleSecondStart + ";");

                System.Text.StringBuilder compositionPages = new System.Text.StringBuilder();

                w.WriteLine("\tpublic static readonly int[] composePage = new int[] {");
                int pageCount = 0;
                for (int j = 0; j * 256 < composeLookupMax + 255; j++)
                {
                    bool empty = true;
                    StringBuilder page = new StringBuilder();
                    for (int k = 0; k < 256; k++)
                    {
                        if (k % 16 == 0)
                        {
                            page.Append("\r\n      ");
                        }
                        if (indices.ContainsKey((int)(j * 256 + k)))
                        {
                            page.Append(indices[(int)(j * 256 + k)]);
                            page.Append(", ");
                            empty = false;
                        }
                        else
                        {
                            page.Append("-1, ");
                        }
                    }

                    if (empty)
                    {
                        w.WriteLine("    -1,");
                    }
                    else
                    {
                        w.WriteLine("    " + pageCount + ",");
                        compositionPages.Append("\t{");
                        compositionPages.Append(page);
                        compositionPages.Append("\r\n    },\r\n");
                        pageCount++;
                    }
                }
                w.WriteLine("  };");
                //w.WriteLine("\t/* jagged Array */");
                w.WriteLine("\tpublic static readonly int[,] composeData = new int[,] {");
                w.Write(compositionPages);
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Finished!");
        }
コード例 #23
0
ファイル: SortedListTest.cs プロジェクト: ItsVeryWindy/mono
		public void TestContains ()
		{
			SortedList sl1 = new SortedList (55);
			for (int i = 0; i <= 50; i++) { sl1.Add ("kala " + i, i); }

			try {
				if (sl1.Contains (null)) {
				}
				Assert.Fail ("#A");
			} catch (ArgumentNullException) {
			}

			Assert.IsTrue (sl1.Contains ("kala 17"), "#B1");
			Assert.IsFalse (sl1.Contains ("ohoo"), "#B2");
		}
コード例 #24
0
ファイル: RoutingTester.cs プロジェクト: johnynek/brunet
    public static void Main(string []args) {
      if (args.Length < 1) {
	Console.WriteLine("please specify the number edge protocol."); 
        Environment.Exit(0);
      }
      if (args.Length < 2) {
        Console.WriteLine("please specify the number of p2p nodes."); 
        Environment.Exit(0);
      }
      if (args.Length < 3) {
        Console.WriteLine("please specify the number of missing edges."); 
        Environment.Exit(0);
      }
      string proto = "function";
      try {
	proto = args[0].Trim();
      } catch(Exception) {}

      bool tunnel = false;
      int base_port = 54000;
      int network_size = Int32.Parse(args[1]);
      int missing_count = Int32.Parse(args[2]);
      try {
	tunnel = args[3].Trim().Equals("tunnel");
      } catch (Exception) {}

      Console.WriteLine("use tunnel edges: {0}", tunnel);

      Random rand = new Random();

      ArrayList missing_edges = new ArrayList();
      for (int i = 0; i < missing_count; i++) {
	int idx = -1;
	int left, right;
	do {
	  idx = rand.Next(0, network_size);
	  left = (idx + 1)%network_size;
	  if (idx == 0) {
	    right = network_size - 1;
	  } else {
	    right = idx - 1;
	  }
	} while (missing_edges.Contains(idx));// ||
	//missing_edges.Contains(left) ||
	//missing_edges.Contains(right));
	
	Console.WriteLine("Will drop a left edge on idx {0}: ", idx);
	missing_edges.Add(idx);
      }
      
      //
      // Sort missing edges.
      //
      missing_edges.Sort();
      SortedList dist = new SortedList();
      //
      // Compute the average distance between missing edges. 
      //
      if (missing_count > 1) {
	for (int i = 0; i < missing_count; i++) {
	  int idx = (int) missing_edges[i];
	  int idx_next;
	  int d;
	  if (i == missing_count - 1) {
	    idx_next = (int) missing_edges[0];
	    d = (network_size - 1) - idx + idx_next;
	  } else {
	    idx_next = (int) missing_edges[i+1];
	    d = idx_next - idx - 1;
	  }
	  if (!dist.Contains(d)) {
	    dist[d] = 0;
	  } else {
	    int c = (int) dist[d];
	    dist[d] = c + 1;
	  }
	}
      }
      double sum = 0.0;
      int num = 0;
      Console.WriteLine("distribution of missing edges separation");
      foreach(DictionaryEntry de in dist) {
	int k = (int) de.Key;
	int c = (int) de.Value;
	Console.WriteLine("{0} {1}", k, c);
	sum = sum + k*c;
	num = num + c;
      }

      Console.WriteLine("average separation: {0}", (double) sum/num);
      string brunet_namespace = "testing";
      Console.WriteLine("Initializing...");

      ArrayList RemoteTA = new ArrayList();
      for(int i = 0; i < network_size; i++) {
	if (proto.Equals("udp")) {
	  RemoteTA.Add(TransportAddressFactory.CreateInstance("brunet.udp://localhost:" + (base_port + i)));
	} else if (proto.Equals("function")) { 
	  RemoteTA.Add(TransportAddressFactory.CreateInstance("brunet.function://localhost:" + (base_port + i)));
	}
      }

      for(int i = 0; i < network_size; i++) {
        AHAddress address = new AHAddress(new RNGCryptoServiceProvider());
        Node node = new StructuredNode(address, brunet_namespace);
        _sorted_node_list.Add((Address) address, node);
	_node_list.Add(node);
	RouteTestHandler test_handler = new RouteTestHandler();
	node.GetTypeSource(new PType(routing_test)).Subscribe(test_handler, address.ToMemBlock());
	RpcManager rpc_man = node.Rpc;
	rpc_man.AddHandler("rpc_routing_test", new  RpcRoutingTestHandler(node));
      }

      for (int i = 0; i < network_size; i++) {
	Node node = (Node) _sorted_node_list.GetByIndex(i);
	Console.WriteLine("Configuring node: {0} ", node.Address);
	TAAuthorizer ta_auth = null;
	if (missing_edges.Contains(i)) {
	  int remote_port;
	  if (i == network_size - 1) {
	    remote_port = base_port;
	  } else {
	    remote_port = base_port + i + 1;
	  }

	  PortTAAuthorizer port_auth = new PortTAAuthorizer(remote_port);
	  Console.WriteLine("Adding a port TA authorizer at: {0} for remote port: {1}", base_port + i, remote_port);
	  ArrayList arr_tas = new ArrayList();
	  arr_tas.Add(port_auth);
	  arr_tas.Add(new ConstantAuthorizer(TAAuthorizer.Decision.Allow));
	  ta_auth = new SeriesTAAuthorizer(arr_tas);
	}
	
	if (proto.Equals("udp")) { 
	  node.AddEdgeListener(new UdpEdgeListener(base_port + i, null, ta_auth));
	} else if(proto.Equals("function")) {
	  node.AddEdgeListener(new FunctionEdgeListener(base_port + i, -1.00, ta_auth));
	}
	
	if (tunnel) {
	  Console.WriteLine("Adding a tunnel edge listener");
	  node.AddEdgeListener(new Tunnel.TunnelEdgeListener(node));
	}
	_node_to_port[node] = base_port + i;
        node.RemoteTAs = RemoteTA;	
      }

      //start nodes one by one.
      for (int i  = 0; i < network_size; i++) {
	Node node = (Node) _node_list[i];
	Console.WriteLine("Starting node: {0}, {1}", i, node.Address);
        node.Connect();
	Console.WriteLine("Going to sleep for 2 seconds.");
        System.Threading.Thread.Sleep(2000);
      }

      //wait for 300000 more seconds
      Console.WriteLine("Going to sleep for 300000 seconds.");
      System.Threading.Thread.Sleep(300000);
      bool complete = CheckStatus();

      int count = 0;
      //
      // Send a large number of packets as exact packets to random destinations
      // and make sure exact routing is perfect.
      //
      
      for (int i = 0; i < network_size; i++) {
	for (int j = 0; j < network_size; j++) {
	  
	  int src_idx = i;
	  int dest_idx = j;
	  Node src_node = (Node) _sorted_node_list.GetByIndex(src_idx);
	  Node dest_node = (Node) _sorted_node_list.GetByIndex(dest_idx);
	  //Console.WriteLine("{0} -> {1}", src_idx, dest_idx);
	  Address dest_address = (Address) dest_node.Address;
	  ISender s = new AHExactSender(src_node, dest_address);
	  MemBlock p = dest_address.ToMemBlock();
	  s.Send(new CopyList(new PType(routing_test), p));
	  _sent++;
	  //System.Threading.Thread.Sleep(10);
	  s.Send(new CopyList(new PType(routing_test), p));
	  _sent++;
	  //System.Threading.Thread.Sleep(10);
	}
      }
      //wait for 10 more seconds
      Console.WriteLine("Going to sleep for 10 seconds.");
      System.Threading.Thread.Sleep(10000);      
      Console.WriteLine("Final statistics");
      lock(_class_lock) {
	Console.WriteLine("Sent: {0}, Received: {1}, Wrongly routed: {2}", 
			  _sent, _received, _wrongly_routed);
      }

      int missing_rpcs = 0;
      int correct_rpcs = 0;
      int incorrect_rpcs = 0;
      Hashtable queue_to_address = new Hashtable();
      for (int i = 0; i < network_size; i++) {
	for (int j = 0; j < network_size; j++) {
	  
	  int src_idx = i;
	  int dest_idx = j;
	  Node src_node = (Node) _sorted_node_list.GetByIndex(src_idx);
	  Node dest_node = (Node) _sorted_node_list.GetByIndex(dest_idx);
	  //Console.WriteLine("{0} -> {1}", src_idx, dest_idx);
	  Address dest_address = (Address) dest_node.Address;
	  ISender s = new AHExactSender(src_node, dest_address);
	  RpcManager rpc_man = src_node.Rpc;
	  Channel q = new Channel();
	  lock (_class_lock) {
	    queue_to_address[q] = dest_address;
	  }
	  q.CloseAfterEnqueue();
	  q.CloseEvent += delegate(object o, EventArgs cargs) {
	    lock(_class_lock) {
	      Channel qu = (Channel) o;
	      if (qu.Count == 0) {
		missing_rpcs++;
	      }
	      queue_to_address.Remove(qu);
	    }
	  };
	  q.EnqueueEvent += delegate(object o, EventArgs cargs) {
	    lock(_class_lock) {
	      Channel qu = (Channel) o;
	      RpcResult rpc_reply = (RpcResult) qu.Peek();
	      byte []result = (byte[]) rpc_reply.Result;
	      Address target = new AHAddress(result);
	      if (target.Equals(queue_to_address[qu])) {
		correct_rpcs++;
	      } else {
		incorrect_rpcs++;
	      }
	    }
	  };
	  rpc_man.Invoke(s, q, "rpc_routing_test.GetIdentification", new object[]{});
	}
      }
      
      //wait for 10 more seconds
      while (true) {
	int c = -1;
	lock(_class_lock) {
	  c = incorrect_rpcs + missing_rpcs + correct_rpcs;
	}
	if (c < network_size*network_size) {
	  Console.WriteLine("Going to sleep for 10 seconds.");
	  System.Threading.Thread.Sleep(10000);
	} else {
	  break;
	}
      }
      
      Console.WriteLine("Final statistics");
      Console.WriteLine("correct rpcs: {0}, incorrect rpcs: {1}, missing rpcs: {2}", 
			correct_rpcs, incorrect_rpcs, missing_rpcs);
      
      System.Environment.Exit(1);
    }
コード例 #25
0
        public static Hashtable FillFeatureCache(ITable inputSignsTable, int inFromIDFI, int inToIDFI,
                                                 IFeatureClass inputLineFeatures, string linesIDFieldName,
                                                 ITrackCancel trackcancel)
        {
            // make and fill a SortedList from the IDs referenced in the table

            // for MultiNet data, there is only one ID field, so its index will be
            // passed in as inFromIDFI, while -1 will be passed in to inToIDFI.

            SortedList IDs = new System.Collections.SortedList();

            ICursor inCursor = inputSignsTable.Search(null, true);
            IRow row;

            long fromID, toID;
            bool exists;
            int cancelCheckInterval = 100;

            if (inToIDFI == -1)
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);
                }
            }
            else
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));
                    toID = Convert.ToInt64(row.get_Value(inToIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);

                    exists = IDs.Contains(toID);
                    if (!exists)
                        IDs.Add(toID, toID);
                }
            }

            // make the query filter for fetching features

            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.SubFields = "*";

            // Now fetch batches of features

            long currID;
            int numFeaturesPerQuery = 200;
            int numToFetch = IDs.Count;
            int totalRemaining, totalDone = 0;

            int linesIDFieldIndex = inputLineFeatures.FindField(linesIDFieldName);

            Hashtable outputFeatures = new System.Collections.Hashtable((int)numToFetch);

            if (numFeaturesPerQuery > numToFetch)
                numFeaturesPerQuery = numToFetch;

            while (totalDone < numToFetch)
            {
                // Populate the QueryDef Where clause IN() statement for the current batch of features.
                // This is going to be very slow unless linesIDFieldName is indexed and this is why
                // we added a warning to the GP message window if this is the case.  If you cannot
                // index linesIDFieldName, then this code would run faster scanning the whole feature
                // class looking for the records we need (no Where clause).

                string whereClause = linesIDFieldName + " IN(";

                for (int i = 0; i < numFeaturesPerQuery; i++)
                {
                    currID = Convert.ToInt64(IDs.GetByIndex(totalDone + i), System.Globalization.CultureInfo.InvariantCulture);
                    whereClause += Convert.ToString(currID, System.Globalization.CultureInfo.InvariantCulture);
                    if (i != (numFeaturesPerQuery - 1))
                        whereClause += ",";
                    else
                        whereClause += ")";
                }

                queryFilter.WhereClause = whereClause;

                // select the features

                IFeatureCursor inputFeatureCursor = inputLineFeatures.Search(queryFilter, false);

                // get the features

                IFeature feature;

                while ((feature = inputFeatureCursor.NextFeature()) != null)
                {
                    // keep a copy of the OID and shape of feature - skip records that cause errors
                    // (perhaps pass the GPMessages in and log warnings in there if you need to log exceptions)

                    try
                    {
                        FeatureData data = new FeatureData(feature.OID, feature.ShapeCopy);
                        outputFeatures.Add(Convert.ToInt64(feature.get_Value(linesIDFieldIndex)), data);
                    }
                    catch
                    {
                    }

                    if ((totalDone % cancelCheckInterval) == 0)
                    {
                        // check for user cancel

                        if (trackcancel != null && !trackcancel.Continue())
                            throw (new COMException("Function cancelled."));
                    }
                }

                // finished? set up for next batch

                totalDone += numFeaturesPerQuery;

                totalRemaining = numToFetch - totalDone;
                if (totalRemaining > 0)
                {
                    if (numFeaturesPerQuery > totalRemaining)
                        numFeaturesPerQuery = totalRemaining;
                }
            }

            return outputFeatures;
        }
コード例 #26
0
        /// <devdoc>
        ///    <para>
        ///       Generates code for the specified CodeDom based compile unit start
        ///       representation.
        ///    </para>
        /// </devdoc>
        private  void GenerateCompileUnitStart(CodeCompileUnit e) {
        
            if (e.StartDirectives.Count > 0) {
                GenerateDirectives(e.StartDirectives);
            }
        
            Output.WriteLine("//------------------------------------------------------------------------------");
            Output.Write("// <");
            Output.WriteLine(SR.GetString(SR.AutoGen_Comment_Line1));
            Output.Write("//     ");
            Output.WriteLine(SR.GetString(SR.AutoGen_Comment_Line2));
            Output.Write("//     ");
            Output.Write(SR.GetString(SR.AutoGen_Comment_Line3));
            Output.WriteLine(System.Environment.Version.ToString());
            Output.WriteLine("//");
            Output.Write("//     ");
            Output.WriteLine(SR.GetString(SR.AutoGen_Comment_Line4));
            Output.Write("//     ");
            Output.WriteLine(SR.GetString(SR.AutoGen_Comment_Line5));
            Output.Write("// </");
            Output.WriteLine(SR.GetString(SR.AutoGen_Comment_Line1));            
            Output.WriteLine("//------------------------------------------------------------------------------");
            Output.WriteLine("");

            SortedList importList;            
            // CSharp needs to put assembly attributes after using statements.
            // Since we need to create a empty namespace even if we don't need it,
            // using will generated after assembly attributes.
            importList = new SortedList(StringComparer.Ordinal);
            foreach (CodeNamespace nspace in e.Namespaces) {
                if( String.IsNullOrEmpty(nspace.Name)) {
                    // mark the namespace to stop it generating its own import list
                    nspace.UserData["GenerateImports"] = false;

                    // Collect the unique list of imports
                    foreach (CodeNamespaceImport import in nspace.Imports) {
                        if (!importList.Contains(import.Namespace)) {
                            importList.Add(import.Namespace, import.Namespace);
                        }
                    }
                }
            }

            // now output the imports
            foreach(string import in importList.Keys) {
                Output.Write("using ");
                OutputIdentifier(import);
                Output.WriteLine(";");
            }
            if( importList.Keys.Count > 0) {
                Output.WriteLine("");
            }

            // in C# the best place to put these is at the top level.
            if (e.AssemblyCustomAttributes.Count > 0) {
                GenerateAttributes(e.AssemblyCustomAttributes, "assembly: ");
                Output.WriteLine("");
            }
            
        }
コード例 #27
0
        /// <summary>
        /// Set up the print job. Save information from print dialog
        /// and print document for easy access. Also sets up the rows
        /// and columns that will be printed. At this point, we're 
        /// collecting all columns in colstoprint. This will be broken
        /// up into pagesets later on 
        /// </summary>
        /// <param name="pd">The print dialog the user just filled out</param>
        void SetupPrint(PrintDialog pd)
        {
            //-----------------------------------------------------------------
            // get info on the limits of the printer's actual print area available. Convert
            // to int's to work with margins.
            //-----------------------------------------------------------------
            int hardx = (int)Math.Round(printDoc.DefaultPageSettings.HardMarginX);
            int hardy = (int)Math.Round(printDoc.DefaultPageSettings.HardMarginY);
            int printareawidth;
            if (printDoc.DefaultPageSettings.Landscape)
                printareawidth = (int)Math.Round(printDoc.DefaultPageSettings.PrintableArea.Height);
            else
                printareawidth = (int)Math.Round(printDoc.DefaultPageSettings.PrintableArea.Width);

            //-----------------------------------------------------------------
            // set the print area we're working within
            //-----------------------------------------------------------------

            pageHeight = printDoc.DefaultPageSettings.Bounds.Height;
            pageWidth = printDoc.DefaultPageSettings.Bounds.Width;

            //-----------------------------------------------------------------
            // Set the printable area: margins and pagewidth
            //-----------------------------------------------------------------

            // Set initial printer margins 
            printmargins = printDoc.DefaultPageSettings.Margins;

            // adjust for when the margins are less than the printer's hard x/y limits
            printmargins.Right = (hardx > printmargins.Right) ? hardx : printmargins.Right;
            printmargins.Left = (hardx > printmargins.Left) ? hardx : printmargins.Left;
            printmargins.Top = (hardy > printmargins.Top) ? hardy : printmargins.Top;
            printmargins.Bottom = (hardy > printmargins.Bottom) ? hardy : printmargins.Bottom;

            // Now, we can calc default print width, again, respecting the printer's limitations
            printWidth = pageWidth - printmargins.Left - printmargins.Right;
            printWidth = (printWidth > printareawidth) ? printareawidth : printWidth;

            //-----------------------------------------------------------------
            // Figure out which pages / rows to print
            //-----------------------------------------------------------------

            // save print range 
            printRange = pd.PrinterSettings.PrintRange;

            // pages to print handles "some pages" option
            if (PrintRange.SomePages == printRange)
            {
                // set limits to only print some pages
                fromPage = pd.PrinterSettings.FromPage;
                toPage = pd.PrinterSettings.ToPage;
            }
            else
            {
                // set extremes so that we'll print all pages
                fromPage = 0;
                toPage = 2147483647;
            }

            //-----------------------------------------------------------------
            // set up the rows and columns to print
            //-----------------------------------------------------------------

            // rows to print (handles "selection" and "current page" options
            if (PrintRange.Selection == printRange)
            {
                // if DGV has rows selected, it's easy, selected rows and all visible columns
                if (0 != dgv.SelectedRows.Count)
                {
                    rowstoprint = dgv.SelectedRows;
                    colstoprint = new List<object>(dgv.Columns.Count);
                    foreach (DataGridViewColumn col in dgv.Columns) if (col.Visible) colstoprint.Add(col);
                }
                // if selected columns, then all rows, and selected columns
                else if (0 != dgv.SelectedColumns.Count)
                {
                    rowstoprint = dgv.Rows;
                    colstoprint = dgv.SelectedColumns;
                }
                // we just have a bunch of selected cells so we have to do some work
                else
                {
                    // set up sorted lists. the selectedcells method does not guarantee
                    // that the cells will always be in left-right top-bottom order. 
                    SortedList temprowstoprint = new SortedList(dgv.SelectedCells.Count);
                    SortedList tempcolstoprint = new SortedList(dgv.SelectedCells.Count);

                    // for each selected cell, add unique rows and columns
                    int colindex, rowindex;
                    foreach (DataGridViewCell cell in dgv.SelectedCells)
                    {
                        colindex = cell.ColumnIndex;
                        rowindex = cell.RowIndex;

                        // add unique rows
                        if (!temprowstoprint.Contains(rowindex))
                            temprowstoprint.Add(rowindex, dgv.Rows[rowindex]);

                        // add unique columns
                        if (!tempcolstoprint.Contains(colindex))
                            tempcolstoprint.Add(colindex, dgv.Columns[colindex]);
                    }

                    // Move the now-duplicate free columns and rows to our list of what to print
                    rowstoprint = new List<object>(temprowstoprint.Count);
                    foreach (object item in temprowstoprint.Values) rowstoprint.Add(item);
                    colstoprint = new List<object>(tempcolstoprint.Count);
                    foreach (object item in tempcolstoprint.Values) colstoprint.Add(item);
                }
            }
            // if current page was selected, print visible columns for the
            // displayed rows                
            else if (PrintRange.CurrentPage == printRange)
            {
                // create lists
                rowstoprint = new List<object>(dgv.DisplayedRowCount(true));
                colstoprint = new List<object>(dgv.Columns.Count);

                // select all visible rows on displayed page
                for (int i = dgv.FirstDisplayedScrollingRowIndex;
                    i < dgv.FirstDisplayedScrollingRowIndex + dgv.DisplayedRowCount(true);
                    i++)
                {
                    DataGridViewRow row = dgv.Rows[i];
                    if (row.Visible) rowstoprint.Add(row);
                }

                // select all visible columns
                colstoprint = new List<object>(dgv.Columns.Count);
                foreach (DataGridViewColumn col in dgv.Columns) if (col.Visible) colstoprint.Add(col);
            }
            // this is the default for print all - everything marked visible will be printed
            else
            {
                // select all visible rows and all visible columns
                rowstoprint = new List<object>(dgv.Rows.Count);
                foreach (DataGridViewRow row in dgv.Rows) if (row.Visible) rowstoprint.Add(row);

                colstoprint = new List<object>(dgv.Columns.Count);
                foreach (DataGridViewColumn col in dgv.Columns) if (col.Visible) colstoprint.Add(col);
            }

            // Reorder columns based on Display Index (if the programmer or user has
            // changed the column display order we want to respect it in the printout)
            SortedList displayorderlist = new SortedList(colstoprint.Count);
            foreach (DataGridViewColumn col in colstoprint) displayorderlist.Add(col.DisplayIndex, col);
            colstoprint.Clear();
            foreach (object item in displayorderlist.Values) colstoprint.Add(item);

            // Adjust override list to have the same number of entries as colstoprint
            foreach (DataGridViewColumn col in colstoprint)
                if (publicwidthoverrides.ContainsKey(col.Name))
                    colwidthsoverride.Add(publicwidthoverrides[col.Name]);
                else
                    colwidthsoverride.Add(-1);

            //for (int i = colwidthsoverride.Count; i < colstoprint.Count; i++)
            //    colwidthsoverride.Add(-1);

            // Measure the print area
            measureprintarea(printDoc.PrinterSettings.CreateMeasurementGraphics());

            // Count the pages
            totalpages = TotalPages();

        }
 private static SortedList VerifyResourceNames(Dictionary<string, ResourceData> resourceList, CodeDomProvider codeProvider, ArrayList errors, out Hashtable reverseFixupTable)
 {
     reverseFixupTable = new Hashtable(0, StringComparer.InvariantCultureIgnoreCase);
     SortedList list = new SortedList(StringComparer.InvariantCultureIgnoreCase, resourceList.Count);
     foreach (KeyValuePair<string, ResourceData> pair in resourceList)
     {
         string key = pair.Key;
         if ((string.Equals(key, "ResourceManager") || string.Equals(key, "Culture")) || (typeof(void) == pair.Value.Type))
         {
             errors.Add(key);
         }
         else
         {
             if (((key.Length <= 0) || (key[0] != '$')) && (((key.Length <= 1) || (key[0] != '>')) || (key[1] != '>')))
             {
                 if (!codeProvider.IsValidIdentifier(key))
                 {
                     string str2 = VerifyResourceName(key, codeProvider, false);
                     if (str2 == null)
                     {
                         errors.Add(key);
                         goto Label_0185;
                     }
                     string item = (string) reverseFixupTable[str2];
                     if (item != null)
                     {
                         if (!errors.Contains(item))
                         {
                             errors.Add(item);
                         }
                         if (list.Contains(str2))
                         {
                             list.Remove(str2);
                         }
                         errors.Add(key);
                         goto Label_0185;
                     }
                     reverseFixupTable[str2] = key;
                     key = str2;
                 }
                 ResourceData data = pair.Value;
                 if (!list.Contains(key))
                 {
                     list.Add(key, data);
                 }
                 else
                 {
                     string str4 = (string) reverseFixupTable[key];
                     if (str4 != null)
                     {
                         if (!errors.Contains(str4))
                         {
                             errors.Add(str4);
                         }
                         reverseFixupTable.Remove(key);
                     }
                     errors.Add(pair.Key);
                     list.Remove(key);
                 }
             }
         Label_0185:;
         }
     }
     return list;
 }
コード例 #29
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;
		}
コード例 #30
0
 protected override void GenerateCompileUnit(CodeCompileUnit e)
 {
     this.GenerateCompileUnitStart(e);
     SortedList list = new SortedList(StringComparer.OrdinalIgnoreCase);
     foreach (CodeNamespace namespace2 in e.Namespaces)
     {
         namespace2.UserData["GenerateImports"] = false;
         foreach (CodeNamespaceImport import in namespace2.Imports)
         {
             if (!list.Contains(import.Namespace))
             {
                 list.Add(import.Namespace, import.Namespace);
             }
         }
     }
     foreach (string str in list.Keys)
     {
         base.Output.Write("Imports ");
         this.OutputIdentifier(str);
         base.Output.WriteLine("");
     }
     if (e.AssemblyCustomAttributes.Count > 0)
     {
         this.OutputAttributes(e.AssemblyCustomAttributes, false, "Assembly: ", true);
     }
     base.GenerateNamespaces(e);
     this.GenerateCompileUnitEnd(e);
 }
コード例 #31
0
ファイル: sortedlist.cs プロジェクト: SSCLI/sscli_20021101
 public override bool Contains(Object key)
 {
     lock (_root) {
         return(_list.Contains(key));
     }
 }
コード例 #32
0
ファイル: SearchEngine.cs プロジェクト: chandru9279/StarBase
        /// <summary>
        /// Method called from UI
        /// </summary>
        /// <param name="searchterm">search query</param>
        /// <param name="catalog">catalog to search</param>
        /// <returns>ResultFile SortedList for display</returns>
        public SortedList GetResults(string searchterm, Catalog catalog)
        {
            SortedList output = new SortedList();

            // ----------------------- DOING A SEARCH -----------------------
            if ((null != searchterm) && (null != catalog))
            {
                SetPreferences();

                string[] searchTermArray = null, searchTermDisplay = null;

                /****** Too *********/
                Regex r = new Regex(@"\s+");             // matches continuous whitespace
                searchterm = r.Replace(searchterm, " "); // replaces 'em with a single space
                searchTermArray = searchterm.Split(' '); // then split
                searchTermDisplay = (string[])searchTermArray.Clone();
                for (int i = 0; i < searchTermArray.Length; i++)
                {
                    if (_GoChecker.IsGoWord(searchTermArray[i]))
                    {	// was a Go word, just Lower it
                        searchTermArray[i] = searchTermArray[i].ToLower();
                    }
                    else
                    {	// Not a Go word, apply stemming
                        searchTermArray[i] = searchTermArray[i].Trim(' ', '?', '\"', ',', '\'', ';', ':', '.', '(', ')').ToLower();
                        searchTermArray[i] = _Stemmer.StemWord(searchTermArray[i].ToString());
                    }
                }

                if (searchterm == String.Empty)
                {
                    // After trimming the search term, it was found to be empty!
                    return output;
                }
                else
                {	// we have a search term!
                    DateTime start = DateTime.Now;  // to show 'time taken' to perform search

                    // Array of arrays of results that match ONE of the search criteria
                    Hashtable[] searchResultsArrayArray = new Hashtable[searchTermArray.Length];
                    // finalResultsArray is populated with pages that *match* ALL the search criteria
                    HybridDictionary finalResultsArray = new HybridDictionary();

                    bool botherToFindMatches = true;
                    int indexOfShortestResultSet = -1, lengthOfShortestResultSet = -1;

                    for (int i = 0; i < searchTermArray.Length; i++)
                    {	// ##### THE SEARCH #####
                        searchResultsArrayArray[i] = catalog.Search(searchTermArray[i].ToString());
                        if (null == searchResultsArrayArray[i])
                        {
                            _Matches += searchTermDisplay[i] + " <font color='gray' style='font-size:xx-small'>(not found)</font> ";
                            botherToFindMatches = false; // if *any one* of the terms isn't found, there won't be a 'set' of Matches
                        }
                        else
                        {
                            int resultsInThisSet = searchResultsArrayArray[i].Count;
                            _Matches += "<a href=\"?" + Preferences.QuerystringParameterName + "=" + searchTermDisplay[i] + "\" title=\"" + searchTermArray[i] + "\">"
                                    + searchTermDisplay[i]
                                    + "</a> <font color=gray style='font-size:xx-small'>(" + resultsInThisSet + ")</font> ";
                            if ((lengthOfShortestResultSet == -1) || (lengthOfShortestResultSet > resultsInThisSet))
                            {
                                indexOfShortestResultSet = i;
                                lengthOfShortestResultSet = resultsInThisSet;
                            }
                        }
                    }

                    // Find the common files from the array of arrays of documents
                    // matching ONE of the criteria
                    if (botherToFindMatches)                                            // all words have *some* matches
                    {																	// for each result set [NOT required, but maybe later if we do AND/OR searches)
                        int c = indexOfShortestResultSet;                               // loop through the *shortest* resultset
                        Hashtable searchResultsArray = searchResultsArrayArray[c];

                        foreach (object foundInFile in searchResultsArray)             // for each file in the *shortest* result set
                        {
                            DictionaryEntry fo = (DictionaryEntry)foundInFile;          // find matching files in the other resultsets

                            int matchcount = 0, totalcount = 0, weight = 0;

                            for (int cx = 0; cx < searchResultsArrayArray.Length; cx++)
                            {
                                totalcount += (cx + 1);                                // keep track, so we can compare at the end (if term is in ALL resultsets)
                                if (cx == c)                                      // current resultset
                                {
                                    matchcount += (cx + 1);                          // implicitly matches in the current resultset
                                    weight += (int)fo.Value;                       // sum the weighting
                                }
                                else
                                {
                                    Hashtable searchResultsArrayx = searchResultsArrayArray[cx];
                                    if (null != searchResultsArrayx)
                                    {
                                        foreach (object foundInFilex in searchResultsArrayx)
                                        {   // for each file in the result set
                                            DictionaryEntry fox = (DictionaryEntry)foundInFilex;
                                            if (fo.Key == fox.Key)
                                            {
                                                matchcount += (cx + 1);               // and if it matches, track the matchcount
                                                weight += (int)fox.Value;           // and weighting; then break out of loop, since
                                                break;                              // no need to keep looking through this resultset
                                            }
                                        } // foreach
                                    } // if
                                } // else
                            } // for
                            if ((matchcount > 0) && (matchcount == totalcount))		// was matched in each Array
                            {   // we build the finalResults here, to pass to the formatting code below
                                // - we could do the formatting here, but it would mix up the 'result generation'
                                // and display code too much
                                fo.Value = weight; // set the 'weight' in the combined results to the sum of individual document matches
                                if (!finalResultsArray.Contains(fo.Key)) finalResultsArray.Add(fo.Key, fo);
                            } // if
                        } // foreach
                    }

                    // Time taken calculation
                    Int64 ticks = DateTime.Now.Ticks - start.Ticks;
                    TimeSpan taken = new TimeSpan(ticks);
                    if (taken.Seconds > 0)
                    {
                        _DisplayTime = taken.Seconds + " seconds";
                    }
                    else if (taken.TotalMilliseconds > 0)
                    {
                        _DisplayTime = Convert.ToInt32(taken.TotalMilliseconds) + " milliseconds";
                    }
                    else
                    {
                        _DisplayTime = "less than 1 millisecond";
                    }

                    // Format the results
                    if (finalResultsArray.Count > 0)
                    {	// intermediate data-structure for 'ranked' result HTML
                        //SortedList
                        output = new SortedList(finalResultsArray.Count); // empty sorted list
                        ResultFile infile;
                        int sortrank = 0;

                        // build each result row
                        foreach (object foundInFile in finalResultsArray.Keys)
                        {
                            // Create a ResultFile with it's own Rank
                            infile = new ResultFile((File)foundInFile);

                            infile.Rank = (int)((DictionaryEntry)finalResultsArray[foundInFile]).Value;
                            sortrank = infile.Rank * -1000;		// Assume not 'thousands' of results
                            if (output.Contains(sortrank))
                            { // rank exists - drop key index one number until it fits
                                for (int i = 1; i < 999; i++)
                                {
                                    sortrank++;
                                    if (!output.Contains(sortrank))
                                    {
                                        output.Add(sortrank, infile);
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                output.Add(sortrank, infile);
                            }
                            sortrank = 0;	// reset for next pass
                        }
                        // Jim Harkins [paged results]
                        // http://aspnet.4guysfromrolla.com/articles/081804-1.aspx
                    } // else Count == 0, so output SortedList will be empty
                }
            }
            return output;
        }
コード例 #33
0
        public static Hashtable FillFeatureCache(ITable inputSignsTable, int inFromIDFI, int inToIDFI,
                                                 IFeatureClass inputLineFeatures, string linesIDFieldName,
                                                 ITrackCancel trackcancel)
        {
            // make and fill a SortedList from the IDs referenced in the table

            // for MultiNet data, there is only one ID field, so its index will be
            // passed in as inFromIDFI, while -1 will be passed in to inToIDFI.

            SortedList IDs = new System.Collections.SortedList();

            ICursor inCursor = inputSignsTable.Search(null, true);
            IRow    row;

            long fromID, toID;
            bool exists;
            int  cancelCheckInterval = 100;

            if (inToIDFI == -1)
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                    {
                        IDs.Add(fromID, fromID);
                    }
                }
            }
            else
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));
                    toID   = Convert.ToInt64(row.get_Value(inToIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                    {
                        IDs.Add(fromID, fromID);
                    }

                    exists = IDs.Contains(toID);
                    if (!exists)
                    {
                        IDs.Add(toID, toID);
                    }
                }
            }

            // make the query filter for fetching features

            IQueryFilter queryFilter = new QueryFilterClass();

            queryFilter.SubFields = "*";

            // Now fetch batches of features

            long currID;
            int  numFeaturesPerQuery = 200;
            int  numToFetch = IDs.Count;
            int  totalRemaining, totalDone = 0;

            int linesIDFieldIndex = inputLineFeatures.FindField(linesIDFieldName);

            Hashtable outputFeatures = new System.Collections.Hashtable((int)numToFetch);

            if (numFeaturesPerQuery > numToFetch)
            {
                numFeaturesPerQuery = numToFetch;
            }

            while (totalDone < numToFetch)
            {
                // Populate the QueryDef Where clause IN() statement for the current batch of features.
                // This is going to be very slow unless linesIDFieldName is indexed and this is why
                // we added a warning to the GP message window if this is the case.  If you cannot
                // index linesIDFieldName, then this code would run faster scanning the whole feature
                // class looking for the records we need (no Where clause).

                string whereClause = linesIDFieldName + " IN(";

                for (int i = 0; i < numFeaturesPerQuery; i++)
                {
                    currID       = Convert.ToInt64(IDs.GetByIndex(totalDone + i), System.Globalization.CultureInfo.InvariantCulture);
                    whereClause += Convert.ToString(currID, System.Globalization.CultureInfo.InvariantCulture);
                    if (i != (numFeaturesPerQuery - 1))
                    {
                        whereClause += ",";
                    }
                    else
                    {
                        whereClause += ")";
                    }
                }

                queryFilter.WhereClause = whereClause;

                // select the features

                IFeatureCursor inputFeatureCursor = inputLineFeatures.Search(queryFilter, false);

                // get the features

                IFeature feature;

                while ((feature = inputFeatureCursor.NextFeature()) != null)
                {
                    // keep a copy of the OID and shape of feature - skip records that cause errors
                    // (perhaps pass the GPMessages in and log warnings in there if you need to log exceptions)

                    try
                    {
                        FeatureData data = new FeatureData(feature.OID, feature.ShapeCopy);
                        outputFeatures.Add(Convert.ToInt64(feature.get_Value(linesIDFieldIndex)), data);
                    }
                    catch
                    {
                    }

                    if ((totalDone % cancelCheckInterval) == 0)
                    {
                        // check for user cancel

                        if (trackcancel != null && !trackcancel.Continue())
                        {
                            throw (new COMException("Function cancelled."));
                        }
                    }
                }

                // finished? set up for next batch

                totalDone += numFeaturesPerQuery;

                totalRemaining = numToFetch - totalDone;
                if (totalRemaining > 0)
                {
                    if (numFeaturesPerQuery > totalRemaining)
                    {
                        numFeaturesPerQuery = totalRemaining;
                    }
                }
            }

            return(outputFeatures);
        }
コード例 #34
0
 protected ArrayList GroupTransitionsByEvent(ArrayList transitionList)
 {
     ArrayList groupedTransitions = new ArrayList ();
     SortedList groups = new SortedList ();
     int transCount = 0;
     foreach (TransitionInfo info in transitionList)
     {
         string eventName = IsNotEmptyString (info.Transition.Event) ? info.Transition.Event : transCount++.ToString ();
         if (!groups.Contains (eventName))
         {
             groups.Add (eventName, new ArrayList ());
         }
         ArrayList list = (ArrayList) groups [eventName];
         list.Add (info);
     }
     foreach (DictionaryEntry de in groups)
     {
         ArrayList list = (ArrayList) de.Value;
         list.Sort (new TransitionOrderPrioritySorter ());
         groupedTransitions.Add (list);
     }
     return groupedTransitions;
 }
コード例 #35
0
ファイル: SortedList.cs プロジェクト: yonder/mono
 public override bool ContainsKey(object key)
 {
     lock (host.SyncRoot) {
         return(host.Contains(key));
     }
 }
コード例 #36
0
        /// <summary>
        /// Resolve the dependencies for a table (this is a helper method for GetSortedTableNames).
        /// </summary>
        /// <param name="tableName">The name of the table to resolve.</param>
        /// <param name="unsortedTableNames">The unsorted table names.</param>
        /// <param name="sortedTableNames">The sorted table names.</param>
        private void ResolveTableDependencies(string tableName, SortedList unsortedTableNames, StringCollection sortedTableNames)
        {
            unsortedTableNames.Remove(tableName);

            foreach (ColumnDefinition columnDefinition in this.tableDefinitions[tableName].Columns)
            {
                // no dependency to resolve because this column doesn't reference another table
                if (null == columnDefinition.KeyTable)
                {
                    continue;
                }

                foreach (string keyTable in columnDefinition.KeyTable.Split(';'))
                {
                    if (tableName == keyTable)
                    {
                        continue; // self-referencing dependency
                    }
                    else if (sortedTableNames.Contains(keyTable))
                    {
                        continue; // dependent table has already been sorted
                    }
                    else if (!this.tableDefinitions.Contains(keyTable))
                    {
                        this.core.OnMessage(WixErrors.MissingTableDefinition(keyTable));
                    }
                    else if (unsortedTableNames.Contains(keyTable))
                    {
                        this.ResolveTableDependencies(keyTable, unsortedTableNames, sortedTableNames);
                    }
                    else
                    {
                        // found a circular dependency, so ignore it (this assumes that the tables will
                        // use a finalize method to nest their elements since the ordering will not be
                        // deterministic
                    }
                }
            }

            sortedTableNames.Add(tableName);
        }
コード例 #37
0
 public void setValue(SortedList list, string key, string value)
 {
     if (list.Contains(key))
     {
         PrintPoint printPoint = (PrintPoint) list[key];
         printPoint.Value = value;
     }
     else
     {
         throw new Exception("打印模版中不存在Key为" + key + "的节点!");
     }
 }
コード例 #38
0
ファイル: XmlFile.cs プロジェクト: XiBeichuan/hydronumerics
		/// <summary>
		/// Gets all properties of an aggregate in a sorted way.
		/// MetaInfo attribute "XmlIndex" is used for the sorting.
		/// </summary>
		/// <param name="aggregate">The aggregate</param>
		/// <returns>Sorted property names</returns>
		private static string[] GetSortedProperties (IAggregate aggregate) 
		{
			SortedList list = new SortedList();
			string[] properties = aggregate.Properties;

			for (int i = 0; i < properties.Length; i++) 
			{
				int index = (int)MetaInfo.GetAttributeDefault (aggregate.Source.GetType(), properties[i], "XmlIndex", 1000);
				string listIndex = index.ToString("D9") + " " + properties[i].ToLower();
				if (!list.Contains (listIndex))
				{
					list.Add (listIndex, properties[i]);
				}
			}

			/*			for (int i = 0; i < list.GetValueList()..Values.Count; i++) 
						{
							propertyList.Add (list.GetByIndex(i));
						}*/

			ArrayList propertyList = new ArrayList(list.Values);
			return (string[]) propertyList.ToArray(typeof(string));
		}
コード例 #39
0
ファイル: ScheduledFTP.cs プロジェクト: CarverLab/Oyster
        void ThreadProc()
        {
            _stopEvent.Reset();
            string myPath = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location);
            string myConfig = myPath + @"\applicationConfig.xml";
            ApplicationSettings mySettings =
                new ScheduledFtpService.ApplicationSettings();
            string SourceDirectoryPath;
            string FailedDirectoryPath;
            string ManagementServerAddress;
            string ManagementServerPassword;

            if (!File.Exists(myConfig))
            {
                Log.WriteLog(myConfig + " does not exist. Creating one.");
                ClearAndWriteSettingsRow(mySettings);
                mySettings.WriteXml(myConfig);
            }

            mySettings.ReadXml(myConfig);

            ApplicationSettings.SettingsRow settingsRow;

            if (mySettings.Settings.Count == 0)
            {
                Log.WriteLog("There are no settings in " + myConfig);
                ClearAndWriteSettingsRow(mySettings);
            }
            settingsRow = mySettings.Settings[0];
            if (settingsRow.SourceDirectory.Length == 0)
            {
                Log.WriteLog("SourceDirectory in " + myConfig + " is empty. Exiting.");
                _done = true;
                return;
            }

            ManagementServerAddress = settingsRow.ManagementServerAddress;
            if (ManagementServerAddress.Length == 0)
            {
                Log.WriteLog("ManagementServerAddress in " + myConfig + " is empty. Exiting.");
                _done = true;
                return;
            }

            if (settingsRow.IsIdEncrypted)
                ManagementServerPassword = CarverLab.Utility.Crypto.DecryptFromBase64String(settingsRow.ManagementServerId);
            else
                ManagementServerPassword = settingsRow.ManagementServerId;

            SourceDirectoryPath = settingsRow.SourceDirectory;
            FailedDirectoryPath = Path.Combine(SourceDirectoryPath, "Failed");
            DirectoryInfo SourceDirectoryInfo = TryGetDirectory(SourceDirectoryPath);
            if (SourceDirectoryInfo == null)
                return;
            DirectoryInfo FailedDirectoryInfo = TryGetDirectory(FailedDirectoryPath);
            if (FailedDirectoryInfo == null)
                return;

            int TransferRetryMaxCount = mySettings.Settings[0].TransferRetryMaxCount;
            if (TransferRetryMaxCount == 0)
            {
                TransferRetryMaxCount = 3;
            }

            HybridDictionary WaitingFileList = new HybridDictionary();
            Session ftpSession = null;
            while (!_done)
            {
                try
                {
                    FileInfo[] FileInfoList = SourceDirectoryInfo.GetFiles("*.xml");
                    SortedList SortedFileInfoList = new SortedList(
                        new FileInfoDateComparer(FileInfoDateComparer.DateCompareType.CreationTime));
                    foreach (FileInfo fi in FileInfoList)
                    {
                        if (!SortedFileInfoList.Contains(fi))
                            SortedFileInfoList.Add(fi,fi);
                        else	// this should never happen, but it did! what?!??!
                            Log.WriteLog("For some reason, " + fi.FullName + " showed up twice in the directory!");

                    }
                    foreach (DictionaryEntry entry in SortedFileInfoList)
                    {
                        if (_done)
                            break;
                        FileInfo xmlFileInfo = entry.Value as FileInfo;
                        ScheduledFTPFile transferFile = new ScheduledFTPFile();
                        ScheduledFTPFile.FileUploadRow row;
                        try
                        {
                            transferFile.ReadXml(xmlFileInfo.FullName);
                        }
                        catch (System.Exception e)
                        {
                            Log.WriteLog(xmlFileInfo.FullName + " Exception: " + e.Message);
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }
                        row = transferFile.FileUpload[0];
                        string wmvPath = row.FilePath;
                        if (!File.Exists(wmvPath))
                        {
                            Log.WriteLog(wmvPath + " does not exist. Moving to Failed directory.");
                            try
                            {
                                File.Move(xmlFileInfo.FullName, FailedDirectoryInfo.FullName + "\\" + xmlFileInfo.Name);
                            }
                            catch (System.Exception e)
                            {
                                Log.WriteLog("Could not move " + xmlFileInfo.FullName + ": " + e.Message);
                            }
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }

                        // open the file and see if it is in use... if it is, continue and try again...
                        // and keep trying until WME lets go of the file... sheesh
                        try
                        {
                            Log.WriteLog("Checking to see if " + wmvPath + " is still held by the encoder...");
                            FileStream fileCheck = new FileStream(wmvPath, FileMode.Open, FileAccess.ReadWrite);
                            fileCheck.Close();
                            Log.WriteLog(wmvPath + " is free to upload.");
                        }
                        catch (System.Exception e)
                        {
                            if (e.Message.IndexOf("because it is being used") != -1)
                            {
                                Log.WriteLog("Yep, " + wmvPath + " is in use. Will try again... and again.");
                                continue;
                            }
                            // just try again anyway...
                            Log.WriteLog("Error: " + wmvPath + " error: " + e.Message);
                            continue;
                        }

                        if (ftpSession != null)
                        {
                            Log.WriteLog("*** ERROR *** : ftpSession variable should be null!");
                            if (ftpSession.IsConnected)
                                ftpSession.Close();
                            ftpSession = null;
                            //throw new ApplicationException("ftpSession should be null. There must be a serious problem.");
                        }
                        ftpSession = new Session();
                        ftpSession.Server = row.ServerAddress;
                        ftpSession.Port = row.ServerPort;

                        string user, pass;
                        if (row.EncryptedCredentials)
                        {
                            user = Crypto.DecryptFromBase64String(row.User);
                            pass = Crypto.DecryptFromBase64String(row.Password);
                        }
                        else
                        {
                            user = row.User;
                            pass = row.Password;
                        }
                        try
                        {
                            Log.WriteLog("Connecting to ftp server...");
                            ftpSession.Connect(user, pass);
                        }
                        catch (Exception ftpex)
                        {
                            Log.WriteLog("Could not connect to " + row.ServerAddress + ":" + row.ServerPort +
                                ftpex.Message);
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }
                        FtpDirectory dir;
                        Log.WriteLog("Setting ftp current directory to " + row.Directory);
                        if (row.Directory.Length == 0 || row.Directory == ".")
                        {
                            dir = ftpSession.CurrentDirectory;
                            Log.WriteLog("Current ftp directory: " + dir.FullName);
                        }
                        else
                        {
                            Log.Verbose("Subdirectories:");
                            foreach (FtpDirectory dd in ftpSession.CurrentDirectory.SubDirectories)
                            {
                                Log.Verbose(string.Format("Name: {0}; Full name: {1};", dd.Name, dd.FullName));
                            }
                            dir = ftpSession.CurrentDirectory.FindSubdirectory(row.Directory, true);
                            if (dir == null)
                            {
                                Log.WriteLog("Subdirectory " + row.Directory + " doesn't exist on the server.");
                                File.Move(xmlFileInfo.FullName, FailedDirectoryInfo.FullName + "\\" + xmlFileInfo.Name);
                                OnFireUploadedEvent(xmlFileInfo.FullName, false);
                                continue;
                            }
                            Log.WriteLog("Uploading to ftp directory: " + dir.FullName);
                        }
                        try
                        {
                            Log.WriteLog("Opening file " + wmvPath);
                            Stream localStream = File.OpenRead(wmvPath);
                            Log.WriteLog("Creating ftp stream.");
                            string wmvName = Path.GetFileName(wmvPath);
                            Stream remoteStream = dir.CreateFileStream(wmvName);
                            int readed;
                            byte[] uploadBuffer = new byte[4096];
                            Log.WriteLog("Transferring file " + wmvName);
                            while ((readed = localStream.Read(uploadBuffer,0,4096)) != 0)
                            {
                                if (_done)
                                    break;
                                remoteStream.Write(uploadBuffer, 0, 4096);
                            }
                            if (_done)
                                break;
                            remoteStream.Close();
                            localStream.Close();
                            ftpSession.Close();
                            ftpSession = null;

                            Log.WriteLog("Transfer complete on file " + xmlFileInfo.FullName);

                            Log.WriteLog("Connecting to Oyster system at " + ManagementServerAddress);

                            OysterClassLibrary.Oyster oyster = new OysterClassLibrary.Oyster(
                                ManagementServerAddress, ManagementServerPassword);
                            OysterClassLibrary.Recording rec =
                                oyster.GetRecordingByName(wmvName);
                            if (rec == null)
                            {
                                throw new ApplicationException(wmvName + " is not a valid recording on the server.");
                            }
                            rec.IsReady = true;
                            Log.WriteLog("Recording is ready: "  + wmvName);

                            xmlFileInfo.Delete();
                            Log.WriteLog("Deleted : "  + xmlFileInfo.Name);
                            System.IO.File.Delete(wmvPath);
                            Log.WriteLog("Deleted : "  + wmvName);
                            OnFireUploadedEvent(xmlFileInfo.FullName, true);
                        }
                        catch (System.Exception upex)
                        {
                            Log.WriteLog("Transfer failed: " + xmlFileInfo.FullName + ": " + upex.Message);
                            TryFileMove(xmlFileInfo.FullName, Path.Combine(
                                FailedDirectoryInfo.FullName, xmlFileInfo.Name));
                            OnFireUploadedEvent(xmlFileInfo.FullName, false);
                            continue;
                        }
                    }
                    System.Threading.Thread.Sleep(1000);
                }
                catch (System.Exception mainex)
                {
                    Log.WriteLog("Exception in main loop: " + mainex.ToString());
                    if (ftpSession != null)
                    {
                        if (ftpSession.IsConnected)
                        {
                            ftpSession.Close();
                        }
                        ftpSession = null;
                    }
                }
            }
            _stopEvent.Set();
        }
コード例 #40
0
ファイル: SortedList.cs プロジェクト: yonder/mono
 public virtual bool Contains(object key)
 {
     return(host.Contains(key));
 }
コード例 #41
0
ファイル: CCustomerInfoDAO.cs プロジェクト: Jusharra/RMS
 SortedList ICustomerInfoDAO.GetCustomerAddresses(string p_houseNumber, string p_postCode)
 {
     SortedList slCustomerAddress = new SortedList();
     string sqlCommand = String.Empty;
     CCustomerInfo tempCustomerInfo = new CCustomerInfo();
     string[] houseNumberArray = new string[0];
     try
     {
         this.OpenConnection();
         if (p_houseNumber == String.Empty || p_houseNumber == null)
         {
             sqlCommand = String.Format(SqlQueries.GetQuery(Query.GetCustomerAddressWithoutHouseNumber), p_postCode.Replace(" ",""));
         }
         else
         {
             sqlCommand = String.Format(SqlQueries.GetQuery(Query.GetCustomerAddressDetails), p_houseNumber, p_postCode.Replace(" ", ""));
         }
         IDataReader oReader = this.ExecuteReader(sqlCommand);
          string key ="";
         if (oReader != null)
         {
             while (oReader.Read())
             {
                         clsCustomerInfo objCustInfo = new clsCustomerInfo();
                         objCustInfo.ApartmentNumber = Convert.ToString(oReader["SBN"]);
                         objCustInfo.StreenName = Convert.ToString(oReader["STR"]);
                         objCustInfo.HouseNumber = Convert.ToString(oReader["NUM"]);
                         objCustInfo.Town = Convert.ToString(oReader["TWN"]);
                         objCustInfo.buildingName = Convert.ToString(oReader["BNA"]);
                         objCustInfo.PostalCode = p_postCode;
                         key = p_postCode.Replace(" ", "").ToUpper() + "-" + objCustInfo.ApartmentNumber.Replace(" ", "").ToUpper() + "-" + objCustInfo.HouseNumber.Replace(" ", "").ToUpper();
                         if (!slCustomerAddress.Contains(key))
                         {
                             slCustomerAddress.Add(key, objCustInfo);
                         }
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Write("Exception : " + ex + " in CustomerInfoGetByCustomerID()", LogLevel.Error, "Database");
         if (ex.GetType().Equals(typeof(SqlException)))
         {
             SqlException oSQLEx = ex as SqlException;
             if (oSQLEx.Number != 7619)
                 throw new Exception("Exception occured at CustomerInfoGetByCustomerID()", ex);
         }
         else
         {
             throw new Exception("Exception occure at CustomerInfoGetByCustomerID()", ex);
         }
     }
     finally
     {
         this.CloseConnection();
     }
     return slCustomerAddress;
 }
コード例 #42
0
ファイル: SortedList.cs プロジェクト: treesportrait/corefx
 public virtual bool Contains(Object key)
 {
     return(_sortedList.Contains(key));
 }
コード例 #43
0
ファイル: CCustomerInfoDAO.cs プロジェクト: Jusharra/RMS
 /// <summary>
 /// Filling up the address details info
 /// </summary>
 /// <param name="inReader"></param>
 /// <param name="p_slAddressInfo"></param>
 private void FillFlatInfo(IDataReader p_inReader, SortedList p_slAddressInfo,string p_houseNumber)
 {
     string flatNumber = String.Empty;
     string[] flatArray=new string[0];
     string flatInfo = Convert.ToString(p_inReader["SBN"]);
     flatArray = flatInfo.Split(';');
     for (int arrayIndex = 0; arrayIndex < flatArray.Length; arrayIndex++)
     {
             clsCustomerInfo objCustInfo = new clsCustomerInfo();
             objCustInfo.ApartmentNumber = Convert.ToString(flatArray[arrayIndex]);
             objCustInfo.StreenName = Convert.ToString(p_inReader["STR"]);
             objCustInfo.HouseNumber = p_houseNumber;
             objCustInfo.Town = Convert.ToString(p_inReader["TWN"]);
             objCustInfo.buildingName = Convert.ToString(p_inReader["BNA"]);
             string key=objCustInfo.ApartmentNumber.Replace(" ", "").ToUpper() + objCustInfo.HouseNumber.Replace(" ", "").ToUpper();
             if (!p_slAddressInfo.Contains(key))
             {
                 p_slAddressInfo.Add(key, objCustInfo);
             }
     }
 }