IndexOf() public méthode

public IndexOf ( string value ) : int
value string
Résultat int
Exemple #1
0
    /// <summary>
    /// Evaulate the path string in relation to the current item
    /// </summary>
    /// <param name="context">The Revolver context to evaluate the path against</param>
    /// <param name="path">The path to evaulate. Can either be absolute or relative</param>
    /// <returns>The full sitecore path to the target item</returns>
    public static string EvaluatePath(Context context, string path)
    {
      if (ID.IsID(path))
        return path;

      string workingPath = string.Empty;
      if (!path.StartsWith("/"))
        workingPath = context.CurrentItem.Paths.FullPath + "/" + path;
      else
        workingPath = path;

      // Strip any language and version tags
      if (workingPath.IndexOf(':') >= 0)
        workingPath = workingPath.Substring(0, workingPath.IndexOf(':'));

      // Make relative paths absolute
      string[] parts = workingPath.Split('/');
      StringCollection targetParts = new StringCollection();
      targetParts.AddRange(parts);

      while (targetParts.Contains(".."))
      {
        int ind = targetParts.IndexOf("..");
        targetParts.RemoveAt(ind);
        if (ind > 0)
        {
          targetParts.RemoveAt(ind - 1);
        }
      }

      if (targetParts[targetParts.Count - 1] == ".")
        targetParts.RemoveAt(targetParts.Count - 1);

      // Remove empty elements
      while (targetParts.Contains(""))
      {
        targetParts.RemoveAt(targetParts.IndexOf(""));
      }

      string[] toRet = new string[targetParts.Count];
      targetParts.CopyTo(toRet, 0);
      return "/" + string.Join("/", toRet);
    }
Exemple #2
0
        /// <summary>
        /// get a value from a row, position given by AColumnNames
        /// </summary>
        protected static string GetValue(StringCollection AColumnNames,
            string[] ACurrentRow,
            string AColumnName)
        {
            int index = AColumnNames.IndexOf(AColumnName);

            if (index == -1)
            {
                throw new Exception("TFixData.GetValue: Problem with unknown column name " + AColumnName);
            }

            return ACurrentRow[index];
        }
Exemple #3
0
        /// <summary>
        /// set a value of a row, position given by AColumnNames
        /// </summary>
        protected static void SetValue(StringCollection AColumnNames,
            ref string[] ACurrentRow,
            string AColumnName,
            string ANewValue)
        {
            int index = AColumnNames.IndexOf(AColumnName);

            if (index == -1)
            {
                throw new Exception("TFixData.SetValue: Problem with unknown column name " + AColumnName);
            }

            ACurrentRow[index] = ANewValue;
        }
        public PickListForm(string strTitle, string strCurrent, StringCollection strc)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            listBox1.DataSource = strc;
            listBox1.SelectedIndex = strCurrent == "" ? -1 : strc.IndexOf(strCurrent);
            Text = strTitle;
            label1.Text = label1.Text.Replace("$1", strTitle);
        }
Exemple #5
0
        public Settings()
        {
            InitializeComponent();
            Closing += PreventTermination;
            planetList = Properties.Settings.Default.planets;
            System.Collections.IEnumerator se = Constraints.PLANETS.GetEnumerator();
            while (se.MoveNext())
            {
                string pl = (string)se.Current;
                CheckBox tmp = new CheckBox();
                tmp.Checked += delegate(object s, RoutedEventArgs e)
                {
                    if(planetList.IndexOf(pl) == -1) planetList.Add(pl);
                };
                tmp.Unchecked += delegate(object s, RoutedEventArgs e)
                {
                    if(planetList.IndexOf(pl) > -1) planetList.Remove(pl);
                };
                tmp.IsChecked = planetList.IndexOf(pl) > -1;
                StackPanel sp = new StackPanel();
                sp.Orientation = Orientation.Horizontal;
                sp.Children.Add(tmp);
                Label lbl = new Label();
                lbl.Content = pl;
                sp.Children.Add(lbl);
                planets.Children.Add(sp);
            }

            closetaskbar.IsChecked = Properties.Settings.Default.closeToTaskbar;
            mintaskbar.IsChecked = Properties.Settings.Default.minimizeToTaskbar;
            notify.IsChecked = Properties.Settings.Default.notify;
            hasrewards.IsChecked = Properties.Settings.Default.hasRewards;
            reward.Text = Properties.Settings.Default.rewardContains.ToLower();
            credits.Text = Properties.Settings.Default.credits.ToString();
            usefilter.IsChecked = Properties.Settings.Default.useFilter;
        }
Exemple #6
0
    public static int TextHasErrors(ref HyperComponents.WebUI.CustomSpellChecker.SpellChecker c, string v)
    {
        System.Collections.Specialized.StringCollection badWords = new System.Collections.Specialized.StringCollection();
        BadWord badWord = null;

        badWords.Clear();
        //check some text.
        c.Check(v);
        int nbErrors = 0;

        //iterate through all bad words in the text.
        while ((badWord = c.NextBadWord()) != null)
        {
            if (badWords.IndexOf(badWord.Word) < 0)
            {
                //Trace.Warn("          -> " + badWord.Word + " - " + badWord.Reason.ToString());
                nbErrors++;
                badWords.Add(badWord.Word);
            }
        }
        return(nbErrors);
    }
