Insert() public méthode

public Insert ( int index, string value ) : void
index int
value string
Résultat void
        /// <summary>
        /// Adds a string to the list and positions it in the recent list
        /// </summary>
        /// <param name="text">The string that should be added</param>
        public void AddString(string text)
        {
            if (m_List.Contains(text))
            {
                m_List.Remove(text);
                m_List.Insert(0, text);
            }
            else
            {
                if (m_List.Count == m_Capacity)
                {
                    m_List.RemoveAt(m_List.Count - 1);
                }

                m_List.Insert(0, text);
            }
        }
Exemple #2
0
        public void AddToFavoriteFolders(string str)
        {
            _favoriteFolders.Insert(0, str);
            while (_favoriteFolders.Count > 10)
            {
                _favoriteFolders.RemoveAt(10);
            }

            RaisePropertyChanged("FavoriteFolders");
        }
Exemple #3
0
        public void AddRecentlyUsedFile(FileInfo newFile) {
            StringCollection recent = new StringCollection();
            recent.AddRange(data.RecentOpenedFiles);

            while(recent.IndexOf(newFile.FullName) >= 0) {
                recent.Remove(newFile.FullName);
            }

            recent.Insert(0, newFile.FullName);

            while (recent.Count > 16) {
                recent.RemoveAt(16);
            }

            string[] result = new string[recent.Count];
            recent.CopyTo(result, 0);
            data.RecentOpenedFiles = result;
        }
        protected override void OnResize(EventArgs e)
        {
            Debug.WriteLine(String.Format("Before: {0}x{1}, Console: {2}x{3}",
                                          this.Width, this.Height, this.CharSize.Width, this.CharSize.Height));
            // reset scrollbar values);
            this.SetScrollBarValues();
            this.TextAtCursor = this.CaptureTextAtCursor();

            // calculate new rows and columns
            Int32 columns = this.ClientSize.Width/this.CharSize.Width - 1;
            Int32 rows = this.ClientSize.Height/this.CharSize.Height;

            // make sure at least 1 row and 1 col or Control will throw
            if (rows < 5)
            {
                rows = 5;
                this.Height = this.CharSize.Height*rows;
            }

            // make sure at least 1 row and 1 col or Control will throw
            if (columns < 5)
            {
                columns = 5;
                this.Width = this.CharSize.Width*columns;
            }

            // make sure the bottom of this doesn't exceed bottom of parent client area
            // for some reason it was getting stuck like that
            if (this.Parent != null)
            {
                if (this.Bottom > this.Parent.ClientSize.Height)
                    this.Height = this.Parent.ClientSize.Height - this.Top;
            }

            // reset the char grid
            this.SetSize(rows, columns);

            ////Console.WriteLine(Convert.ToString(rows) + " rows. " + Convert.ToString(this.ScrollbackBuffer.Count + " buffer lines"));

            // populate char grid from ScrollbackBuffer
            // parse through ScrollbackBuffer from the end
            // ScrollbackBuffer[0] is the "oldest" string
            // chargrid[0] is the top row on the display
            StringCollection visiblebuffer = new StringCollection();
            for (Int32 i = this.ScrollbackBuffer.Count - 1; i >= 0; i--)
            {
                visiblebuffer.Insert(0, this.ScrollbackBuffer.Characters[i]);

                // don't parse more strings than our display can show
                if (visiblebuffer.Count >= rows - 1) // rows -1 to leave line for cursor space
                    break;
            }

            Int32 lastline = 0;
            for (Int32 i = 0; i < visiblebuffer.Count; i++)
            {
                //Console.WriteLine("Writing string to display: " + visiblebuffer[i]);
                for (Int32 column = 0; column < columns; column++)
                {
                    //this.CharGrid[i][column] = '0';
                    if (column > visiblebuffer[i].Length - 1)
                        continue;

                    this.CharGrid[i][column] = visiblebuffer[i].ToCharArray()[column];
                }

                lastline = i;
            }

            // replace cursor text
            for (Int32 column = 0; column < columns; column++)
            {
                if (column > this.TextAtCursor.Length - 1)
                    continue;

                this.CharGrid[lastline + 1][column] = this.TextAtCursor.ToCharArray()[column];
            }

            this.CaretToAbs(lastline + 1, this.TextAtCursor.Length);
            this.Refresh();

            base.OnResize(e);
            Debug.WriteLine(String.Format("After: {0}x{1}, Console: {2}x{3}",
                                          this.Width, this.Height, this.CharSize.Width, this.CharSize.Height));
        }