Exemple #7
0
        public int ParseFileSection(StringCollection sec, PySection section, int begin, int end)
        {
            // sec collection, doesn't contain # --- begin / # --- end
            int count = begin;

            for (int j=begin; j<end; j++)
            {
                string item = sec[j];
                if (item.Contains("# begin"))
                {
                    // here's we have a new section
                    string trimstr = item.Trim();
                    string nn = trimstr.Substring(7);
                    section.Children.Add(new PySection(nn.Trim()));
                    PySection child = (PySection)section.Children[section.Children.Count - 1];
                    child.Begin = count;
                    // find the end...
                    string ends = item.Replace("begin", "end");
                    int end_idx = sec.IndexOf(ends);
                    if ((end_idx >= begin) || (end_idx <= end))
                    {
                        child.Size = end_idx - child.Begin - 1;
                        ParseFileSection(sec, child, count + 1, end_idx);
                        j = end_idx;
                        count = end_idx;
                    } else {
                        // Not found error...
                    }
                } else if (item.Contains("# end"))
                {
                    // DO NOTHING
                } else
                {
                    section.Lines.Add(item);
                }
                count++;
            }
            return count;
        }
        void SavePdb(string strPdbFile)
        {
            // Make a list of unique sound files

            PdbPacker pdbp = new PdbPacker();
            int cSfx = m_alsNames.Count;
            StringCollection strcUniqueSounds = new StringCollection();
            ArrayList alsPcm = new ArrayList();
            for (int iSfx = 0; iSfx < cSfx; iSfx++) {
                if (!listViewSfx.Items[iSfx].Checked)
                    continue;
                if (!(bool)m_alsSfxEnabled[iSfx])
                    continue;
                string strFile = listViewSfx.Items[iSfx].SubItems[1].Text;
                if (strFile == null)
                    continue;
                strFile.Trim();
                if (strFile.Length == 0)
                    continue;
                int istr = strcUniqueSounds.IndexOf(strFile);
                if (istr == -1)
                    istr = strcUniqueSounds.Add(strFile);
            }

            // Serialize names out

            ArrayList alsStringOffsets = new ArrayList();
            BinaryWriter bwtr = new BinaryWriter(new MemoryStream());
            bwtr.Write(Misc.SwapUShort((ushort)strcUniqueSounds.Count));
            for (int iSound = 0; iSound < strcUniqueSounds.Count; iSound++) {
                alsStringOffsets.Add(bwtr.BaseStream.Position);
                string strFile = Path.ChangeExtension(strcUniqueSounds[iSound], ".snd");
                char[] sz = strFile.ToCharArray();
                bwtr.Write(sz);
                bwtr.Write((byte)0);
            }
            byte[] abSoundFiles = new byte[bwtr.BaseStream.Length];
            bwtr.BaseStream.Seek(0, SeekOrigin.Begin);
            bwtr.BaseStream.Read(abSoundFiles, 0, (int)bwtr.BaseStream.Length);
            bwtr.Close();

            // soundfiles file

            PdbPacker.File fileSounds = new PdbPacker.File("soundfiles", abSoundFiles);
            pdbp.Add(fileSounds);

            // Now serialize the sfx entries in the order of the names

            bwtr = new BinaryWriter(new MemoryStream());
            for (int iName = 0; iName < m_alsNames.Count; iName++) {
                // Need to find the entry in listViewSfx for this name since the persist
                // order needs to match soundeffects.h.

                string strName = ((StringCollection)m_alsNames[iName])[0];
                int iSfx;
                bool fFound = false;
                for (iSfx = 0; iSfx < cSfx; iSfx++) {
                    if (strName == listViewSfx.Items[iSfx].SubItems[0].Text) {
                        fFound = true;
                        break;
                    }
                }
                if (!fFound)
                    throw new Exception("Internal error");

                string strFile = listViewSfx.Items[iSfx].SubItems[1].Text;
                if (!listViewSfx.Items[iSfx].Checked)
                    strFile = null;
                if (!(bool)m_alsSfxEnabled[iSfx])
                    strFile = null;
                if (strFile == null) {
                    bwtr.Write((byte)0xff);
                } else {
                    strFile.Trim();
                    if (strFile.Length == 0) {
                        bwtr.Write((byte)0xff);
                    } else {
                        bwtr.Write((byte)strcUniqueSounds.IndexOf(strFile));
                    }
                }
                bwtr.Write((byte)0); // bwtr.Write(byte.Parse(listViewSfx.Items[iSfx].SubItems[2].Text));
                int nPriority = m_strcPriorities.IndexOf(listViewSfx.Items[iSfx].SubItems[3].Text);
                if (nPriority < 0) {
                    MessageBox.Show("Warning: " + listViewSfx.Items[iSfx].SubItems[0].Text + " has an unfamiliar priority.");
                }
                bwtr.Write((byte)nPriority);
            }
            byte[] abSfxEntries = new byte[bwtr.BaseStream.Length];
            bwtr.BaseStream.Seek(0, SeekOrigin.Begin);
            bwtr.BaseStream.Read(abSfxEntries, 0, (int)bwtr.BaseStream.Length);
            bwtr.Close();

            PdbPacker.File fileSfxEntries = new PdbPacker.File("SfxEntries", abSfxEntries);
            pdbp.Add(fileSfxEntries);

            // Now add in all the sounds

            for (int istrFile = 0; istrFile < strcUniqueSounds.Count; istrFile++) {
                string strFile = Path.GetFullPath(textBoxSoundsDir.Text) + "\\" + strcUniqueSounds[istrFile];
                Pcm pcm = new Pcm(strFile);
                PdbPacker.File fileT = new PdbPacker.File();
                fileT.str = Path.ChangeExtension(strcUniqueSounds[istrFile], ".snd");
                fileT.ab = pcm.GetSndEncoding();
                fileT.fCompress = false;
                pdbp.Add(fileT);
            }

            // Ready to save pdb

            pdbp.Save(strPdbFile, "WARI");
        }
Exemple #9
0
        public void Test01()
        {
            IntlStrings intl;
            StringCollection sc;
            string itm;         // returned value of Item
            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aa",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            intl = new IntlStrings();


            // [] StringCollection Item is returned as expected
            //-----------------------------------------------------------------

            sc = new StringCollection();

            // exception expected
            // all indexes should be invalid for empty collection

            //
            // [] Invalid parameter - set Item() on empty collection
            //
            itm = intl.GetRandomString(MAX_LEN);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[-1] = itm; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[0] = itm; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[0] = null; });

            // [] set Item() on collection filled with simple strings
            //

            sc.Clear();
            sc.AddRange(values);
            int cnt = values.Length;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, cnt));
            }
            for (int i = 0; i < cnt; i++)
            {
                sc[i] = values[cnt - i - 1];
                if (String.Compare(sc[i], values[cnt - i - 1]) != 0)
                {
                    Assert.False(true, string.Format("Error, value is {1} instead of {2}", i, sc[i], values[cnt - i - 1]));
                }
            }


            //
            // Intl strings
            // [] set Item() on collection filled with Intl strings
            //

            string[] intlValues = new string[values.Length];

            // fill array with unique strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }


            int len = values.Length;
            Boolean caseInsensitive = false;
            for (int i = 0; i < len; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper())
                    caseInsensitive = true;
            }



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

            for (int i = cnt; i < cnt; i++)
            {
                sc[i] = intlValues[cnt - i - 1];
                if (String.Compare(sc[i], intlValues[cnt - i - 1]) != 0)
                {
                    Assert.False(true, string.Format("Error, actual item is {1} instead of {2}", i, sc[i], intlValues[cnt - i - 1]));
                }
            }

            //
            //  [] Case sensitivity
            //

            string intlStrUpper = intlValues[0];
            intlStrUpper = intlStrUpper.ToUpper();
            string intlStrLower = intlStrUpper.ToLower();

            sc.Clear();
            sc.AddRange(values);
            sc.Add(intlStrUpper);

            if (sc.Count != values.Length + 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", sc.Count, values.Length + 1));
            }
            // verify that Item returns intl string in a case sensitive way
            //
            // set simple to intl lower
            //
            sc[0] = intlStrLower;
            if (!caseInsensitive && (String.Compare(sc[0], intlStrUpper) == 0))
            {
                Assert.False(true, string.Format("Error, set to uppercase when should have to lower"));
            }
            if (String.Compare(sc[0], intlStrLower) != 0)
            {
                Assert.False(true, string.Format("Error, didn't set to lower"));
            }

            //
            // set intlUpper to intl lower
            //
            sc[sc.Count - 1] = intlStrLower;
            if (!caseInsensitive && (String.Compare(sc[sc.Count - 1], intlStrUpper) == 0))
            {
                Assert.False(true, string.Format("Error, didn't set from uppercase to lowercase "));
            }
            if (String.Compare(sc[sc.Count - 1], intlStrLower) != 0)
            {
                Assert.False(true, string.Format("Error, didn't set to lower"));
            }


            //
            //    set to null  - it's legal - return value will be null
            // [] set Item() to null
            //


            if (sc.Count < 1)
                sc.AddRange(values);

            //
            // set middle item to null
            //
            int ind = sc.Count / 2;
            sc[ind] = null;
            if (sc[ind] != null)
            {
                Assert.False(true, string.Format("Error, failed to set to null"));
            }
            if (!sc.Contains(null))
            {
                Assert.False(true, string.Format("Error, Contains() didn't return true for null"));
            }

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

            //
            // [] Invalid parameter - for filled collection
            //


            sc.Clear();
            sc.AddRange(intlValues);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[-1] = intlStrUpper; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[sc.Count] = intlStrUpper; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[sc.Count + 1] = intlStrUpper; });
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc[sc.Count] = null; });
        }
        public StringCollection controlMatchingBetweenDataAndProfile(String dataFile, String profileFile)
        {
            StringCollection errors = new StringCollection();
            CsvArchiveDocuments ad = new CsvArchiveDocuments();
            if (traceActions)
                ad.setTracesWriter(tracesWriter);
            ad.loadFile(dataFile);
            /*
            StringCollection erreursDonnees = ad.getErrorsList();
            if (erreursDonnees.Count != 0) {
                foreach (String st in erreursDonnees) {
                    errors.Add(st);
                }
            }
            */
            RngProfileController rpc = new RngProfileController();
            if (traceActions)
                rpc.setTracesWriter(tracesWriter);
            rpc.controlProfileFile(profileFile);
            /*
            StringCollection erreursProfil = rpc.getErrorsList();
            if (erreursProfil.Count != 0) {
                foreach (String st in erreursProfil) {
                    errors.Add(st);
                }
            }
            */
            String str;
            StringCollection tagsForKeys = ad.getTagsListForKeys();
            StringCollection tagsForDocs = ad.getTagsListForDocuments();
            StringCollection expectedTags = rpc.getExpectedTagsListList();

            StringCollection expectedTagsForDocs = new StringCollection();
            foreach (String st in expectedTags) {
                if (st.StartsWith("document: ")) {
                    expectedTagsForDocs.Add(st.Substring(10));
                }
            }
            foreach (String st in expectedTagsForDocs) {
                expectedTags.Remove("document: " + st);
            }

            StringCollection tagsForKeysModified = new StringCollection();
            foreach (String st in tagsForKeys) {
                str = Regex.Replace(st, @"#KeywordContent\[#[0-9]+\]", "#KeywordContent");
                tagsForKeysModified.Add(str);
            }

            StringCollection tagsForDocsModified = new StringCollection();
            foreach (String st in tagsForDocs) {
                str = Regex.Replace(st, @"#KeywordContent(\[[^]]+\])?\[#[0-9]+\]", "#KeywordContent$1");
                tagsForDocsModified.Add(str);
            }

            if (traceActions) {
                if (tagsForKeysModified.Count != 0) {
                    tracesWriter.WriteLine("\ntagsForKeysModified");
                    foreach (String st in tagsForKeysModified) {
                        tracesWriter.WriteLine(st);
                    }
                }
                if (tagsForDocsModified.Count != 0) {
                    tracesWriter.WriteLine("\ntagsForDocsModified");
                    foreach (String st in tagsForDocsModified) {
                        tracesWriter.WriteLine(st);
                    }
                }
                if (expectedTags.Count != 0) {
                    tracesWriter.WriteLine("\nexpectedTags");
                    foreach (String st in expectedTags) {
                        tracesWriter.WriteLine(st);
                    }
                }
                if (expectedTagsForDocs.Count != 0) {
                    tracesWriter.WriteLine("\nexpectedTagsForDocs");
                    foreach (String st in expectedTagsForDocs) {
                        tracesWriter.WriteLine(st);
                    }
                }
                tracesWriter.WriteLine("");
            }

            // Test des clés
            foreach (String st in tagsForKeysModified) {
                str = Regex.Replace(st, @"\[#\d+\]", "[#1]");
                str = Regex.Replace(str, @"#KeywordContent\[#[0-9]+\]", "#KeywordContent");
                if (expectedTags.IndexOf(str) == -1)
                    errors.Add("La clé '" + st + "' fournie par les données métier n'est pas attendue par le profil");
            }

            // Test des documents
            foreach (String st in tagsForDocsModified) {
                str = Regex.Replace(st, @"\[#\d+\]", "[#1]");
                str = Regex.Replace(str, @"#KeywordContent(\[[^]]+\])?\[#[0-9]+\]", "#KeywordContent$1");
                if (expectedTagsForDocs.IndexOf(str) == -1)
                    errors.Add("Le document typé par le tag '" + st + "' n'est pas attendu par le profil");
            }

            // Test du profil
            foreach (String st in expectedTags) {
                if (tagsForKeysModified.IndexOf(st) == -1) {
                    errors.Add("Dans le profil, le tag '" + st + "' ne trouve pas de correspondance dans les données métier");
                }
            }
            foreach (String st in expectedTagsForDocs) {
                if (tagsForDocsModified.IndexOf(st) == -1) {
                    errors.Add("Dans le profil, le tag de document '" + st + "' ne trouve pas de correspondance dans les données métier");
                }
            }
            return errors;
        }
        /// <summary>
        /// Tries to find and remove a word from the word list.
        /// </summary>
        /// <param name="wordList">The word list.</param>
        /// <param name="word">The word to find and remove.</param>
        /// <returns>Whether or not the word was found and removed.</returns>
        private static bool TryFindAndRemoveWord(StringCollection wordList, string word)
        {
            bool removed = false;

            int wordIndex = wordList.IndexOf(word);
            if (wordIndex >= 0)
            {
                wordList.RemoveAt(wordIndex);
                removed = true;
            }

            return removed;
        }