Exemple #5
0
 private void InsertToPos(StringCollection coll, int pos, string str)
 {
     if (pos >= coll.Count)
     {
         // coll.Add(pos.ToString() + " :: " + str);
         coll.Add(str);
     } else {
         // coll.Insert(pos, pos.ToString() + " :: " + str);
         coll.Insert(pos, str);
     }
 }
        // generic method to add a string to a history item
        private void AddSearchHistoryItem(StringCollection history, string toAdd)
        {
            // add the item to the find history
            if (history.Contains(toAdd)) {
                // remove it so it gets added at the top
                history.Remove(toAdd);
            }
            // make sure there is only 20
            if (history.Count == historyLimit) {
                history.RemoveAt(historyLimit - 1);
            }
            history.Insert(0, toAdd);

            // update the drop down for the combobox
            ListStore store = new ListStore (typeof (string));
            for (int i = 0; i < history.Count; i ++)
                store.AppendValues (history[i]);

            if (history == findHistory)
                searchPatternEntry.Completion.Model = store;
            else if( history == replaceHistory)
                replacePatternEntry.Completion.Model = store;
        }
        // generic method to add a string to a history item
        private void AddSearchHistoryItem(StringCollection history, string toAdd)
        {
            // add the item to the find history
            if (history.Contains(toAdd)) {
                // remove it so it gets added at the top
                history.Remove(toAdd);
            }
            // make sure there is only 20
            if (history.Count == HISTORY_LIMIT) {
                history.RemoveAt(HISTORY_LIMIT - 1);
            }
            history.Insert(0, toAdd);

            // update the drop down for the combobox
            string[] stringArray = new string[history.Count];
            history.CopyTo(stringArray, 0);
            if (history == findHistory) {
                searchPatternComboBox.SetPopdownStrings(stringArray);
            } else if( history == replaceHistory) {
                replacePatternComboBox.SetPopdownStrings(stringArray);
            }
        }
Exemple #8
0
    private StringCollection GetVersions(string ns, string topic)
    {
      StringCollection versions = new StringCollection(); 
      FlexWiki.AbsoluteTopicName atn = new FlexWiki.AbsoluteTopicName(topic, ns); 
      foreach (TopicChange change in federation.GetTopicChanges(atn))
      {
        // They appear to come in reverse chronological order, so we 
        // add them in reverse order. 
        versions.Insert(0, change.Version); 
      }

      return versions; 
    }