Exemple #12
0
			private static StringCollection GetFilteredFileList(DirectoryInfo sourceDirectory, ArrayList includes, ArrayList excludes)
			{
				StringCollection fileList = new StringCollection();

				foreach (FileFilter fileFilter in includes)
				{
					FileInfo[] files = sourceDirectory.GetFiles(fileFilter.Mask);

					if (files.Length <= 0)
					{
						if (fileFilter.FailOnEmpty)
							GenError("File by mask '{0}' not found in directory '{1}' !", fileFilter.Mask, sourceDirectory.FullName);
					}
					else
						for (int i = 0; i < files.Length; ++i)
						{
							string fileFullName = files[i].FullName;

							int fileIndex = fileList.IndexOf(fileFullName);
							// Защита от дублирования
							if (fileIndex < 0)
								fileList.Add(fileFullName);
							else
							{
								Console.Error.WriteLine(
									"WixGen.exe : warning WGEN1002: File '{0}' already included.\r\nDetail info: Directory '{1}', Filter '{2}'\r\n",
									fileFullName, sourceDirectory.FullName, fileFilter.Mask);
							}
						}
				}

				foreach (FileFilter fileFilter in excludes)
				{
					FileInfo[] files = sourceDirectory.GetFiles(fileFilter.Mask);

					for (int i = 0; i < files.Length; ++i)
					{
						int fileIndex = fileList.IndexOf(files[i].FullName);
						if (fileIndex >= 0)
							fileList.RemoveAt(fileIndex);
					}
				}

				return fileList;
			}