Exemple #9
0
 private static void AddFileDropListToClipboard(string driveKey, StringCollection fileDropList, bool cut)
 {
     if (cut || fileDropList[0].StartsWith("hdfs://"))
     {
         if (cut)
             fileDropList.Insert(0, MoveModeToken);
         fileDropList.Insert(0, driveKey);
         Clipboard.SetData(ClipboardDataType, fileDropList);
     }
     else
         Clipboard.SetFileDropList(fileDropList);
 }
        protected override void OnResize(System.EventArgs e)
        {
            this.Font       = new System.Drawing.Font (this.TypeFace, this.TypeSize, this.TypeStyle);
            // reset scrollbar values
            this.SetScrollBarValues();

            // capture text at cursor b/c it's not in the scrollback buffer yet
            string TextAtCursor = "";
            for (int x = 0; x < this._cols; x++)
            {
                char CurChar = this.CharGrid[this.Caret.Pos.Y][x];

                if (CurChar == '\0')
                {
                    continue;
                }
                TextAtCursor = TextAtCursor + Convert.ToString(CurChar);
            }

            // calculate new rows and columns
            int columns = this.ClientSize.Width / this.CharSize.Width - 1;
            int rows = this.ClientSize.Height / this.CharSize.Height;

            // make sure at least 1 row and 1 col or Control will throw
            if (rows < 5)
            {
                rows = 5;
                this.Height = this.CharSize.Height * rows;
            }

            // make sure at least 1 row and 1 col or Control will throw
            if (columns < 5)
            {
                columns = 5;
                this.Width = this.CharSize.Width * columns;
            }

            // make sure the bottom of this doesn't exceed bottom of parent client area
            // for some reason it was getting stuck like that
            if (this.Parent != null)
                if (this.Bottom > this.Parent.ClientSize.Height)
                    this.Height = this.Parent.ClientSize.Height - this.Top;

            // reset the char grid
            this.SetSize(rows, columns);

            //Console.WriteLine(Convert.ToString(rows) + " rows. " + Convert.ToString(this.ScrollbackBuffer.Count + " buffer lines"));

            // populate char grid from ScrollbackBuffer

            // parse through ScrollbackBuffer from the end
            // ScrollbackBuffer[0] is the "oldest" string
            // chargrid[0] is the top row on the display
            StringCollection visiblebuffer = new StringCollection();
            for (int i = this.ScrollbackBuffer.Count - 1; i >= 0; i--)
            {

                visiblebuffer.Insert(0, this.ScrollbackBuffer[i]);

                // don't parse more strings than our display can show
                if (visiblebuffer.Count >= rows - 1) // rows -1 to leave line for cursor space
                    break;
            }

            int lastline  = 0;
            for (int i = 0; i < visiblebuffer.Count; i++)
            {
                //Console.WriteLine("Writing string to display: " + visiblebuffer[i]);
                for (int column = 0; column < columns; column++)
                {
                    //this.CharGrid[i][column] = '0';
                    if (column > visiblebuffer[i].Length - 1)
                        continue;
                    this.CharGrid[i][column] = visiblebuffer[i].ToCharArray()[column];

                }
                lastline = i;

            }

            // replace cursor text
            for (int column = 0; column < columns; column++)
            {
                if (column > TextAtCursor.Length - 1)
                    continue;
                this.CharGrid[lastline+1][column] = TextAtCursor.ToCharArray()[column];

            }

            this.CaretToAbs(lastline+1, TextAtCursor.Length);
            this.Refresh();

            base.OnResize(e);
        }
        private void HandleScroll(Object sender, ScrollEventArgs se)
        {
            // capture text at cursor
            if (this.Caret.IsOff)
            {
            }
            else
            {
                this.TextAtCursor = "";
                for (int x = 0; x < this._cols; x++)
                {
                    char CurChar = this.CharGrid[this.Caret.Pos.Y][x];
                    if (CurChar == '\0')
                    {
                        continue;
                    }
                    this.TextAtCursor = this.TextAtCursor + Convert.ToString(CurChar);
                }
            }

            switch (se.Type)
            {
                case ScrollEventType.SmallIncrement: // down
                    this.LastVisibleLine += 1;
                    break;
                case ScrollEventType.SmallDecrement: // up
                    this.LastVisibleLine += -1;
                    break;
                default:
                    return;
            }

            // make sure we don't set LastVisibleLine past the end of the StringCollection
            // LastVisibleLine is relative to the last line in the StringCollection
            // 0 is the Last element
            if (this.LastVisibleLine > 0)
            {
                this.LastVisibleLine = 0;
            }

            if (this.LastVisibleLine < (0 - this.ScrollbackBuffer.Count) + (this._rows))
            {
                this.LastVisibleLine = (0 - this.ScrollbackBuffer.Count) + (this._rows)-1;
            }

            int columns = this._cols;
            int rows    = this._rows;

            this.SetSize(rows, columns);

            StringCollection visiblebuffer = new StringCollection();
            for (int i = this.ScrollbackBuffer.Count - 1 + this.LastVisibleLine; i >= 0; i--)
            {
                visiblebuffer.Insert(0, this.ScrollbackBuffer[i]);

                // don't parse more strings than our display can show
                if (visiblebuffer.Count >= rows - 1) // rows -1 to leave line for cursor space
                    break;
            }

            //int lastline = (0 - this.ScrollbackBuffer.Count) + (this.Rows);
            //int lastline = this.LastVisibleLine;
            for (int i = 0; i < visiblebuffer.Count; i++)
            {
                //Console.WriteLine("Writing string to display: " + visiblebuffer[i]);
                for (int column = 0; column < columns; column++)
                {
                    //this.CharGrid[i][column] = '0';
                    if (column > visiblebuffer[i].Length - 1)
                        continue;
                    this.CharGrid[i][column] = visiblebuffer[i].ToCharArray()[column];

                }
                // if we're displaying the last line in scrollbackbuffer, then
                // replace the cursor and the text on the cursor line
                //System.Console.WriteLine(Convert.ToString(lastline) + " " + Convert.ToString(this.ScrollbackBuffer.Count));
                if (this.LastVisibleLine == 0)
                {
                    this.CaretOn();
                    //this.CaretToAbs(0,0);
                    for (int column = 0; column < this._cols; column++)
                    {
                        if (column > this.TextAtCursor.Length - 1)
                            continue;
                        this.CharGrid[this._rows - 1][column] = this.TextAtCursor.ToCharArray()[column];
                    }
                    this.CaretToAbs(this._rows - 1, this.TextAtCursor.Length);
                }
                else
                {
                    this.CaretOff();
                }
            }

            this.Refresh();
        }
        /// <summary>
        /// This method creates a script that calls ExecuteScript() to invoke
        /// multiple scripts.  It is designed to allow multiple scripts to wire up
        /// to an event handler.  The script is created and compiled and both
        /// the NSS and NCS files are added to the module.
        /// </summary>
        /// <param name="module">The module to modify</param>
        /// <param name="property">The property to which the scripts are being attached</param>
        /// <param name="originalScript">The original script on the property, or
        /// string.Empty if none</param>
        /// <param name="otherScripts">A list of other scripts to execute</param>
        /// <returns>The ResRef of the newly created script</returns>
        private string CreateExecuteScript(Erf module, string property, 
			string originalScript, StringCollection otherScripts)
        {
            // If the original script and the otherScripts are the same then
            // there is nothing to do, just return originalScript as the RefRef
            if (1 == otherScripts.Count &&
                0 == string.Compare(otherScripts[0], originalScript, true, CultureInfo.InvariantCulture))
                return originalScript.ToLower();

            // Build the file name and full name of the script file.
            string substring = property.Length > 12 ? property.Substring(0, 12) : property;
            string sourceName = "hif_" + substring + ".nss";
            string fullSourceName = Path.Combine(currentTempDir, sourceName);
            System.Text.StringBuilder b = new System.Text.StringBuilder();

            // Check to see if the original script is one of our generated scripts
            // (the name will start with "hif_" if it is).  If so then we need to
            // open the file and read the list of scripts currently being called
            // and add them to the list of scripts to call.
            StringCollection scriptsToExecute = new StringCollection();
            bool createScript =
                0 != string.Compare(originalScript, Path.GetFileNameWithoutExtension(sourceName), true, CultureInfo.InvariantCulture);
            if (!createScript)
            {
                // Read the list of scripts currently being executed from the hif_
                // script file.
                string[] scripts = null;
                using (StreamReader reader = new StreamReader(fullSourceName))
                {
                    // Read the first line, strip the comment prefix off, and
                    // split the line into all of the scripts that the script
                    // executes.
                    string line = reader.ReadLine();
                    line = line.Trim();
                    line = line.Substring(3, line.Length - 3);
                    scripts = line.Split(',');
                }

                // Add all of the scripts currently in the file, and then add
                // all of the scripts in the otherScripts collection if they aren't
                // already there.
                scriptsToExecute.AddRange(scripts);
                foreach (string script in otherScripts)
                    if (!scriptsToExecute.Contains(script)) scriptsToExecute.Insert(0, script);
            }
            else
            {
                // Add all of the other scripts to our execute list, then add the
                // original script if there was one.
                // modified by fluffyamoeba 2008-06-16
                // swapped so original script is executed last
                foreach (string script in otherScripts)
                    scriptsToExecute.Add(script);
                if (string.Empty != originalScript) scriptsToExecute.Add(originalScript);
            }

            // Create the script file.
            using (StreamWriter writer = new StreamWriter(fullSourceName, false,
                       System.Text.Encoding.ASCII))
            {
                // Make the first line be a list of the scripts being executed
                // so we can do updates to the file later.
                b.Length = 0;
                foreach (string script in scriptsToExecute)
                {
                    if (b.Length > 0) b.Append(",");
                    b.Append(script);
                }
                writer.WriteLine("// {0}", b.ToString());

                // Write out a comment header.
                writer.WriteLine("/////////////////////////////////////////////////////////////////////");
                writer.WriteLine("//");
                writer.WriteLine("// This script has been auto-generated by HakInstaller to call");
                writer.WriteLine("// multiple handlers for the {0} event.", property);
                writer.WriteLine("//");
                writer.WriteLine("/////////////////////////////////////////////////////////////////////");
                writer.WriteLine("");

                writer.WriteLine("void main()");
                writer.WriteLine("{");

                // Add an execute line for each script in the collection.
                foreach (string script in scriptsToExecute)
                    writer.WriteLine("    ExecuteScript(\"{0}\", OBJECT_SELF);", script);

                writer.WriteLine("}");
                writer.Flush();
                writer.Close();
            }

            // Build the name of the obj file.
            string objName = Path.GetFileNameWithoutExtension(sourceName) + ".ncs";
            string fullObjName = Path.Combine(currentTempDir, objName);

            // Generate the compiler command line.
            string compiler = Path.Combine(NWNInfo.ToolsPath, "clcompile.exe");
            b.Length = 0;
            b.AppendFormat("\"{0}\" \"{1}\"", fullSourceName, currentTempDir);

            // Start the compiler process and wait for it.
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = compiler;
            info.Arguments = b.ToString();
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            Process process = Process.Start(info);
            process.WaitForExit();

            // If the compiler didn't work then we have a problem.
            if (0 != process.ExitCode)
                throw new NWNException("Could not run the NWN script compiler");

            // Add the source and object files to the module, if we have created new
            // files.  If the original script was a hif_ script that we just changed
            // then the file is already part of the module, no need to add it.
            if (createScript)
            {
                module.AddFile(fullSourceName, true);
                module.AddFile(fullObjName, true);
            }

            // Return the ResRef for the new script file.
            return Path.GetFileNameWithoutExtension(sourceName).ToLower();
        }