Exemple #13
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()
            };

            int cnt = 0;            // Count
            // initialize IntStrings
            intl = new IntlStrings();


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

            sc = new StringCollection();

            // [] Remove() from empty collection
            //
            for (int i = 0; i < values.Length; i++)
            {
                sc.Remove(values[i]);
                if (sc.Count != 0)
                {
                    Assert.False(true, string.Format("Error, Remove changed Count for empty collection", i));
                }
            }


            // [] Remove() from collection filled with simple strings
            //

            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));
            }

            for (int i = 0; i < values.Length; i++)
            {
                // verify that collection contains all added items
                //
                if (!sc.Contains(values[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain {0} item", i));
                }

                cnt = sc.Count;

                // Remove each item
                //
                sc.Remove(values[i]);

                if (sc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, didn't remove anything", i));
                }

                if (sc.Contains(values[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            //
            // Intl strings
            // [] Remove() from collection filled with Intl strings
            //

            string[] intlValues = new string[values.Length];

            // fill array with unique strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            int len = values.Length;
            Boolean caseInsensitive = false;
            for (int i = 0; i < len; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper())
                    caseInsensitive = true;
            }


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

            for (int i = 0; i < intlValues.Length; i++)
            {
                // verify that collection contains all added items
                //
                if (!sc.Contains(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain {0} item", i));
                }

                cnt = sc.Count;

                // Remove each item
                //
                sc.Remove(intlValues[i]);

                if (sc.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, didn't remove anything", i));
                }

                if (sc.Contains(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            // duplicate strings
            // [] Remove() from filled collection with duplicate strings
            //
            sc.Clear();
            string intlStr = intlValues[0];

            sc.Add(intlStr);        // index 0
            sc.AddRange(values);
            sc.AddRange(intlValues);        // second index values.Length + 1
            cnt = values.Length + 1 + intlValues.Length;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, cnt));
            }

            // verify Index of newly added item
            //
            if (sc.IndexOf(intlStr) != 0)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), 0));
            }

            // remove
            //
            sc.Remove(intlStr);
            if (!sc.Contains(intlStr))
            {
                Assert.False(true, string.Format("Error, removed both duplicates"));
            }
            // second string should still be present
            if (sc.IndexOf(intlStr) != values.Length)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), values.Length));
            }

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

                if (sc.IndexOf(intlValues[i]) != i + values.Length)
                {
                    Assert.False(true, string.Format("Error, IndexOf {1} item returned {2} ", i, i + values.Length, sc.IndexOf(intlValues[i])));
                }
            }


            //
            // [] Case sensitivity: search should be case-sensitive
            //

            sc.Clear();
            sc.Add(intlStr.ToUpper());
            sc.AddRange(values);
            sc.Add(intlStr.ToLower());
            cnt = values.Length + 2;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2} ", sc.Count, cnt));
            }

            // remove lowercase item
            //
            intlStr = intlStr.ToLower();

            cnt = sc.Count;
            sc.Remove(intlStr);
            if (sc.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove anything"));
            }

            if (!caseInsensitive && sc.Contains(intlStr))
            {
                Assert.False(true, string.Format("Error, didn't remove lowercase "));
            }

            // but should still contain Uppercase
            if (!sc.Contains(intlValues[0].ToUpper()))
            {
                Assert.False(true, string.Format("Error, removed uppercase "));
            }

            //
            //  remove item that is not in the collection
            //

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

            // remove non-existing item
            //
            intlStr = "Hello";
            cnt = sc.Count;
            sc.Remove(intlStr);
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, removed something"));
            }
        }
        /// <summary>
        /// Updates the terrain toolbar with properties from the edit control.
        /// </summary>
        private void SyncTerrainToolbar()
        {
            this.toolStripTextBoxHeightLevel.TextChanged -= this.ToolStripTextBoxHeightLevel_TextChanged;
            this.toolStripComboBoxSeason.SelectedIndexChanged -= this.ToolStripComboBoxSeason_SelectedIndexChanged;
            this.toolStripButtonHideBaseSeasonTerrain.Click -= this.ToolStripButtonHideBaseSeasonTerrain_Click;
            this.toolStripButtonSelect.Click -= this.ToolStripButtonSelect_Click;
            this.toolStripButtonRaise.Click -= this.ToolStripButtonRaise_Click;
            this.toolStripButtonLower.Click -= this.ToolStripButtonLower_Click;
            this.toolStripButtonFlatten.Click -= this.ToolStripButtonFlatten_Click;
            this.toolStripButtonSmooth.Click -= this.ToolStripButtonSmooth_Click;
            this.toolStripTextBoxCursorSize.TextChanged -= this.ToolStripTextBoxCursorSize_TextChanged;
            this.toolStripTextBoxIntensity.TextChanged -= this.ToolStripTextBoxIntensity_TextChanged;
            this.toolStripButtonApplyTerrainType.Click -= this.ToolStripButtonApplyTerrainType_Click;
            this.toolStripComboBoxApplyTerrainType.SelectedIndexChanged -= this.ToolStripComboBoxApplyTerrainType_SelectedIndexChanged;

            if (this.toolStripComboBoxSeason.Items.Count == 0)
            {
                this.toolStripComboBoxSeason.Items.AddRange(SeasonExtensions.GetSortedList());
            }

            if (this.toolStripComboBoxApplyTerrainType.Items.Count == 0)
            {
                this.toolStripComboBoxApplyTerrainType.Items.AddRange(TerrainTypeExtensions.GetSortedList());
            }

            this.toolStripButtonHideBaseSeasonTerrain.Checked = this.terrainControl.HideBaseSeasonTerrain;

            this.toolStripTextBoxHeightLevel.Text = this.terrainControl.CurrentHeightLevel.ToString(CultureInfo.InvariantCulture);
            this.toolStripTextBoxCursorSize.Text = this.terrainControl.CursorSize.ToString(CultureInfo.InvariantCulture);
            this.toolStripTextBoxIntensity.Text = this.terrainControl.Intensity.ToString(CultureInfo.InvariantCulture);

            this.toolStripButtonSelect.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Select);
            this.toolStripButtonRaise.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Raise);
            this.toolStripButtonLower.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Lower);
            this.toolStripButtonFlatten.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Flatten);
            this.toolStripButtonSmooth.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Smooth);
            this.toolStripButtonApplyTerrainType.Checked = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.TerrainType);

            this.toolStripTextBoxCursorSize.Enabled = !this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Select) || this.terrainControl.TerrainTool.IsSet(TerrainControlTools.TerrainType);
            this.toolStripTextBoxIntensity.Enabled = !this.terrainControl.TerrainTool.IsSet(TerrainControlTools.Select);
            this.toolStripComboBoxApplyTerrainType.Enabled = this.terrainControl.TerrainTool.IsSet(TerrainControlTools.TerrainType);

            StringCollection seasons = new StringCollection();
            seasons.AddRange(SeasonExtensions.GetSortedList());
            this.toolStripComboBoxSeason.SelectedIndex = seasons.IndexOf(this.terrainControl.CurrentSeason.ToString());

            StringCollection terrainTypes = new StringCollection();
            terrainTypes.AddRange(TerrainTypeExtensions.GetSortedList());
            this.toolStripComboBoxApplyTerrainType.SelectedIndex = terrainTypes.IndexOf(this.terrainControl.ApplyTerrainType.ToString());

            this.toolStripTextBoxHeightLevel.TextChanged += this.ToolStripTextBoxHeightLevel_TextChanged;
            this.toolStripComboBoxSeason.SelectedIndexChanged += this.ToolStripComboBoxSeason_SelectedIndexChanged;
            this.toolStripButtonHideBaseSeasonTerrain.Click += this.ToolStripButtonHideBaseSeasonTerrain_Click;
            this.toolStripButtonSelect.Click += this.ToolStripButtonSelect_Click;
            this.toolStripButtonRaise.Click += this.ToolStripButtonRaise_Click;
            this.toolStripButtonLower.Click += this.ToolStripButtonLower_Click;
            this.toolStripButtonFlatten.Click += this.ToolStripButtonFlatten_Click;
            this.toolStripButtonSmooth.Click += this.ToolStripButtonSmooth_Click;
            this.toolStripTextBoxCursorSize.TextChanged += this.ToolStripTextBoxCursorSize_TextChanged;
            this.toolStripTextBoxIntensity.TextChanged += this.ToolStripTextBoxIntensity_TextChanged;
            this.toolStripButtonApplyTerrainType.Click += this.ToolStripButtonApplyTerrainType_Click;
            this.toolStripComboBoxApplyTerrainType.SelectedIndexChanged += this.ToolStripComboBoxApplyTerrainType_SelectedIndexChanged;
        }
Exemple #15
0
		public int LoadSelections (String [] Selectionen, int NumberOfEntries,
								DateTime FromDate, DateTime ToDate, String Format)
			{
			String SelectStatementPart;
			if ((Selectionen.Length == 0)
				|| ((Selectionen.Length == 1)
				&& (Selectionen [0] == "All")))
				{
				SelectStatementPart = "";
				}
			else
				{
				SelectStatementPart = "";
				foreach (String Entry in Selectionen)
					{
					if (SelectStatementPart == "")
						SelectStatementPart += "and ((ZuordnungName = '" + Basics.RemoveMaliciousSQLContent (Entry) + "') ";
					else
						SelectStatementPart += " or (ZuordnungName = '" + Basics.RemoveMaliciousSQLContent (Entry) + "') ";
					}
				SelectStatementPart += ") ";
				}
			String SelectStatement = "";
			if ((Format == "")
				|| (Format == "Full"))
				{
				if (NumberOfEntries > 0)
					SelectStatement = String.Format (CVM.CommonValues.SELECT_ARCHIVE_ENTRIES,
												"top (" + Convert.ToString (NumberOfEntries + 1) + ")",
												ToDate.ToString ("yyyy.MM.dd HH:mm:ss"),
												SelectStatementPart);
				else
					SelectStatement = String.Format (CVM.CommonValues.SELECT_ARCHIVE_ENTRIES,
												"",
												ToDate.ToString ("yyyy.MM.dd HH:mm:ss"),
												SelectStatementPart);
				}
			if (Format == "Grid")
				{
				SelectStatement = String.Format (CVM.CommonValues.SELECT_ARCHIVE_ENTRIES_LIST,
											ToDate.ToString ("yyyy.MM.dd HH:mm:ss"),
											SelectStatementPart);
				}

			try
				{
				m_ArchivDataSet = WPMediaDataBase.GetCommonDataSet (SelectStatement);
				}
			catch (Exception Exc)
				{
				String Reason = Exc.ToString();
				return 0;
				}
			if (m_ArchivDataSet == null)
				return 0;
			if (m_ArchivDataSet.Tables ["BeitraegeAusArchiv"] == null)
				return 0;
			int NumberOfReadedEntries = m_ArchivDataSet.Tables ["BeitraegeAusArchiv"].Rows.Count;
			if (m_ArchivDataSet.Tables ["BeitraegeAusArchiv"].Rows.Count > NumberOfEntries)
				m_MoreEntriesAvailable = true;
			StringCollection UniqueBeitrag = new StringCollection ();
			foreach (DataRow Row in m_ArchivDataSet.Tables ["BeitraegeAusArchiv"].Rows)
				{
				String BeitragID = Row ["BeitragID"].ToString ();
				if (UniqueBeitrag.IndexOf (BeitragID) == -1)
					{
					UniqueBeitrag.Add (BeitragID);
					}
				else
					{
					Row.Delete ();
					}
				}
			m_ArchivDataSet.Tables ["BeitraegeAusArchiv"].AcceptChanges ();
			return m_ArchivDataSet.Tables ["BeitraegeAusArchiv"].Rows.Count;
			}