Exemple #13
0
 /// <summary>
 /// Adds the empty column for the row numbers to a schema
 /// </summary>
 /// <param name="schema">The schema to add the line to</param>
 private void AddRowColumnToSchema(StringCollection schema)
 {
     // If the first entry is not blank then we need to add an empty
     // column for the row number to the schema.
     if (string.Empty != schema[0]) schema.Insert(0, string.Empty);
 }
        /// <summary>
        /// 获取函数的搜索结果,且按照匹配程度从大到小排列
        /// </summary>
        /// <param name="funList">函数列表</param>
        /// <param name="searchKey">搜索关键字</param>
        /// <param name="searchFunSort">要搜索的函数类别</param>
        public static StringCollection GetFunSearchResult(StringCollection funList, string searchKey, string searchFunSort)
        {
            StringCollection result = new StringCollection();
            List<double> resultMatchList = new List<double>();//与result对应的匹配程度列表

            try
            {
                //逐个扫描函数列表,从后往前扫描
                for (int i = funList.Count - 1; i >= 0; i--)
                {
                    string[] fun = funList[i].Split('|');
                    string funName = fun[0].ToLower();//函数名称
                    string funDesc = fun[1].ToLower();//函数描述
                    string funParameter = fun[3].ToLower();//函数参数
                    string funSort = fun[4].ToLower();//函数类别
                    double howMatch = 0;//匹配程度

                    searchKey = searchKey.Trim().ToLower();
                    searchFunSort = searchFunSort.Trim().ToLower();
                    string funInfo = funName + funDesc + funParameter;//函数信息,包括名称、描述、参数
                    //根据函数类别和搜索关键字判断
                    if (funInfo.IndexOf(searchKey) != -1 //函数信息中存在搜索关键字
                        && (searchFunSort == "" //函数类别为空
                        || funSort == searchFunSort)) //函数类别等于要搜索的函数类别
                    {
                        if (funName.IndexOf(searchKey) != -1)//函数名称中存在搜索关键字
                        {
                            double d = searchKey.Length / (double)funName.Length;
                            if (d > howMatch)
                            {
                                howMatch = d + 1E-5;//使得函数名称、函数描述和参数列表在相同howMatch情况下,以函数名称的匹配为准
                            }
                        }
                        if (funDesc.IndexOf(searchKey) != -1)//函数描述中存在搜索关键字
                        {
                            double d = searchKey.Length / (double)funDesc.Length;
                            if (d > howMatch)
                            {
                                howMatch = d;
                            }
                        }
                        if (funParameter.IndexOf(searchKey) != -1)//函数参数列表中存在搜索关键字
                        {
                            double d = searchKey.Length / (double)funParameter.Length;
                            if (d > howMatch)
                            {
                                howMatch = d;
                            }
                        }

                        //添加到result中
                        if (result.Count == 0)
                        {
                            result.Add(funList[i]);
                            resultMatchList.Add(howMatch);
                        }
                        else
                        {
                            //插入到合适位置
                            int k = 0;
                            for (; k < result.Count; k++)
                            {
                                //如果比当前位置的函数的匹配程度高
                                if (howMatch > resultMatchList[k])
                                {
                                    result.Insert(k, funList[i]);
                                    resultMatchList.Insert(k, howMatch);
                                    break;
                                }
                            }
                            if (k == result.Count)//前面没有找到对应的插入位置
                            {
                                result.Add(funList[i]);
                                resultMatchList.Add(howMatch);
                            }
                        }
                    }//end if
                }//end for
            }
            catch
            {
            }

            return result;
        }