Exemple #16
0
        protected string extractUrlFromSwfHtml(string swfHtml)
        {
            try
            {
                StringCollection videoURLsBrut = new StringCollection();
                StringCollection videoURLs = new StringCollection();
                String[] separateur = new String[1];
                StringCollection paramNames;
                separateur[0] = Settings.Default.separateurUrlYoutube;
                int index = -1;

                swfHtml = swfHtml.Substring(swfHtml.IndexOf(Settings.Default.debutUrlYoutube) + Settings.Default.debutUrlYoutube.Length);
                swfHtml = swfHtml.Substring(swfHtml.IndexOf(separateur[0]) + separateur[0].Length);
                swfHtml = swfHtml.Substring(0, swfHtml.IndexOf(Settings.Default.finSwfHtmlRelevant));
                paramNames = GetAllParamNames(swfHtml);

                videoURLsBrut.AddRange(swfHtml.Split(separateur, StringSplitOptions.RemoveEmptyEntries));

                foreach (String chaine in videoURLsBrut)
                {
                    if (chaine.StartsWith("http"))
                    {
                        String videoUrl = chaine.Trim();
                        separateur[0] = ",";
                        videoUrl = RemoveExtraParams(videoUrl, Settings.Default.paramNamesToRemoveYoutube.Split(separateur, StringSplitOptions.RemoveEmptyEntries));
                        int indexLastComa = chaine.LastIndexOf(",");
                        if (indexLastComa == videoUrl.Length - 1)
                            videoUrl = videoUrl.Substring(0, indexLastComa);

                        videoURLs.Add(videoUrl);
                    }
                }

                int currentTagPriorite = 998;
                foreach (String url in videoURLs)
                {
                    int itagIndex = url.IndexOf(Settings.Default.itagParam);
                    if (itagIndex != -1)
                    {
                        itagIndex += Settings.Default.itagParam.Length;
                        int indexSeparator = url.IndexOf(Settings.Default.paramSeparator, itagIndex);
                        String itagString = url.Substring(itagIndex, indexSeparator - itagIndex);
                        int itag = Convert.ToInt32(itagString);
                        int priorite = manager.getPrioriteFromFormatTag(itag);
                        if (priorite < currentTagPriorite)
                        {
                            currentTagPriorite = priorite;
                            index = videoURLs.IndexOf(url);
                        }
                    }
                }

                /*separateur[0] = ",";
                String resultUrl = RemoveExtraParams(videoURLs[index], null);*/
                return videoURLs[index];

                //Settings.Default.paramNamesToRemoveYoutube.Split(separateur, StringSplitOptions.RemoveEmptyEntries));
                /*                int nombreParamNamesAEnlever = (Settings.Default.paramNamesToRemoveYoutube.Split(separateur, StringSplitOptions.RemoveEmptyEntries)).Length;
                                for (int i = 0; i < nombreParamNamesAEnlever; i++)
                                {
                                    paramNames.RemoveAt(paramNames.Count - 1);
                                }

                                return videoURLs[index].Substring(0, GetIndexFinParams(videoURLs[index], paramNames));
                 * */
            }
            catch (Exception ex)
            {
                AddErrorMsg("YoutubeDownload.extractUrlFromSwfHtml swfHtml= " + swfHtml, ex);
                return null;
            }
        }
Exemple #17
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();

            // [] RemoveAt() for empty collection
            //
            if (sc.Count > 0)
                sc.Clear();
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(0); });

            // [] RemoveAt() on 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));
            }

            sc.RemoveAt(0);

            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.Contains(values[0]))
            {
                Assert.False(true, string.Format("Error, removed wrong item"));
            }

            // 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.RemoveAt(values.Length - 1);

            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.Contains(values[values.Length - 1]))
            {
                Assert.False(true, string.Format("Error, removed wrong item"));
            }

            // check that all init items were moved
            for (int i = 0; i < values.Length - 1; 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.RemoveAt(values.Length / 2);

            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.Contains(values[values.Length / 2]))
            {
                Assert.False(true, string.Format("Error, removed wrong item"));
            }

            // check that all init items were moved
            for (int i = 0; i < values.Length; i++)
            {
                int expected = i;
                if (i == values.Length / 2)
                    expected = -1;
                else
                    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));
                }
            }


            //
            // [] RemoveAt() on collection with identical items
            //

            sc.Clear();
            string intlStr = intl.GetRandomString(MAX_LEN);

            sc.Add(intlStr);        // index 0
            sc.AddRange(values);
            sc.Add(intlStr);        // second index values.Length + 1
            if (sc.Count != values.Length + 2)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, values.Length + 2));
            }

            // remove
            //
            sc.RemoveAt(values.Length + 1);
            if (!sc.Contains(intlStr))
            {
                Assert.False(true, string.Format("Error, removed both duplicates"));
            }
            // second string should still be present
            if (sc.IndexOf(intlStr) != 0)
            {
                Assert.False(true, string.Format("Error, removed 1st instance"));
            }


            //
            // [] Invalid parameter
            //


            sc.Clear();
            sc.AddRange(values);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(-1); });
            sc.Clear();
            sc.AddRange(values);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(sc.Count); });
            sc.Clear();
            sc.AddRange(values);
            Assert.Throws<ArgumentOutOfRangeException>(() => { sc.RemoveAt(sc.Count + 1); });
        }
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()
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


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

            sc = new StringCollection();

            // [] for empty collection
            //
            for (int i = 0; i < values.Length; i++)
            {
                if (sc.IndexOf(values[i]) != -1)
                {
                    Assert.False(true, string.Format("Error, returned {1} for empty collection", i, sc.IndexOf(values[i])));
                }
            }

            //
            // [] add simple strings and verify IndexOf()


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

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

            //
            // Intl strings
            // [] add Intl strings and verify IndexOf()
            //

            string[] intlValues = new string[values.Length];

            // fill array with unique strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            int len = values.Length;
            Boolean caseInsensitive = false;
            for (int i = 0; i < len; i++)
            {
                if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper())
                    caseInsensitive = true;
            }

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

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

            //
            // [] duplicate strings
            //
            sc.Clear();
            string intlStr = intlValues[0];

            sc.Add(intlStr);        // index 0
            sc.AddRange(values);
            sc.AddRange(intlValues);        // second index values.Length + 1
            cnt = values.Length + 1 + intlValues.Length;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, cnt));
            }

            // verify Index of newly added item
            //
            if (sc.IndexOf(intlStr) != 0)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), 0));
            }

            sc.Clear();

            sc.AddRange(values);
            sc.AddRange(intlValues);        // second index values.Length + 1
            sc.Add(intlStr);        // index values.Length + intlValues.Length
            cnt = values.Length + 1 + intlValues.Length;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, cnt));
            }

            // verify Index of newly added item
            //
            if (sc.IndexOf(intlStr) != values.Length)
            {
                Assert.False(true, string.Format("Error, IndexOf returned {0} instead of {1}", sc.IndexOf(intlStr), values.Length));
            }

            //
            // [] Case sensitivity: search should be case-sensitive
            //

            sc.Clear();
            sc.Add(intlValues[0].ToUpper());
            sc.AddRange(values);
            sc.Add(intlValues[0].ToLower());
            cnt = values.Length + 2;
            if (sc.Count != cnt)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2} ", sc.Count, cnt));
            }

            // look for lowercase item - should be (values.Length  + 1) index
            //
            intlStr = intlValues[0].ToLower();

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

            // string half_upper+half_lower should not be found
            //
            if (intlStr.Length > 2)
            {
                int mid = intlStr.Length / 2;
                String strTemp = intlStr.Substring(0, mid).ToLower() + intlStr.Substring(mid, intlStr.Length - mid).ToUpper();
                if (strTemp != intlStr.ToUpper() &&
                    strTemp != intlStr.ToLower() &&
                    !caseInsensitive)
                {
                    intlStr = strTemp;

                    if (sc.IndexOf(intlStr) != -1)
                    {
                        Assert.False(true, string.Format("Error, IndexOf() returned {0} instead of -1 ", sc.IndexOf(intlStr)));
                    }
                }
            }
        }
Exemple #19
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()
            };

            int cnt = 0;            // Count
            int ind = 0;            // Index

            // initialize IntStrings
            intl = new IntlStrings();


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

            sc = new StringCollection();

            // [] Add() simple strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                cnt = sc.Count;
                sc.Add(values[i]);
                if (sc.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sc.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (!sc.Contains(values[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain new item", i));
                }

                // verify that item was added at the end
                //
                ind = sc.IndexOf(values[i]);
                if (ind != sc.Count - 1)
                {
                    Assert.False(true, string.Format("Error, returned index {1} instead of {2}", i, ind, sc.Count - 1));
                }

                //  access the item
                //
                if (ind != -1)
                {
                    if (String.Compare(sc[ind], values[i]) != 0)
                    {
                        Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sc[ind], values[i]));
                    }
                }
            }

            //
            // Intl strings
            // [] Add() Intl strings
            //
            string[] intlValues = new string[values.Length];

            // fill array with unique strings
            //
            for (int i = 0; i < values.Length; i++)
            {
                string val = intl.GetRandomString(MAX_LEN);
                while (Array.IndexOf(intlValues, val) != -1)
                    val = intl.GetRandomString(MAX_LEN);
                intlValues[i] = val;
            }

            for (int i = 0; i < intlValues.Length; i++)
            {
                cnt = sc.Count;

                sc.Add(intlValues[i]);
                if (sc.Count != cnt + 1)
                {
                    Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sc.Count, cnt + 1));
                }

                // verify that collection contains newly added item
                //
                if (!sc.Contains(intlValues[i]))
                {
                    Assert.False(true, string.Format("Error, collection doesn't contain new item", i));
                }

                // verify that item was added at the end
                //
                ind = sc.IndexOf(intlValues[i]);
                if (ind != sc.Count - 1)
                {
                    Assert.False(true, string.Format("Error, returned index {1} instead of {2}", i, ind, sc.Count - 1));
                }

                //  access the item
                //
                if (ind != -1)
                {
                    if (String.Compare(sc[ind], intlValues[i]) != 0)
                    {
                        Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sc[ind], intlValues[i]));
                    }
                }
            }

            //
            // add very long string
            // [] Add() very long string
            //
            cnt = sc.Count;
            string intlStr = intlValues[0];
            while (intlStr.Length < 10000)
                intlStr += intlStr;

            sc.Add(intlStr);
            if (sc.Count != cnt + 1)
            {
                Assert.False(true, string.Format("Error, count is {1} instead of {2}", sc.Count, cnt + 1));
            }

            // verify that collection contains newly added item
            //
            if (!sc.Contains(intlStr))
            {
                Assert.False(true, string.Format("Error, collection doesn't contain new item"));
            }

            // verify that item was added at the end
            //
            ind = sc.IndexOf(intlStr);
            if (ind != sc.Count - 1)
            {
                Assert.False(true, string.Format("Error, returned index {1} instead of {2}", ind, sc.Count - 1));
            }

            //  access the item
            //
            if (ind != -1)
            {
                if (String.Compare(sc[ind], intlStr) != 0)
                {
                    Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", sc[ind], intlStr));
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Adds the passed hif name / version number to the list of hifs installed on
        /// the module.  Both arrays must be the same length.
        /// </summary>
        /// <param name="hifs">The hifs to add</param>
        /// <param name="versions">The version numbers of the hifs</param>
        public void AddInstalledHakInfos(string[] hifs, float[] versions)
        {
            // Get the current values if any.
            string[] currentHifs;
            float[] currentVersions;
            GetInstalledHakInfos(out currentHifs, out currentVersions);

            // Create StringCollections for them so we can use IndexOf() for searching.
            StringCollection colHifs = new StringCollection();
            colHifs.AddRange(currentHifs);
            ArrayList colVersions = new ArrayList();
            colVersions.AddRange(currentVersions);

            // Check for duplicates, pruning duplicates out of the current list.
            foreach (string hif in hifs)
            {
                // Find the hif in the current values, if we don't find it then
                // skip it.
                int index = colHifs.IndexOf(hif);
                if (-1 == index) continue;

                // Remove it from the current list.
                colHifs.RemoveAt(index);
                colVersions.RemoveAt(index);
            }

            // Now build a string with all of the current hifs/version numbers then
            // all of the added hif/version numbers.
            System.Text.StringBuilder b = new StringBuilder();
            for (int i = 0; i < colHifs.Count; i++)
            {
                if (b.Length > 0) b.Append(";");
                b.AppendFormat("{0};{1}", colHifs[i], colVersions[i].ToString());
            }
            for (int i = 0; i < hifs.Length; i++)
            {
                if (b.Length > 0) b.Append(";");
                b.AppendFormat("{0};{1}", hifs[i], versions[i].ToString());
            }

            // Get the schema for the field and get it, creating it if it is not there.
            // Then save the StringBuilder text as the field's value.
            GffFieldSchema schema = properties["installedhifs"];
            GffExoStringField field = (GffExoStringField) GetField(schema);
            field.Value = b.ToString();
        }
Exemple #21
0
 public bool ValueExists(string Section, string Ident)
 {
     StringCollection Idents = new StringCollection();
     ReadSection(Section, Idents);
     return Idents.IndexOf(Ident) > -1;
 }
Exemple #22
0
        /// <summary>
        /// This method updates the cache and hak list properties in the module
        /// info, adding the passed array of strings to the appropriate property.
        /// Both of these lists consist of an array of structures with 1 string
        /// item in each struture.
        /// </summary>
        /// <param name="listTag">The property name for the list</param>
        /// <param name="entryTag">The property name for each string in the list's 
        /// structures</param>
        /// <param name="structID">The structure ID of the structures in the list</param>
        /// <param name="stringType">The data type of the string in the list, either
        /// ExoString or ResRef</param>
        /// <param name="values">The array of strings to add, duplicates are pruned</param>
        private void UpdateList(string listTag, string entryTag, uint structID, 
			GffFieldType stringType, string[] values)
        {
            // Get the array of elements in the list.
            GffListField listField = (GffListField) GetField(properties[listTag]);
            GffFieldCollection list = listField.Value;

            // Create a string collection containing lower case copies of all of
            // the strings.
            StringCollection strings = new StringCollection();
            strings.AddRange(values);
            for (int i = 0; i < strings.Count; i ++)
                strings[i] = strings[i].ToLower();

            // Make a first pass and eliminate any strings that are already
            // in the module.
            foreach (GffStructField field in list)
            {
                // Get the string entry for the value.
                GffFieldDictionary dict = field.Value;
                GffField structValue = dict[entryTag];

                // Check to see if the hak is in the list of haks to add if it is
                // then remove it.
                int index = strings.IndexOf((string) structValue.Value);
                if (-1 != index) strings.RemoveAt(index);
            }

            // Now loop through all of the remaining strings and add them to the
            // beginning of the list.  We walk the list backwards adding the items
            // to the beginning of the list's collection, so when we are done
            // all of the added items are in order at the FRONT of the list.
            for (int i = strings.Count - 1; i >= 0; i--)
            {
                // Create a ExoString field for the hak file name.
                GffField structValue = GffFieldFactory.CreateField(stringType);
                structValue.Value = strings[i];

                // Create a GffStructField for the new list element and
                // save the exoString hak name in it.
                GffStructField listStruct = (GffStructField)
                    GffFieldFactory.CreateField(GffFieldType.Struct);
                listStruct.StructureType = structID;
                listStruct.Value = new GffFieldDictionary();
                listStruct.Value.Add(entryTag, structValue);

                // Add the structure to the list.
                list.Insert(0, listStruct);
            }
        }
Exemple #23
0
 public bool SectionExists(String Section)
 {
     StringCollection Sections = new StringCollection();
     ReadSections(Sections);
     return Sections.IndexOf(Section) > -1;
 }
Exemple #24
0
        protected string extractUrlFromBrutSwfHtml(string swfHtml)
        {
            try
            {
                StringCollection videoURLsBrut = new StringCollection();
                String[] separateurs = new String[1];
                separateurs[0] = ",";
                int index = -1;

                swfHtml = swfHtml.Substring(swfHtml.IndexOf(Settings.Default.debutUrlYoutube) + Settings.Default.debutUrlYoutube.Length);
                swfHtml = swfHtml.Substring(swfHtml.IndexOf("\"") + 1);
                swfHtml = swfHtml.Substring(0, swfHtml.IndexOf(Settings.Default.finSwfHtmlRelevant));

                videoURLsBrut.AddRange(swfHtml.Split(separateurs, StringSplitOptions.RemoveEmptyEntries));

                int currentTagPriorite = 998;
                foreach (String chaine in videoURLsBrut)
                {
                    String temp = chaine.Replace("\\u0026", "&");
                    int itagIndex = temp.IndexOf(Settings.Default.itagParam);
                    if (itagIndex != -1)
                    {
                        itagIndex += Settings.Default.itagParam.Length;
                        int indexSeparator = temp.IndexOf("&", itagIndex);
                        String itagString;
                        if (indexSeparator == -1)
                            itagString = temp.Substring(itagIndex);
                        else
                            itagString = temp.Substring(itagIndex, indexSeparator - itagIndex);

                        int itag = Convert.ToInt32(itagString);
                        int priorite = manager.getPrioriteFromFormatTag(itag);
                        if (priorite < currentTagPriorite)
                        {
                            currentTagPriorite = priorite;
                            index = videoURLsBrut.IndexOf(chaine);
                        }
                    }
                }

                if (index != -1)
                {

                    String chaine = videoURLsBrut[index].Replace("\\u0026", "&");
                    int indexDebutSignature = chaine.IndexOf(Settings.Default.youtubeSignatureParam) + Settings.Default.youtubeSignatureParam.Length;
                    int indexFinSignature = chaine.IndexOf("&", indexDebutSignature);
                    String signature;
                    if (indexFinSignature == -1)
                        signature = chaine.Substring(indexDebutSignature);
                    else
                        signature = chaine.Substring(indexDebutSignature, indexFinSignature - indexDebutSignature);

                    int indexDebutUrl = chaine.IndexOf(Settings.Default.separateurUrlYoutube) + Settings.Default.separateurUrlYoutube.Length;
                    int indexFinUrl = chaine.IndexOf("&", indexDebutUrl);
                    String videoUrl;
                    if (indexFinUrl == -1)
                        videoUrl = chaine.Substring(indexDebutUrl);
                    else
                        videoUrl = chaine.Substring(indexDebutUrl, indexFinUrl - indexDebutUrl);

                    videoUrl = CleanASCIICoding(videoUrl) + "&" + Settings.Default.youtubeSignatureParamOut + "=" + signature;

                    return videoUrl;
                }
                else
                {
                    AddInfoMsg("YoutubeDownload.extractUrlFromBrutSwfHtml index = -1 for  swfHtml= " + swfHtml);
                    return null;
                }
            }
            catch (Exception ex)
            {
                AddErrorMsg("YoutubeDownload.extractUrlFromSwfHtml swfHtml= " + swfHtml, ex);
                return null;
            }
        }
Exemple #25
0
    /// <summary>
    /// Remove an element from an array by value and optionally a number of elements after it.
    /// </summary>
    /// <param name="array">The array to remove the value from</param>
    /// <param name="value">The value to remove</param>
    /// <param name="count">The number of elements after the value to remove aswell</param>
    /// <returns>An array without the value</returns>
    public static string[] RemoveParameter(string[] array, string value, int count)
    {
      if (Array.IndexOf(array, value) < 0)
        return array;
      else
      {
        StringCollection coll = new StringCollection();
        coll.AddRange(array);
        int ind = coll.IndexOf(value);
        for (int i = ind + count; i >= ind; i--)
          coll.RemoveAt(ind);

        string[] output = new string[coll.Count];
        coll.CopyTo(output, 0);
        return output;
      }
    }
Exemple #26
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;
        }
Exemple #27
0
    /// <summary>
    /// Extract flags, named and numbered parameters from a string array of arguments
    /// </summary>
    /// <param name="named">The found named parameters</param>
    /// <param name="numbered">The found numbered parameters</param>
    /// <param name="input">The arguments</param>
    /// <param name="flags">Allowed flags to find</param>
    public static void ExtractParameters(out StringDictionary named, out string[] numbered, string[] input, string[] flags)
    {
      named = new StringDictionary();
      StringCollection numberedColl = new StringCollection();
      StringCollection args = new StringCollection();
      args.AddRange(input);

      // Pull out flags first
      if (flags != null)
      {
        for (int i = 0; i < flags.Length; i++)
        {
          int ind = -1;
          if ((ind = args.IndexOf("-" + flags[i])) >= 0)
          {
            named.Add(flags[i], string.Empty);
            //	args.RemoveAt(ind);
            args[ind] = null;
          }
        }
      }

      // pull out named parameters
      StringEnumerator e = args.GetEnumerator();
      string name = string.Empty;
      while (e.MoveNext())
      {
        if (e.Current != null)
        {
          if (name != string.Empty)
          {
            string nextname = string.Empty;
            string value = e.Current;
            if (value == null)
              value = string.Empty;

            if (value.StartsWith("-") && value.Length > 1)
            {
              nextname = value.Substring(1);
              value = string.Empty;
            }

            if (value.StartsWith("\\-"))
              value = "-" + value.Substring(2);

            named.Add(name, value);

            if (nextname != string.Empty)
              name = nextname;
            else
              name = string.Empty;
          }
          else if (e.Current.StartsWith("-") && e.Current.Length > 1)
            name = e.Current.Substring(1);
          else
          {
            string value = e.Current;
            if (value.StartsWith("\\-"))
              value = "-" + value.Substring(2);

            numberedColl.Add(value);
          }
        }
        else
        {
          if (name != string.Empty)
          {
            named.Add(name, string.Empty);
            name = string.Empty;
          }
        }
      }

      if (name != string.Empty)
        named.Add(name, string.Empty);

      // Pull out numbered parameters
      numbered = new string[numberedColl.Count];
      numberedColl.CopyTo(numbered, 0);
    }
Exemple #28
0
        void LightAndRunScene(string sceneName)
        {
            string vsceneName = Path.ChangeExtension(Path.GetFileName(sceneName), ".vscene");

              DeleteLitFileForScene(sceneName); // before the scene starts
              CommonSubtestInit(sceneName);
              int iFrameCount = 2000;

              VisionEngineManager em = (VisionEngineManager)EditorManager.EngineManager;
              StringCollection names = new StringCollection();
              em.GetReplacementRenderLoopEffects(names);
              int iLightShading = names.IndexOf("Lighting Only");
              Assert.IsTrue(iLightShading >= 0, "Lighting only shading not available");

              // render frames
              EditorManager.Scene.ResetStaticLighting();
              for (int i = 0; i < iFrameCount; i++)
              {
            EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "Unlit version of the scene", VisionColors.White);
            EditorManager.ActiveView.UpdateView(true);
              }

              // get the currently set lighting tool (might be Beast or something)
              IStaticLightingTool lt = EditorManager.LightingTool;
              // set vLux as the current tool
              EditorManager.LightingTool = new VLux.VLuxLightingTool ();

              Assert.IsTrue(EditorApp.Scene.UpdateStaticLighting(false, null, true)); // without dialog

              // reset to the original lighting tool
              EditorManager.LightingTool = lt;

              for (int i = 0; i < iFrameCount; i++)
              {
            EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "..after vLux lighting", VisionColors.White);
            EditorManager.ActiveView.UpdateView(true);
              }
              em.SetReplacementRenderLoopEffect(iLightShading);
              for (int i = 0; i < iFrameCount; i++)
              {
            EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "..after vLux lighting light shading only", VisionColors.White);
            EditorManager.ActiveView.UpdateView(true);
              }
              em.SetReplacementRenderLoopEffect(-1);

              // now export and see whether projector looks identically
              EditorManager.Scene.ExportScene(null, null);
              EditorManager.Scene.Close();
              TestManager.Helpers.LoadExportedScene(vsceneName);
              for (int i = 0; i < iFrameCount; i++)
              {
            EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "This is the exported version", VisionColors.White);
            EditorManager.ActiveView.UpdateView(true);
              }
              TestManager.Helpers.CloseExportedScene();

              // reload the scene
              CommonSubtestInit(sceneName);
              // render frames
              EditorManager.Scene.ResetStaticLighting();
              for (int i = 0; i < iFrameCount; i++)
              {
            EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "Unlit version of the scene (again)", VisionColors.White);
            EditorManager.ActiveView.UpdateView(true);
              }
              // export again to restore SVN files
              EditorManager.Scene.ExportScene(null, null);

              CommonSubtestDeInit();
        }
 /// <summary>
 /// The process button.
 /// </summary>
 /// <param name="indexOfUserData">
 /// The index of user data.
 /// </param>
 /// <param name="indexOfString">
 /// The index of string.
 /// </param>
 /// <param name="attributes">
 /// The attributes.
 /// </param>
 /// <param name="values">
 /// The values.
 /// </param>
 private void ProcessButton(string indexOfUserData, string indexOfString, StringCollection attributes, StringCollection values)
 {
     if (attributes.Contains(indexOfUserData))
     {
         var processName = values[attributes.IndexOf(indexOfUserData)];
         var content = attributes.Contains(indexOfString) ? values[attributes.IndexOf(indexOfString)] : "Button ??";
         if (!Utilities.IsNumber(processName))
         {
             DebugViewModel.Instance.ProcessAnalysisViewModel.LoadProcessFromExpression(
                 SourceDefinition.Button,
                 SourceDefinition.Process,
                 processName,
                 this,
                 content);
         }
     }
 }