Exemple #15
0
        private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (null == options)
                throw new ArgumentNullException("options");
            if (null == fileNames)
                throw new ArgumentNullException("fileNames");

            CompilerResults results = new CompilerResults(options.TempFiles);
            Process mcs = new Process();

#if !NET_2_0
            string mcs_output;
            string mcs_stdout;
            string[] mcsOutput;
#endif

            // FIXME: these lines had better be platform independent.
            if (Path.DirectorySeparatorChar == '\\')
            {
                mcs.StartInfo.FileName = windowsMonoPath;
                mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
#if NET_2_0
					BuildArgs (options, fileNames, ProviderOptions);
#else
                    BuildArgs(options, fileNames);
#endif
            }
            else
            {
#if NET_2_0
				// FIXME: This is a temporary hack to make code genaration work in 2.0+
#if NET_4_0
				mcs.StartInfo.FileName="dmcs";
#else
				mcs.StartInfo.FileName="gmcs";
#endif
				mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
#else
                mcs.StartInfo.FileName = "mcs";
                mcs.StartInfo.Arguments = BuildArgs(options, fileNames);
#endif
            }

#if NET_2_0
			mcsOutput = new StringCollection ();
			mcsOutMutex = new Mutex ();
#endif

            string monoPath = Environment.GetEnvironmentVariable("MONO_PATH");
            if (monoPath == null)
                monoPath = String.Empty;

            string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            if (privateBinPath != null && privateBinPath.Length > 0)
                monoPath = String.Format("{0}:{1}", privateBinPath, monoPath);

            if (monoPath.Length > 0)
            {
                StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
                if (dict.ContainsKey("MONO_PATH"))
                    dict["MONO_PATH"] = monoPath;
                else
                    dict.Add("MONO_PATH", monoPath);
            }

            mcs.StartInfo.CreateNoWindow = true;
            mcs.StartInfo.UseShellExecute = false;
            mcs.StartInfo.RedirectStandardOutput = true;
            mcs.StartInfo.RedirectStandardError = true;