Exemple #30
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 #31
0
        /// <summary>
        /// Insert a table into the project database .
        /// </summary>
        /// <param name="dataTable">Insert this table to the project database.</param>
        /// <param name="pathDB">Path to the database.</param>
        /// <param name="requiredCols">Collection of required columns.</param>
        public static bool CreateTable(DataTable dataTable, string pathDB, params IAccessColumn[] requiredCols)
        {
            //Validate the table;
            if (dataTable == null || string.IsNullOrEmpty(dataTable.TableName))
            {
                //ActiveStatus.UpdateStatus(new DataStatus("The table is not valid and cannot be parsed. The table may not be named.", Environment.StackTrace, "Unknown Table"));
                return false;
            }

            //List of column names and indices;
            StringCollection colName = new StringCollection();
            StringCollection primaryKey = new StringCollection();
            StringCollection unique = new StringCollection();

            //Check if the required columns exists;
            if (requiredCols != null)
                foreach (IAccessColumn col in requiredCols)
                {

                    //Check if the column exists;
                    if (!dataTable.Columns.Contains(col.ColumnName))
                    {
                        //ActiveStatus.UpdateStatus(new DataStatus("The table is missing a required column and cannot be parsed. The names of the columns are case-sensitive.", Environment.StackTrace, dataTable.TableName));
                        return false;
                    }

                    //Store the name of the column;
                    colName.Add(col.ColumnName);

                    //Store the indices;
                    if (col.PrimaryKey)
                        primaryKey.Add(col.ColumnName);
                    if (col.Unique)
                        unique.Add(col.ColumnName);
                }

            //Remove the existing table;
            string sql = string.Format("drop table if exists {0};", dataTable.TableName);

            //Create the new table declaration;
            sql += string.Format("create table {0}(", dataTable.TableName);

            //Declare the columns;
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {

                //Give priority to pre-defined columns;
                if (colName.Contains(dataTable.Columns[i].ColumnName))
                    sql += BuildColumnDefinition(requiredCols[colName.IndexOf(dataTable.Columns[i].ColumnName)]);
                else
                    sql += BuildColumnDefinition(dataTable.Columns[i]);

                //Append a comma or close the bracket;
                if (i < dataTable.Columns.Count - 1)
                    sql += ",";
                else
                {

                    //Add constraints;
                    if (primaryKey.Count > 0)
                    {
                        string[] sz = new string[primaryKey.Count];
                        primaryKey.CopyTo(sz, 0);
                        sql += string.Format(",primary key ({0}) on conflict ignore", string.Join(",", sz).ToString());
                    }
                    if (unique.Count > 0)
                    {
                        string[] sz = new string[unique.Count];
                        unique.CopyTo(sz, 0);
                        sql += string.Format(",unique ({0}) on conflict ignore", string.Join(",", sz));
                    }

                    //Close command;
                    sql += ");";
                }
            }

            //Establish the connection;
            SQLiteConnection conn = Query.OpenConnection(pathDB) as SQLiteConnection;

            //Begin a transaction;
            if (conn != null)
                using (SQLiteTransaction t = conn.BeginTransaction())
                {

                    //Create the table;
                    SQLiteCommand cmd = new SQLiteCommand(sql, conn, t);
                    try { cmd.ExecuteNonQuery(); }
                    catch { return false; }

                    //Import the data;
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        cmd.CommandText = string.Format("insert into {0} values(", dataTable.TableName);
                        for (int i = 0; i < dataTable.Columns.Count; i++)
                        {

                            //Append the value;
                            Type dataType = dataTable.Columns[i].DataType;
                            if (colName.Contains(dataTable.Columns[i].ColumnName))
                                dataType = requiredCols[colName.IndexOf(dataTable.Columns[i].ColumnName)].Type;
                            if (dataType == typeof(float) || dataType == typeof(double) || dataType == typeof(int))
                                cmd.CommandText += dr[i].ToString();
                            else
                                cmd.CommandText += string.Format("'{0}'", dr[i].ToString());

                            //Append comma or else bracket at the end of the line;
                            if (i < dataTable.Columns.Count - 1)
                                cmd.CommandText += ",";
                            else
                                cmd.CommandText += ");";
                        }
                        try { cmd.ExecuteNonQuery(); }
                        catch { return false; }
                    }

                    //Close the transation;
                    t.Commit();

                    //Return;
                    //ActiveStatus.UpdateStatus(new DataStatus(string.Format("The table {0} was successfully parsed to: {1}", dataTable.TableName, pathDB), Environment.StackTrace, dataTable.TableName));
                    return true;
                }

            //Return false if the transaction was not initialized or else did not complete;
            return false;
        }