#if NET_2_0
			mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
#endif

            try
            {
                mcs.Start();
            }
            catch (Exception e)
            {
                Win32Exception exc = e as Win32Exception;
                if (exc != null)
                {
                    /*throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName,
                                    Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));*/
                }
                throw;
            }

            try
            {
#if NET_2_0
				mcs.BeginOutputReadLine ();
				mcs.BeginErrorReadLine ();
#else
                // If there are a few kB in stdout, we might lock
                mcs_output = mcs.StandardError.ReadToEnd();
                mcs_stdout = mcs.StandardOutput.ReadToEnd();
#endif
                mcs.WaitForExit();

                results.NativeCompilerReturnValue = mcs.ExitCode;
            }
            finally
            {
#if NET_2_0
				mcs.CancelErrorRead ();
				mcs.CancelOutputRead ();
#endif

                mcs.Close();
            }

#if NET_2_0
			StringCollection sc = mcsOutput;
#else
            mcsOutput = mcs_output.Split(System.Environment.NewLine.ToCharArray());
            StringCollection sc = new StringCollection();
#endif

            bool loadIt = true;
            foreach (string error_line in mcsOutput)
            {
#if !NET_2_0
                sc.Add(error_line);
#endif
                CompilerError error = CreateErrorFromString(error_line);
                if (error != null)
                {
                    results.Errors.Add(error);
                    if (!error.IsWarning)
                        loadIt = false;
                }
            }

            if (sc.Count > 0)
            {
                sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);

                //results.Output = sc;
            }

            if (loadIt)
            {
                if (!File.Exists(options.OutputAssembly))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in sc)
                        sb.Append(s + Environment.NewLine);

                    throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'");
                }

                if (options.GenerateInMemory)
                {
                    using (FileStream fs = File.OpenRead(options.OutputAssembly))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
                        fs.Close();
                    }
                }
                else
                {
                    // Avoid setting CompiledAssembly right now since the output might be a netmodule
                    results.PathToAssembly = options.OutputAssembly;
                }
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return results;
        }
Exemple #16
0
        private void AddPathToHistory(StringCollection list, string entry)
        {
            if (list == null)
                return;

            foreach (string item in list) {
                if (item == entry) {
                    list.Remove(item);
                    break;
                }
            }

            while (list.Count >= 5)
                list.RemoveAt(list.Count - 1);

            list.Insert(0, entry);
        }
        public static void UpdateRecentFiles(string file, int offset = 0)
        {
            if (string.IsNullOrWhiteSpace(file)) return;
            var recent = Settings.Default.RecentFiles ?? new StringCollection();

            var files = recent
                .Cast<string>()
                .Where(f => f.StripOffsetFromFileName() != file);

            var sc = new StringCollection(); // string collections suck
            sc.AddRange(files.Take(19).ToArray());
            sc.Insert(0, file.AddOffsetToFileName(offset));
            Settings.Default.RecentFiles = sc;
        }
Exemple #18
0
        public void Test01()
        {
            IntlStrings intl;
            StringCollection sc;
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // initialize IntStrings
            intl = new IntlStrings();


            // [] StringCollection is constructed as expected
            //-----------------------------------------------------------------

            sc = new StringCollection();

            // [] Insert into empty collection
            //
            for (int i = 0; i < values.Length; i++)
            {
                if (sc.Count > 0)
                    sc.Clear();
                sc.Insert(0, values[i]);
                if (sc.Count != 1)
                {
                    Assert.False(true, string.Format("Error, Count {1} instead of 1", i, sc.Count));
                }
                if (!sc.Contains(values[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain just inserted item", i));
                }
            }

            //
            // [] Insert into filled collection



            sc.Clear();
            sc.AddRange(values);
            if (sc.Count != values.Length)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
            }

            // string to insert
            string val = intl.GetRandomString(MAX_LEN);

            sc.Insert(0, val);

            if (sc.Count != values.Length + 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length + 1));
            }

            if (sc.IndexOf(val) != 0)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(val), 0));
            }

            // check that all init items were moved
            for (int i = 0; i < values.Length; i++)
            {
                if (sc.IndexOf(values[i]) != i + 1)
                {
                    Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i + 1));
                }
            }

            sc.Clear();
            sc.AddRange(values);
            if (sc.Count != values.Length)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
            }

            sc.Insert(values.Length, val);

            if (sc.Count != values.Length + 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length + 1));
            }

            if (sc.IndexOf(val) != values.Length)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(val), values.Length));
            }

            // check that all init items were moved
            for (int i = 0; i < values.Length; i++)
            {
                if (sc.IndexOf(values[i]) != i)
                {
                    Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), i));
                }
            }


            sc.Clear();
            sc.AddRange(values);
            if (sc.Count != values.Length)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length));
            }

            sc.Insert(values.Length / 2, val);

            if (sc.Count != values.Length + 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of {1}", sc.Count, values.Length + 1));
            }

            if (sc.IndexOf(val) != values.Length / 2)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(val), values.Length / 2));
            }

            // check that all init items were moved
            for (int i = 0; i < values.Length; i++)
            {
                int expected = i;
                if (i >= values.Length / 2)
                    expected = i + 1;
                if (sc.IndexOf(values[i]) != expected)
                {
                    Assert.False(true, string.Format("Error, IndexOf returned {1} instead of {2}", i, sc.IndexOf(values[i]), expected));
                }
            }

            //
            // [] Invalid parameter
            //
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.Insert(-1, val); });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.Insert(sc.Count + 1, val); });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.Insert(sc.Count + 2, val); });
        }
Exemple #19
0
 private void InsertToPos(StringCollection coll, int pos, string str)
 {
     if (pos >= coll.Count)
     {
         coll.Add(str);
     } else {
         coll.Insert(pos, str);
     }
 }