Contains() public method

public Contains ( object key ) : bool
key object
return bool
Esempio n. 1
0
        /// <summary>
        /// Returns true if all items in <paramref name="names0"/> and <paramref name="names1"/> are 
        /// unique strings.  Case sensitivity consideration depends on <paramref name="ignoreCase"/>.
        /// </summary>
        /// <param name="names0">An array of strings.</param>
        /// <param name="names1">An array of strings.</param>
        /// <param name="ignoreCase">If true then case is not considered when comparing strings.</param>
        /// <returns>bool</returns>
        public static bool AreNamesUnique(string[] names0, string[] names1, bool ignoreCase)
        {
            bool result = true;
            if (names0 == null && names1 == null)
                return result;

            ListDictionary dic = new ListDictionary(StringComparer.Create(new CultureInfo("en"), ignoreCase));

            for (int i = 0; i < names0.Length; i++)
            {
                if (dic.Contains(names0[i]))
                {
                    result = false;
                    break;
                }
                dic.Add(names0[i], null);
            }
            for (int i = 0; i < names1.Length; i++)
            {
                if (dic.Contains(names1[i]))
                {
                    result = false;
                    break;
                }
                dic.Add(names1[i], null);
            }
            if (dic.Count == 0)
                result = false; // when both arrays are empty
            return result;
        }
Esempio n. 2
0
		private void BasicTests (ListDictionary ld)
		{
			Assert.AreEqual (0, ld.Count, "Count");
			Assert.IsFalse (ld.IsFixedSize, "IsFixedSize");
			Assert.IsFalse (ld.IsReadOnly, "IsReadOnly");
			Assert.IsFalse (ld.IsSynchronized, "IsSynchronized");
			Assert.AreEqual (0, ld.Keys.Count, "Keys");
			Assert.AreEqual (0, ld.Values.Count, "Values");
			Assert.IsNotNull (ld.SyncRoot, "SyncRoot");
			Assert.IsNotNull (ld.GetEnumerator (), "GetEnumerator");
			Assert.IsNotNull ((ld as IEnumerable).GetEnumerator (), "IEnumerable.GetEnumerator");

			ld.Add ("a", "1");
			Assert.AreEqual (1, ld.Count, "Count-1");
			Assert.IsTrue (ld.Contains ("a"), "Contains(a)");
			Assert.IsFalse (ld.Contains ("1"), "Contains(1)");

			ld.Add ("b", null);
			Assert.AreEqual (2, ld.Count, "Count-2");
			Assert.IsNull (ld["b"], "this[b]");

			DictionaryEntry[] entries = new DictionaryEntry[2];
			ld.CopyTo (entries, 0);

			ld["b"] = "2";
			Assert.AreEqual ("2", ld["b"], "this[b]2");

			ld.Remove ("b");
			Assert.AreEqual (1, ld.Count, "Count-3");
			ld.Clear ();
			Assert.AreEqual (0, ld.Count, "Count-4");
		}
Esempio n. 3
0
 public bool Contains(Object key)
 {
     if (hash != null)
     {
         return(hash.Contains(key));
     }
     else
     {
         return(list.Contains(key));
     }
 }
        public bool Contains(object key)
        {
            ListDictionary list = this.list;

            if (this.hashtable != null)
            {
                return(this.hashtable.ContainsKey(key as string));
            }
            if (list != null)
            {
                return(list.Contains(key));
            }
            if (key == null)
            {
                throw new ArgumentNullException("key", SR.GetString("ArgumentNull_Key"));
            }
            return(false);
        }
		public void BuildDriveList()
		{
			base.Items.Clear();

			ShellAPI.SHFILEINFO shInfo = new ShellAPI.SHFILEINFO();
			ShellAPI.SHGFI dwAttribs = 
				ShellAPI.SHGFI.SHGFI_ICON |
				ShellAPI.SHGFI.SHGFI_SMALLICON |
				ShellAPI.SHGFI.SHGFI_SYSICONINDEX |
				ShellAPI.SHGFI.SHGFI_DISPLAYNAME;

			ListDictionary _iconDict = new ListDictionary();			
			foreach( string drive in System.IO.Directory.GetLogicalDrives() )
			{
				IntPtr m_pHandle = ShellAPI.SHGetFileInfo(drive, ShellAPI.FILE_ATTRIBUTE_NORMAL, ref shInfo, (uint)System.Runtime.InteropServices.Marshal.SizeOf(shInfo), dwAttribs);

				if( m_pHandle.Equals(IntPtr.Zero)==false )					
				{
					int idxIcon = 0;
					if( _iconDict.Contains(shInfo.iIcon)==false )
					{
						base.ImageList.Images.Add( System.Drawing.Icon.FromHandle(shInfo.hIcon).Clone() as System.Drawing.Icon );

						User32API.DestroyIcon(shInfo.hIcon);

						_iconDict.Add( shInfo.iIcon, _iconDict.Count );
						idxIcon = _iconDict.Count-1;
					}
					else
						idxIcon = Convert.ToInt32( _iconDict[shInfo.iIcon] );


					ImageComboItem item = new ImageComboItem(shInfo.szDisplayName, idxIcon, false);
					item.ItemValue = drive;
					base.Items.Add( item );
				}
			}

			if( base.Items.Count!=0 )
				base.SelectedIndex = 0;
		}
Esempio n. 6
0
        public bool Contains(object key)
        {
            ListDictionary cachedList = _list;

            if (_hashtable != null)
            {
                return(_hashtable.Contains(key));
            }
            else if (cachedList != null)
            {
                return(cachedList.Contains(key));
            }
            else
            {
                if (key == null)
                {
                    throw new ArgumentNullException("key", SR.ArgumentNull_Key);
                }
                return(false);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Returns an array of strings where all entries are unique.  If a duplicate string is found,
        /// then it is modified using the <see cref="NamingHelper.Reformat()"/> method.
        /// </summary>
        /// <param name="names">An array of strings.</param>
        /// <returns>An array of strings of equal length as the input array</returns>
        public static string[] MakeUnique(string[] names)
        {
            string[] results = new string[names.Length];
            int ctr;
            ListDictionary dic = new ListDictionary();
            for (int i = 0; i < names.Length; i++)
            {
                results[i] = string.Copy(names[i]);
                ctr = 1;    // ctr is 1 based, as the 0th item is already in the array
                while (dic.Contains(results[i]))
                    results[i] = Reformat(names[i], ctr++);
                dic.Add(results[i], null);
            }

            return results;
        }
Esempio n. 8
0
        /// <summary>
        /// Identifies all entries in <paramref name="names0"/> which match an entry in <paramref name="names1"/> and 
        /// if a duplicate string is found, then it is modified using the <see cref="NamingHelper.Reformat()"/> method.
        /// The returned array will not have duplicates which match any entry in <paramref name="names1"/>.  Case sensitivity
        /// is considered.
        /// </summary>
        /// <param name="names1">An array of strings.</param>
        /// <returns>An array of strings of equal length as the input array</returns>
        public static string[] MakeUnique(string[] names0, string[] names1)
        {
            if (names0 == null && names1 == null)
                return new string[0];

            var results = new string[names0.Length + names1.Length];
            int ctr;
            var dic = new ListDictionary();
            for (int i = 0; i < names0.Length; i++)
            {
                results[i] = string.Copy(names0[i]);
                ctr = 1;    // ctr is 1 based, as the 0th item is already in the array
                while (dic.Contains(results[i]))
                    results[i] = Reformat(names0[i], ctr++);
                dic.Add(results[i], null);
            }
            int offset = names0.Length;
            for (int i = 0; i < names1.Length; i++)
            {
                results[i + offset] = string.Copy(names1[i]);
                ctr = 1;
                while (dic.Contains(results[i + offset]))
                    results[i + offset] = Reformat(names1[i], ctr++);
                dic.Add(results[i + offset], null);
            }
            return results;
        }
Esempio n. 9
0
        private void doAnova()
        {
            REngine engine = REngine.GetInstance();
            daoChart _daoChart = new daoChart();

            DataSet dsRec = new DataSet();
            DataTable dtRec = new DataTable();
            ListDictionary Diets = new ListDictionary();
            List<double> dMeasure = new List<double>();
            List<string> sDiet = new List<string>();
 
            dsRec = _daoChart.getRData(1);
            dtRec = dsRec.Tables[0];
            int k = 0;
            for (int j = 0; j < dtRec.Rows.Count; j++)
            {
                if (!Diets.Contains(dtRec.Rows[j]["C"].ToString()))
                {
                    Diets.Add(dtRec.Rows[j]["C"].ToString(), k);
                    sDiet.Add(dtRec.Rows[j]["C"].ToString());
                    k++;
                }
            }
            List<double>[] dDataAll = new List<double>[Diets.Count];
            List<double>[] dDataFemale = new List<double>[Diets.Count];
            List<double>[] dDataMale = new List<double>[Diets.Count];


            foreach (DictionaryEntry de in Diets)
            {
                dDataAll[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataMale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataFemale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
            }

            for (int i = 0; i < dtRec.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dtRec.Rows[i]["WEIGHT"].ToString()))
                    continue;

                foreach (DictionaryEntry entry in Diets)
                {
                    if (entry.Key.ToString().Equals(dtRec.Rows[i]["C"].ToString()))
                    {
                        dDataAll[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        if (dtRec.Rows[i]["SEX"].ToString().Equals("M"))
                            dDataMale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));
                        else
                            dDataFemale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        break;
                    }

                }
            }

            /*double[] test = new double[Diets.Count];

            for (int j = 0; j < test.Length; j++)
            {
                test[j] = doMeans(dDataMale[j].ToArray());

            }*/

            List<string> testString = new List<string>();
            List<double> testDouble = new List<double>();
            for (int j = 0; j < dtRec.Rows.Count; j++)
            {
                if (dtRec.Rows[j]["SEX"].ToString().Equals("M"))
                {
                    testString.Add(dtRec.Rows[j]["C"].ToString());
                    testDouble.Add(Convert.ToDouble(dtRec.Rows[j]["WEIGHT"].ToString()));
                }
            }

            engine.SetSymbol("measure", engine.CreateNumericVector(testDouble.ToArray()));
            engine.SetSymbol("diet", engine.CreateCharacterVector(testString.ToArray()));

           /* var res = engine.Evaluate("anova(y ~ a, data = data.frame(y = measure, a = diet))").AsList()["Pr(>F)"].AsNumeric();

            for (int loop = 0; loop < res.Length; loop++)
                tbREngine.Text += res[loop] + "\n\n";*/

            engine.Evaluate("bob <- aov(y~a, data.frame(y = measure, a = diet)");
            var resName = engine.Evaluate("names(bob)").AsList().AsCharacter();
            int loop = 0;
            for (loop = 0; loop < resName.Length; loop++)
                tbREngine.Text += resName[loop].ToString() + "\n";

            var resSum = engine.Evaluate("summary(bob)").AsList().AsCharacter();

            string newsummary = resSum[0].ToString();
            newsummary = newsummary.Replace("list(", string.Empty);
            newsummary = newsummary.Replace("'", string.Empty);
            newsummary = newsummary.Replace("c", string.Empty);
            string[] sumArray = newsummary.Split('=');

            for (loop = 0; loop < sumArray.Length; loop++ )
                tbREngine.Text += sumArray[loop].ToString() + "\n";

           // var res = engine.Evaluate("anova1)").AsList()["Pr(>F)"].AsNumeric();
            /*List<string> test = new List<string>();
            foreach (var loop in res)
                test.Add(loop.ToString());*/

            var res1 = engine.Evaluate("tapply(measure, diet, mean)").AsNumeric();
            var res2 = engine.Evaluate("tapply(measure, diet, var)").AsNumeric();
            var res3 = engine.Evaluate("tapply(measure, diet, length)").AsNumeric();
            var res4 = engine.Evaluate("tapply(measure, diet, sd, na.rm=T)").AsNumeric();
            var res5 = engine.Evaluate("tapply(measure, diet, min, na.rm=T)").AsNumeric();
            var res6 = engine.Evaluate("tapply(measure, diet, max, na.rm=T)").AsNumeric();


            for (int j = 0; j < sDiet.Count; j++)
            {
                tbREngine.Text += sDiet[j].ToString() + "\n";
                tbREngine.Text += "Mean: " + res1[j].ToString() + "\n";
                tbREngine.Text += "Variance: " +res2[j].ToString() + "\n";
                tbREngine.Text += "Length: " + res3[j].ToString() + "\n";
                tbREngine.Text += "Standard Dev: " + res4[j].ToString() + "\n";
                tbREngine.Text += "Minimum: " + res5[j].ToString() + "\n";
                tbREngine.Text += "Maximum: " + res6[j].ToString() + "\n";
                tbREngine.Text += "Standard Error of the Means: " + (Math.Sqrt(Convert.ToDouble(res4[j].ToString()))/(Convert.ToDouble(res3[j].ToString()))).ToString() + "\n\n";
            }

        }
Esempio n. 10
0
 public MemberInfo[] GetMembers(Type type)
 {
     Stack stack = new Stack();
     while (type != null)
     {
         stack.Push(type);
         type = type.BaseType;
     }
     IDictionary members = new ListDictionary();
     foreach (Type htype in stack)
     {
         foreach (MemberInfo member in htype.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
         {
             if (members.Contains(member.Name))
                 members.Remove(member.Name);
             members.Add(member.Name, member);
         }
     }
     return (MemberInfo[]) new ArrayList(members.Values).ToArray(typeof(MemberInfo));
 }
Esempio n. 11
0
        public void Test01()
        {
            IntlStrings intl;
            ListDictionary ld;
            Object itm;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            //  initialize IntStrings
            intl = new IntlStrings();


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

            ld = new ListDictionary();

            //  [] on empty dictionary
            //
            cnt = ld.Count;
            Assert.Throws<ArgumentNullException>(() => { itm = ld[null]; });

            cnt = ld.Count;
            itm = ld["some_string"];
            if (itm != null)
            {
                Assert.False(true, string.Format("Error, returned non=null"));
            }

            cnt = ld.Count;
            itm = ld[new Hashtable()];
            if (itm != null)
            {
                Assert.False(true, string.Format("Error, returned non-null"));
            }

            //  [] get Item() on dictionary filled with simple strings
            //

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

            for (int i = 0; i < len; i++)
            {
                if (!ld.Contains(keys[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain key", i));
                }
                if (String.Compare(ld[keys[i]].ToString(), values[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned wrong value", i));
                }
            }


            //
            // Intl strings
            //  [] get Item() on dictionary filled with Intl strings
            //

            string[] intlValues = new string[len * 2];

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

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

            cnt = ld.Count;
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);
            }
            if (ld.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                if (!ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain key", i));
                }
                if (String.Compare(ld[intlValues[i + len]].ToString(), intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned wrong value", i));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpper();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLower();
            }

            ld.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key
                if (!ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain key", i));
                }

                if (String.Compare(ld[intlValues[i + len]].ToString(), intlValues[i]) != 0)
                {
                    Assert.False(true, string.Format("Error, returned wrong value", i));
                }
            }

            ld.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //  LD is case-sensitive by default
            for (int i = 0; i < len; i++)
            {
                // lowercase key
                cnt = ld.Count;
                if (!caseInsensitive && ld[intlValuesLower[i + len]] != null)
                {
                    Assert.False(true, string.Format("Error, failed: returned non-null for lowercase key", i));
                }
            }

            //
            //  [] get Item() on filled dictionary with case-insensitive comparer

            ld = new ListDictionary(new InsensitiveComparer());

            len = values.Length;
            ld.Clear();
            string kk = "key";
            for (int i = 0; i < len; i++)
            {
                ld.Add(kk + i, values[i]);
            }
            if (ld.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                if (ld[kk.ToUpper() + i] == null)
                {
                    Assert.False(true, string.Format("Error, returned null for differently cased key", i));
                }
                else
                {
                    if (String.Compare(ld[kk.ToUpper() + i].ToString(), values[i]) != 0)
                    {
                        Assert.False(true, string.Format("Error, returned wrong value", i));
                    }
                }
            }


            //
            //   [] Item(null) for dilled dictionary
            //
            ld = new ListDictionary();
            cnt = ld.Count;
            if (ld.Count < len)
            {
                ld.Clear();
                for (int i = 0; i < len; i++)
                {
                    ld.Add(keys[i], values[i]);
                }
            }

            Assert.Throws<ArgumentNullException>(() => { itm = ld[null]; });

            //  [] get Item(special_object)
            //
            ld = new ListDictionary();

            ld.Clear();
            ArrayList b = new ArrayList();
            ArrayList b1 = new ArrayList();
            Hashtable lbl = new Hashtable();
            Hashtable lbl1 = new Hashtable();

            ld.Add(lbl, b);
            ld.Add(lbl1, b1);
            if (ld.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2));
            }

            if (!ld[lbl].Equals(b))
            {
                Assert.False(true, string.Format("Error, failed to access special object"));
            }
            if (!ld[lbl1].Equals(b1))
            {
                Assert.False(true, string.Format("Error, failed to access special object"));
            }
        }
Esempio n. 12
0
		//ExtendedProperties
		//	Per config
		//		Platform : Eg. Any CPU
		//		SolutionConfigurationPlatforms
		//
		SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor)
		{
			string headerComment;
			string version = GetSlnFileVersion (fileName, out headerComment);

			ListDictionary globals = null;
			SolutionFolder folder = null;
			SlnData data = null;
			List<Section> projectSections = null;
			List<string> lines = null;
			
			FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format);

			monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1);
			//Parse the .sln file
			using (StreamReader reader = new StreamReader(fileName)) {
				sol.FileName = fileName;
				sol.ConvertToFormat (projectFormat, false);
				folder = sol.RootFolder;
				sol.Version = "0.1"; //FIXME:
				data = new SlnData ();
				folder.ExtendedProperties [typeof (SlnFileFormat)] = data;
				data.VersionString = version;
				data.HeaderComment = headerComment;

				string s = null;
				projectSections = new List<Section> ();
				lines = new List<string> ();
				globals = new ListDictionary ();
				//Parse
				while (reader.Peek () >= 0) {
					s = GetNextLine (reader, lines).Trim ();

					if (String.Compare (s, "Global", StringComparison.OrdinalIgnoreCase) == 0) {
						ParseGlobal (reader, lines, globals);
						continue;
					}

					if (s.StartsWith ("Project", StringComparison.Ordinal)) {
						Section sec = new Section ();
						projectSections.Add (sec);

						sec.Start = lines.Count - 1;

						int e = ReadUntil ("EndProject", reader, lines);
						sec.Count = (e < 0) ? 1 : (e - sec.Start + 1);

						continue;
					}

					if (s.StartsWith ("VisualStudioVersion = ", StringComparison.Ordinal)) {
						Version v;
						if (Version.TryParse (s.Substring ("VisualStudioVersion = ".Length), out v))
							data.VisualStudioVersion = v;
						else
							monitor.Log.WriteLine ("Ignoring unparseable VisualStudioVersion value in sln file");
					}

					if (s.StartsWith ("MinimumVisualStudioVersion = ", StringComparison.Ordinal)) {
						Version v;
						if (Version.TryParse (s.Substring ("MinimumVisualStudioVersion = ".Length), out v))
							data.MinimumVisualStudioVersion = v;
						else
							monitor.Log.WriteLine ("Ignoring unparseable MinimumVisualStudioVersion value in sln file");
					}
				}
			}

			monitor.BeginTask("Loading projects ..", projectSections.Count + 1);
			Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> ();
			List<SolutionItem> sortedList = new List<SolutionItem> ();
			foreach (Section sec in projectSections) {
				monitor.Step (1);
				Match match = ProjectRegex.Match (lines [sec.Start]);
				if (!match.Success) {
					LoggingService.LogDebug (GettextCatalog.GetString (
						"Invalid Project definition on line number #{0} in file '{1}'. Ignoring.",
						sec.Start + 1,
						fileName));

					continue;
				}

				try {
					// Valid guid?
					new Guid (match.Groups [1].Value);
				} catch (FormatException) {
					//Use default guid as projectGuid
					LoggingService.LogDebug (GettextCatalog.GetString (
						"Invalid Project type guid '{0}' on line #{1}. Ignoring.",
						match.Groups [1].Value,
						sec.Start + 1));
					continue;
				}

				string projTypeGuid = match.Groups [1].Value.ToUpper ();
				string projectName = match.Groups [2].Value;
				string projectPath = match.Groups [3].Value;
				string projectGuid = match.Groups [4].Value.ToUpper ();
				List<string> projLines;

				if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) {
					//Solution folder
					SolutionFolder sfolder = new SolutionFolder ();
					sfolder.Name = projectName;
					MSBuildProjectService.InitializeItemHandler (sfolder);
					MSBuildProjectService.SetId (sfolder, projectGuid);

					projLines = lines.GetRange (sec.Start + 1, sec.Count - 2);
					DeserializeSolutionItem (sol, sfolder, projLines);
					
					foreach (string f in ReadFolderFiles (projLines))
						sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f));
					
					SlnData slnData = new SlnData ();
					slnData.Extra = projLines.ToArray ();
					sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData;

					items.Add (projectGuid, sfolder);
					sortedList.Add (sfolder);
					
					continue;
				}

				if (projectPath.StartsWith("http://")) {
					monitor.ReportWarning (GettextCatalog.GetString (
						"{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.",
						fileName, sec.Start + 1, projectPath));
					data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count));
					continue;
				}

				string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath);
				if (String.IsNullOrEmpty (path)) {
					monitor.ReportWarning (GettextCatalog.GetString (
						"Invalid project path found in {0} : {1}", fileName, projectPath));
					LoggingService.LogWarning (GettextCatalog.GetString (
						"Invalid project path found in {0} : {1}", fileName, projectPath));
					continue;
				}

				projectPath = Path.GetFullPath (path);
				
				SolutionEntityItem item = null;
				
				try {
					if (sol.IsSolutionItemEnabled (projectPath)) {
						item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate {
							return MSBuildProjectService.LoadItem (monitor, projectPath, format, projTypeGuid, projectGuid);
						});
						
						if (item == null) {
							throw new UnknownSolutionItemTypeException (projTypeGuid);
						}
					} else {
						var uitem = new UnloadedSolutionItem () {
							FileName = projectPath
						};
						var h = new MSBuildHandler (projTypeGuid, projectGuid) {
							Item = uitem,
						};
						uitem.SetItemHandler (h);
						item = uitem;
					}
					
				} catch (Exception e) {
					// If we get a TargetInvocationException from using Activator.CreateInstance we
					// need to unwrap the real exception
					while (e is TargetInvocationException)
						e = ((TargetInvocationException) e).InnerException;
					
					bool loadAsProject = false;

					if (e is UnknownSolutionItemTypeException) {
						var name = ((UnknownSolutionItemTypeException)e).TypeName;

						var relPath = new FilePath (path).ToRelative (sol.BaseDirectory);
						if (!string.IsNullOrEmpty (name)) {
							var guids = name.Split (';');
							var projectInfo = MSBuildProjectService.GetUnknownProjectTypeInfo (guids, fileName);
							if (projectInfo != null) {
								loadAsProject = projectInfo.LoadFiles;
								LoggingService.LogWarning (string.Format ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ()));
								monitor.ReportWarning (GettextCatalog.GetString ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ()));
							} else {
								LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type '{1}'", relPath, name));
								monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", relPath, name));
							}
						} else {
							LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type", relPath));
							monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", relPath));
						}

					} else if (e is UserException) {
						var ex = (UserException) e;
						LoggingService.LogError ("{0}: {1}", ex.Message, ex.Details);
						monitor.ReportError (string.Format ("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.Details), null);
					} else {
						LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e);
						monitor.ReportWarning (GettextCatalog.GetString (
							"Error while trying to load the project '{0}': {1}", projectPath, e.Message));
					}

					SolutionEntityItem uitem;
					if (loadAsProject) {
						uitem = new UnknownProject () {
							FileName = projectPath,
							LoadError = e.Message,
						};
					} else {
						uitem = new UnknownSolutionItem () {
							FileName = projectPath,
							LoadError = e.Message,
						};
					}

					var h = new MSBuildHandler (projTypeGuid, projectGuid) {
						Item = uitem,
					};
					uitem.SetItemHandler (h);
					item = uitem;
				}

				MSBuildHandler handler = (MSBuildHandler) item.ItemHandler;
				projLines = lines.GetRange (sec.Start + 1, sec.Count - 2);
				DataItem it = GetSolutionItemData (projLines);

				handler.UnresolvedProjectDependencies = ReadSolutionItemDependencies (projLines);
				handler.SlnProjectContent = projLines.ToArray ();
				handler.ReadSlnData (it);

				if (!items.ContainsKey (projectGuid)) {
					items.Add (projectGuid, item);
					sortedList.Add (item);
					data.ItemsByGuid [projectGuid] = item;
				} else {
					monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null);
				}
			}
			monitor.EndTask ();

			if (globals != null && globals.Contains ("NestedProjects")) {
				LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor);
				globals.Remove ("NestedProjects");
			}

			// Resolve project dependencies
			foreach (var it in items.Values.OfType<SolutionEntityItem> ()) {
				MSBuildHandler handler = (MSBuildHandler) it.ItemHandler;
				if (handler.UnresolvedProjectDependencies != null) {
					foreach (var id in handler.UnresolvedProjectDependencies.ToArray ()) {
						SolutionItem dep;
						if (items.TryGetValue (id, out dep) && dep is SolutionEntityItem) {
							handler.UnresolvedProjectDependencies.Remove (id);
							it.ItemDependencies.Add ((SolutionEntityItem)dep);
						}
					}
					if (handler.UnresolvedProjectDependencies.Count == 0)
						handler.UnresolvedProjectDependencies = null;
				}
			}

			//Add top level folders and projects to the main folder
			foreach (SolutionItem ce in sortedList) {
				if (ce.ParentFolder == null)
					folder.Items.Add (ce);
			}

			//FIXME: This can be just SolutionConfiguration also!
			if (globals != null) {
				if (globals.Contains ("SolutionConfigurationPlatforms")) {
					LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines,
						sol, monitor);
					globals.Remove ("SolutionConfigurationPlatforms");
				}

				if (globals.Contains ("ProjectConfigurationPlatforms")) {
					LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines,
						sol, monitor);
					globals.Remove ("ProjectConfigurationPlatforms");
				}

				if (globals.Contains ("MonoDevelopProperties")) {
					LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines,	sol, monitor);
					globals.Remove ("MonoDevelopProperties");
				}
				
				ArrayList toRemove = new ArrayList ();
				foreach (DictionaryEntry e in globals) {
					string name = (string) e.Key;
					if (name.StartsWith ("MonoDevelopProperties.")) {
						int i = name.IndexOf ('.');
						LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor);
						toRemove.Add (e.Key);
					}
				}
				foreach (object key in toRemove)
					globals.Remove (key);
			}

			//Save the global sections that we dont use
			List<string> globalLines = new List<string> ();
			foreach (Section sec in globals.Values)
				globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count));

			data.GlobalExtra = globalLines;
			monitor.EndTask ();

			// When reloading a project, keep the solution data and item id
			sol.SolutionItemAdded += delegate(object sender, SolutionItemChangeEventArgs e) {
				if (e.Reloading) {
					ItemSlnData.TransferData (e.ReplacedItem, e.SolutionItem);
					var ih = e.SolutionItem.ItemHandler as MSBuildHandler;
					if (ih != null)
						ih.ItemId = e.ReplacedItem.ItemId;
				}
			};

			return folder;
		}
 private void ParseNode( Object parent, Object context, XmlNode node, Hashtable config, String prefix )
 {
     foreach ( XmlNode item in node.ChildNodes ) {
         if ( item.NodeType.Equals(XmlNodeType.Element) ) {
             String sectionname = String.Concat(prefix, "/", item.Name);;
             switch ( item.Name ) {
                 case "general":
                 case "login":
                 case "message":
                 case "inbox":
                     SingleTagSectionHandler singlesection = new SingleTagSectionHandler();
                     InitConfigSection(config, sectionname, singlesection.Create(parent, context, item) as System.Collections.Hashtable);
                     break;
                 case "read":
                 case "send":
                     if ( item.HasChildNodes )
                         ParseNode( parent, context, item, config, sectionname );
                     break;
                 case "servers":
                     if ( item.HasChildNodes )
                         config.Add(sectionname, ParseConfigServers(item.ChildNodes));
                     break;
                 case "addressbook":
                     if ( !config.Contains(sectionname) )
                         config.Add(sectionname, new SortedList());
                     SortedList addressbooks = (SortedList)config[sectionname];
                     Hashtable tmpaddressbook = (Hashtable)(new System.Configuration.SingleTagSectionHandler()).Create(parent, context, item);
                     ListDictionary addressbook = new ListDictionary(new System.Collections.CaseInsensitiveComparer());
                     foreach ( String configitem in tmpaddressbook.Keys) {
                         addressbook.Add(configitem, tmpaddressbook[configitem]);
                     }
                     tmpaddressbook = null;
                     if ( addressbook.Contains("type") && !addressbook["type"].Equals("none") && addressbook.Contains("name") && !addressbooks.Contains(addressbook["name"]) ) {
                         if ( addressbook.Contains("pagesize") )
                             addressbook["pagesize"] = ParseConfigElement(addressbook["pagesize"].ToString(), 10);
                         else
                             addressbook["pagesize"] = 10;
                         addressbooks.Add(addressbook["name"], addressbook);
                         if ( addressbook.Contains("allowupdate") )
                             addressbook["allowupdate"] = ParseConfigElement(addressbook["allowupdate"].ToString(), false);
                         else
                             addressbook["allowupdate"] = false;
                     }
                     break;
             }
         }
     }
 }
        private void RenderActiveScriptBlocks(List<UpdatePanel> updatePanels,
            HtmlTextWriter writer,
            string token,
            List<RegisteredScript> scriptRegistrations) {
            
            List<RegisteredScript> entriesToRender = new List<RegisteredScript>();
            // no comparer needed because it will contain ScriptKeys which implement Equals
            ListDictionary uniqueEntries = new ListDictionary();

            // For each entry registered in the page, check and see which ones
            // came from controls within UpdatePanels that are going to be updated.
            Control lastControl = null;
            foreach (RegisteredScript entry in scriptRegistrations) {
                Control child = entry.Control;

                bool isActive = ((lastControl != null) && (child == lastControl)) ||
                    IsControlRegistrationActive(updatePanels, child, true);

                if (isActive) {
                    lastControl = child;
                    ScriptKey scriptKey = new ScriptKey(entry.Type, entry.Key);
                    if (!uniqueEntries.Contains(scriptKey)) {
                        entriesToRender.Add(entry);
                        uniqueEntries.Add(scriptKey, entry);
                    }
                }
            }

            foreach (RegisteredScript activeRegistration in entriesToRender) {
                if (String.IsNullOrEmpty(activeRegistration.Url)) {
                    if (activeRegistration.AddScriptTags) {
                        PageRequestManager.EncodeString(writer,
                            token,
                            "ScriptContentNoTags",
                            activeRegistration.Script);
                    }
                    else {
                        WriteScriptWithTags(writer, token, activeRegistration);
                    }
                }
                else {
                    PageRequestManager.EncodeString(writer,
                        token,
                        "ScriptPath",
                        activeRegistration.Url);
                }

                string fallbackScriptPath;
                if (_fallbackScripts != null && _fallbackScripts.TryGetValue(new ScriptKey(activeRegistration.Type, activeRegistration.Key), out fallbackScriptPath)) {
                    // Only encode the fallback path and not the expression. On the client, we would use the success flag on load / readystatechanged to 
                    // determine if the script was successfully fetched.
                    PageRequestManager.EncodeString(writer,
                        "fallbackScript",
                        fallbackScriptPath,
                        content: null);
                }
            }
        }
		private void HandleExternalNamespace (string prefix, string ns, ListDictionary includes)
		{
			if (includes.Contains (ns))
				return; // nothing to do
			includes.Add (ns, "_" + prefix + ".xsd");
		}
Esempio n. 16
0
        public void Test01()
        {
            ListDictionary ld;
            IDictionaryEnumerator en;

            DictionaryEntry curr;        // Enumerator.Current value
            DictionaryEntry de;        // Enumerator.Entry value
            Object k;        // Enumerator.Key value
            Object v;        // Enumerator.Value

            // simple string values
            string[] values =
            {
                "a",
                "aa",
                "",
                " ",
                "text",
                "     spaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "one",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };


            // [] ListDictionary GetEnumerator()
            //-----------------------------------------------------------------

            ld = new ListDictionary();

            // [] for empty dictionary
            //
            en = ld.GetEnumerator();
            string type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return false
            //
            bool res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });
            //
            //   []  for Filled dictionary
            //
            for (int i = 0; i < values.Length; i++)
            {
                ld.Add(keys[i], values[i]);
            }

            en = ld.GetEnumerator();
            type = en.GetType().ToString();
            if (type.IndexOf("Enumerator", 0) == 0)
            {
                Assert.False(true, string.Format("Error, type is not Enumerator"));
            }

            //
            //  MoveNext should return true
            //

            for (int i = 0; i < ld.Count; i++)
            {
                res = en.MoveNext();
                if (!res)
                {
                    Assert.False(true, string.Format("Error, MoveNext returned false", i));
                }

                curr = (DictionaryEntry)en.Current;
                de = en.Entry;
                //
                //enumerator enumerates in different than added order
                // so we'll check Contains
                //
                if (!ld.Contains(curr.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!ld.Contains(en.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain key from enumerator", i));
                }
                if (!ld.Contains(de.Key.ToString()))
                {
                    Assert.False(true, string.Format("Error, Current dictionary doesn't contain Entry.Key from enumerator", i));
                }
                if (String.Compare(ld[curr.Key.ToString()].ToString(), curr.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i));
                }
                if (String.Compare(ld[de.Key.ToString()].ToString(), de.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, Entry.Value for current Entry.Key is different in dictionary", i));
                }
                if (String.Compare(ld[en.Key.ToString()].ToString(), en.Value.ToString()) != 0)
                {
                    Assert.False(true, string.Format("Error, En-tor.Value for current En-tor.Key is different in dictionary", i));
                }

                // while we didn't MoveNext, Current should return the same value
                DictionaryEntry curr1 = (DictionaryEntry)en.Current;
                if (!curr.Equals(curr1))
                {
                    Assert.False(true, string.Format("Error, second call of Current returned different result", i));
                }
                DictionaryEntry de1 = en.Entry;
                if (!de.Equals(de1))
                {
                    Assert.False(true, string.Format("Error, second call of Entry returned different result", i));
                }
            }

            // next MoveNext should bring us outside of the collection
            //
            res = en.MoveNext();
            res = en.MoveNext();
            if (res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned true"));
            }

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //
            //  Attempt to get Key should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { k = en.Key; });

            //
            //  Attempt to get Value should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { v = en.Value; });

            en.Reset();

            //
            //  Attempt to get Current should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });

            //
            //  Attempt to get Entry should result in exception
            //
            Assert.Throws<InvalidOperationException>(() => { de = en.Entry; });

            //
            //   [] Modify dictionary when enumerating
            //
            if (ld.Count < 1)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    ld.Add(keys[i], values[i]);
                }
            }

            en = ld.GetEnumerator();
            res = en.MoveNext();
            if (!res)
            {
                Assert.False(true, string.Format("Error, MoveNext returned false"));
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;
            int cnt = ld.Count;
            ld.Remove(keys[0]);
            if (ld.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr2 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr2))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // will return just removed item
            DictionaryEntry de2 = en.Entry;
            if (!de.Equals(de2))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }

            // will return just removed item
            Object k2 = en.Key;
            if (!k.Equals(k2))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }

            // will return just removed item
            Object v2 = en.Value;
            if (!v.Equals(v2))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });


            //
            //   [] Modify dictionary after enumerated beyond the end
            //
            ld.Clear();
            for (int i = 0; i < values.Length; i++)
            {
                ld.Add(keys[i], values[i]);
            }

            en = ld.GetEnumerator();
            for (int i = 0; i < ld.Count; i++)
            {
                en.MoveNext();
            }
            curr = (DictionaryEntry)en.Current;
            de = en.Entry;
            k = en.Key;
            v = en.Value;

            cnt = ld.Count;
            ld.Remove(keys[0]);
            if (ld.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
            }

            // will return just removed item
            DictionaryEntry curr3 = (DictionaryEntry)en.Current;
            if (!curr.Equals(curr3))
            {
                Assert.False(true, string.Format("Error, current returned different value after modification"));
            }

            // will return just removed item
            de2 = en.Entry;
            if (!de.Equals(de2))
            {
                Assert.False(true, string.Format("Error, Entry returned different value after modification"));
            }

            // will return just removed item
            k2 = en.Key;
            if (!k.Equals(k2))
            {
                Assert.False(true, string.Format("Error, Key returned different value after modification"));
            }

            // will return just removed item
            v2 = en.Value;
            if (!v.Equals(v2))
            {
                Assert.False(true, string.Format("Error, Value returned different value after modification"));
            }

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });

            // exception expected
            Assert.Throws<InvalidOperationException>(() => { en.Reset(); });

            /////////////////////////////////////
            //// Code coverage
            //
            // [] Call IEnumerable.GetEnumerator()
            //
            en = ld.GetEnumerator();
            IEnumerator en2 = ((IEnumerable)ld).GetEnumerator();
            if (en2 == null)
            {
                Assert.False(true, string.Format("Error, enumerator was null"));
            }
        }
Esempio n. 17
0
 /// <summary>
 /// Creates the specified attribute calculate recurrence.
 /// </summary>
 /// <param name="iCalRecurrence">The attribute calculate recurrence.</param>
 /// <param name="patternStart">The pattern start.</param>
 /// <param name="timeZone">The time zone.</param>
 /// <param name="duration">The duration.</param>
 /// <returns></returns>
 public static IRecurrencePattern Create(string iCalRecurrence, DateTime patternStart, TimeZone timeZone,
     TimeSpan duration)
 {
     AsyncServiceException.ThrowIfNull(iCalRecurrence, "iCalRecurrence");
     AsyncServiceException.ThrowIfNull(timeZone, "timeZone");
     AsyncServiceException.ThrowIfNegative(duration, "duration");
     var recurrencePattern = new RecurrencePattern(patternStart, timeZone, duration);
     if (iCalRecurrence.EndsWith(";"))
     {
         iCalRecurrence = iCalRecurrence.Substring(0, iCalRecurrence.Length - 1);
     }
     var parts = iCalRecurrence.Split(new char[]
         {
             ';'
         });
     var partDictionary = new ListDictionary();
     for (int i = 0; i < parts.Length; i++)
     {
         string text = parts[i];
         string[] aPart = text.Split(new[]
             {
                 '='
             });
         if (aPart.Length != 2)
         {
             throw new InvalidRecurrenceRuleException(String.Format(CultureInfo.InvariantCulture,
                                                                      "每个规则必须是使用等号分隔的键值对(2部分)。实际却多于2部分: {0}",
                                                                      aPart.Length));
         }
         string partName = aPart[0];
         string partValue = aPart[1];
         if (partDictionary.Contains(partName))
         {
             throw new InvalidRecurrenceRuleException(String.Format(CultureInfo.InvariantCulture,
                                                                      "重复出现 {0} 分部。",
                                                                      partName));
         }
         PartParserBase partParserBase =
             PartParserFactory.Create(partName);
         partParserBase.Parse(partValue, recurrencePattern);
         partDictionary.Add(partName, partParserBase);
     }
     foreach (PartParserBase parserBase in partDictionary.Values)
     {
         parserBase.ThrowIfInvalid(recurrencePattern);
     }
     if (recurrencePattern.Frequency == RecurrenceFrequency.None)
     {
         throw new InvalidRecurrenceRuleException("重复模式必须包含 FREQ 分部。");
     }
     return recurrencePattern;
 }
Esempio n. 18
0
        private void doTTest()
        {
            REngine engine = REngine.GetInstance();
            daoChart _daoChart = new daoChart();

            DataSet dsRec = new DataSet();
            DataTable dtRec = new DataTable();
            ListDictionary Diets = new ListDictionary();

            dsRec = _daoChart.getRData(1);
            dtRec = dsRec.Tables[0];

            int k = 0;
            for (int j = 0; j < dtRec.Rows.Count; j++)
            {
                if (!Diets.Contains(dtRec.Rows[j]["C"].ToString()))
                {
                    Diets.Add(dtRec.Rows[j]["C"].ToString(), k);
                    k++;
                }
            }
            List<double>[] dData = new List<double>[Diets.Count];

            foreach (DictionaryEntry de in Diets)
            {
                dData[Convert.ToInt32(de.Value.ToString())] = new List<double>();
            }

            for (int i = 0; i < dtRec.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dtRec.Rows[i]["WEIGHT"].ToString()))
                    continue;

                foreach (DictionaryEntry entry in Diets)
                {
                    if (entry.Key.ToString().Equals(dtRec.Rows[i]["C"].ToString()))
                    {
                        dData[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));
                        break;
                    }

                }
            }

            foreach (DictionaryEntry deVector in Diets)
            {
                NumericVector Vgroup1 = engine.CreateNumericVector(dData[Convert.ToInt32(deVector.Value)].ToArray());
                engine.SetSymbol(deVector.Key.ToString(), Vgroup1);
                foreach (DictionaryEntry compareVector in Diets)
                {
                    NumericVector Vgroup2 = engine.CreateNumericVector(dData[Convert.ToInt32(compareVector.Value)].ToArray());
                    if (!deVector.Key.ToString().Equals(compareVector.Key.ToString()))
                    {
                        engine.SetSymbol(compareVector.Key.ToString(), Vgroup2);
                        GenericVector testResult1 = engine.Evaluate("t.test(" + deVector.Key.ToString() + "," +
                        compareVector.Key.ToString() + ")").AsList();
                        double p1 = testResult1["p.value"].AsNumeric().First();
                        tbREngine.Text += deVector.Key.ToString() + "\\" + compareVector.Key.ToString();
                        tbREngine.Text += "\nP1-value = {0:0.000}" + p1 + "\n\n";
                        //engine.ClearGlobalEnvironment();
                    }
                }
            }

        }
Esempio n. 19
0
        private void doQuantile()
        {
            REngine engine = REngine.GetInstance();
            daoChart _daoChart = new daoChart();

            DataSet dsRec = new DataSet();
            DataTable dtRec = new DataTable();
            ListDictionary Diets = new ListDictionary();

            dsRec = _daoChart.getRData(1);
            dtRec = dsRec.Tables[0];

            int k = 0;
            for (int j = 0; j < dtRec.Rows.Count; j++)
            {
                if (!Diets.Contains(dtRec.Rows[j]["C"].ToString()))
                {
                    Diets.Add(dtRec.Rows[j]["C"].ToString(), k);
                    k++;
                }
            }
            List<double>[] dDataAll = new List<double>[Diets.Count];
            List<double>[] dDataFemale = new List<double>[Diets.Count];
            List<double>[] dDataMale = new List<double>[Diets.Count];


            foreach (DictionaryEntry de in Diets)
            {
                dDataAll[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataMale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataFemale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
            }

            for (int i = 0; i < dtRec.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dtRec.Rows[i]["WEIGHT"].ToString()))
                    continue;

                foreach (DictionaryEntry entry in Diets)
                {
                    if (entry.Key.ToString().Equals(dtRec.Rows[i]["C"].ToString()))
                    {
                        dDataAll[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        if (dtRec.Rows[i]["SEX"].ToString().Equals("M"))
                            dDataMale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));
                        else
                            dDataFemale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        break;
                    }

                }
            }

            int meanLoop = 0;
            foreach (DictionaryEntry de in Diets)
            {
                engine.SetSymbol("ALL", engine.CreateNumericVector(dDataAll[meanLoop].ToArray()));
                var testResult = engine.Evaluate("quantile(ALL)").AsNumeric();
                tbREngine.Text += de.Key.ToString() + " All \n";
                for (int qloop = 0; qloop < 4; qloop++ )
                    tbREngine.Text += testResult[qloop].ToString() + "\n";
                tbREngine.Text += "\n";
                engine.SetSymbol("MALE", engine.CreateNumericVector(dDataMale[meanLoop].ToArray()));
                testResult = engine.Evaluate("quantile(MALE)").AsNumeric();
                tbREngine.Text += de.Key.ToString() + " Male \n";
                for (int qloop = 0; qloop < 4; qloop++)
                    tbREngine.Text += testResult[qloop].ToString() + "\n";
                tbREngine.Text += "\n";
                engine.SetSymbol("FEMALE", engine.CreateNumericVector(dDataFemale[meanLoop].ToArray()));
                testResult = engine.Evaluate("boxplot(FEMALE, vertical=true)").AsNumeric();
                tbREngine.Text += de.Key.ToString() + " Female \n";
                for (int qloop = 0; qloop < 4; qloop++)
                    tbREngine.Text += testResult[qloop].ToString() + "\n";
                tbREngine.Text += "\n";
                meanLoop++;
            }

        }
Esempio n. 20
0
        public void Test01()
        {
            IntlStrings intl;
            ListDictionary ld;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


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

            ld = new ListDictionary();

            // [] Contains() on empty dictionary
            //
            Assert.Throws<ArgumentNullException>(() => { ld.Contains(null); });

            if (ld.Contains("some_string"))
            {
                Assert.False(true, string.Format("Error, empty dictionary contains some_object"));
            }
            if (ld.Contains(new Hashtable()))
            {
                Assert.False(true, string.Format("Error, empty dictionary contains some_object"));
            }

            //  [] simple strings and Contains()
            //

            cnt = ld.Count;
            int len = values.Length;
            for (int i = 0; i < len; i++)
            {
                ld.Add(keys[i], values[i]);
            }
            if (ld.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, values.Length));
            }
            //
            for (int i = 0; i < len; i++)
            {
                if (!ld.Contains(keys[i]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, keys[i]));
                }
            }


            //
            // Intl strings
            // [] Intl strings and Contains()
            //

            string[] intlValues = new string[len * 2];

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

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

            ld.Clear();
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);
            }
            if (ld.Count != (len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                if (!ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain \"{1}\"", i, intlValues[i + len]));
                }
            }


            //
            // [] Case sensitivity
            // by default ListDictionary is case-sensitive
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpper();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLower();
            }

            ld.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key
                if (!ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, doesn't contain added uppercase \"{1}\"", i, intlValues[i + len]));
                }

                // lowercase key
                if (!caseInsensitive && ld.Contains(intlValuesLower[i + len]))
                {
                    Assert.False(true, string.Format("Error, contains lowercase \"{1}\" - should not", i, intlValuesLower[i + len]));
                }
            }

            //  [] different_in_casing_only keys and Contains()
            //

            ld.Clear();
            string[] ks = { "Key", "kEy", "keY" };
            len = ks.Length;
            for (int i = 0; i < len; i++)
            {
                ld.Add(ks[i], "Value" + i);
            }
            if (ld.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
            }

            if (ld.Contains("Value0"))
            {
                Assert.False(true, string.Format("Error, returned true when should not"));
            }
            for (int i = 0; i < len; i++)
            {
                if (!ld.Contains(ks[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }


            //
            //   [] Contains(null) - for filled dictionary
            //
            ld.Clear();
            for (int i = 0; i < len; i++)
            {
                ld.Add(keys[i], values[i]);
            }
            Assert.Throws<ArgumentNullException>(() => { ld.Contains(null); });

            // [] Contains() for case-insensitive comparer
            //

            ld = new ListDictionary(new InsensitiveComparer());
            ld.Clear();
            len = ks.Length;
            ld.Add(ks[0], "Value0");

            for (int i = 1; i < len; i++)
            {
                Assert.Throws<ArgumentException>(() => { ld.Add(ks[i], "Value" + i); });
            }
            if (ld.Count != 1)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 1));
            }

            if (ld.Contains("Value0"))
            {
                Assert.False(true, string.Format("Error, returned true when should not"));
            }
            for (int i = 0; i < len; i++)
            {
                if (!ld.Contains(ks[i]))
                {
                    Assert.False(true, string.Format("Error, returned false when true expected", i));
                }
            }
            if (!ld.Contains("KEY"))
            {
                Assert.False(true, string.Format("Error, returned false non-existing-cased key"));
            }

            // [] Contains() and objects_not_overriding_Equals
            //

            ld = new ListDictionary();
            ld.Clear();
            Hashtable lbl = new Hashtable();
            Hashtable lbl1 = new Hashtable();
            ArrayList b = new ArrayList();
            ArrayList b1 = new ArrayList();
            ld.Add(lbl, b);
            ld.Add(lbl1, b1);

            Assert.Throws<ArgumentException>(() => { ld.Add(lbl, "Hello"); });

            if (ld.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2));
            }

            if (!ld.Contains(lbl))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (!ld.Contains(lbl1))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (ld.Contains(new Hashtable()))
            {
                Assert.False(true, string.Format("Error, returned true when false expected"));
            }

            //  [] Contains and Special_Comparer for objects
            //

            ld = new ListDictionary(new SpecialComparer());
            lbl["foo"] = "Hello";
            lbl1["foo"] = "Hello";
            ld.Add(lbl, b);

            Assert.Throws<ArgumentException>(() => { ld.Add(lbl1, b1); });

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

            if (!ld.Contains(lbl))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (!ld.Contains(lbl1))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            lbl1["foo"] = "HELLO";
            if (ld.Contains(lbl1))
            {
                Assert.False(true, string.Format("Error, returned true when false expected"));
            }

            //  [] Contains() and special_structs_not_overriding_Equals
            ld = new ListDictionary();
            SpecialStruct s = new SpecialStruct();
            s.Num = 1;
            s.Wrd = "one";
            SpecialStruct s1 = new SpecialStruct();
            s.Num = 1;
            s.Wrd = "one";
            ld.Add(s, "first");
            ld.Add(s1, "second");
            if (ld.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2));
            }
            if (!ld.Contains(s))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
            if (!ld.Contains(s1))
            {
                Assert.False(true, string.Format("Error, returned false when true expected"));
            }
        }
Esempio n. 21
0
		/// <summary>
		/// Emit attribute for Attributable symbol
		/// </summary>
		public void Emit (ListDictionary allEmitted)
		{
			CustomAttributeBuilder cb = Resolve ();
			if (cb == null)
				return;

			AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
			if ((usage_attr.ValidOn & Target) == 0) {
				Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
					      "It is valid on `{1}' declarations only",
					GetSignatureForError (), GetValidTargets ());
				return;
			}

			try {
				foreach (Attributable owner in owners)
					owner.ApplyAttributeBuilder (this, cb);
			}
			catch (Exception e) {
				Error_AttributeEmitError (e.Message);
				return;
			}

			if (!usage_attr.AllowMultiple && allEmitted != null) {
				if (allEmitted.Contains (this)) {
					ArrayList a = allEmitted [this] as ArrayList;
					if (a == null) {
						a = new ArrayList (2);
						allEmitted [this] = a;
					}
					a.Add (this);
				} else {
					allEmitted.Add (this, null);
				}
			}

			if (!RootContext.VerifyClsCompliance)
				return;

			// Here we are testing attribute arguments for array usage (error 3016)
			if (Owner.IsClsComplianceRequired ()) {
				if (PosArguments != null) {
					foreach (Argument arg in PosArguments) { 
						// Type is undefined (was error 246)
						if (arg.Type == null)
							return;

						if (arg.Type.IsArray) {
							Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
							return;
						}
					}
				}
			
				if (NamedArguments == null)
					return;
			
				foreach (DictionaryEntry de in NamedArguments) {
					Argument arg  = (Argument) de.Value;

					// Type is undefined (was error 246)
					if (arg.Type == null)
						return;

					if (arg.Type.IsArray) {
						Report.Warning (3016, 1, Location, "Arrays as attribute arguments are not CLS-compliant");
						return;
					}
				}
			}
		}
        public void RenderActiveHiddenFields(List<UpdatePanel> updatePanels, HtmlTextWriter writer) {
            Debug.Assert(writer != null, "Should always have a writer");
            List<RegisteredHiddenField> entriesToRender = new List<RegisteredHiddenField>();
            ListDictionary uniqueEntries = new ListDictionary(StringComparer.Ordinal);

            // For each entry registered in the page, check and see which ones
            // came from controls within UpdatePanels that are going to be updated.
            Control lastControl = null;
            foreach (RegisteredHiddenField entry in ScriptHiddenFields) {
                Control child = entry.Control;

                bool isActive = ((lastControl != null) && (child == lastControl)) ||
                    IsControlRegistrationActive(updatePanels, child, true);

                if (isActive) {
                    lastControl = child;
                    if (!uniqueEntries.Contains(entry.Name)) {
                        entriesToRender.Add(entry);
                        uniqueEntries.Add(entry.Name, entry);
                    }
                }
            }

            foreach (RegisteredHiddenField activeRegistration in entriesToRender) {
                PageRequestManager.EncodeString(writer,
                    PageRequestManager.HiddenFieldToken,
                    activeRegistration.Name,
                    activeRegistration.InitialValue);
            }
        }
Esempio n. 23
0
        public string doMedian(DataSet ds)
        {
            if (ds.Tables[0].Rows.Count == 0)
                return null;

            DataTable dtRec = new DataTable();
            ListDictionary Diets = new ListDictionary();

            dtRec = ds.Tables[0];

            int k = 0;
            for (int j = 0; j < dtRec.Rows.Count; j++)
            {
                if (!Diets.Contains(dtRec.Rows[j]["C"].ToString()))
                {
                    Diets.Add(dtRec.Rows[j]["C"].ToString(), k);
                    k++;
                }
            }
            List<double>[] dDataAll = new List<double>[Diets.Count];
            List<double>[] dDataFemale = new List<double>[Diets.Count];
            List<double>[] dDataMale = new List<double>[Diets.Count];


            foreach (DictionaryEntry de in Diets)
            {
                dDataAll[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataMale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
                dDataFemale[Convert.ToInt32(de.Value.ToString())] = new List<double>();
            }

            for (int i = 0; i < dtRec.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dtRec.Rows[i]["WEIGHT"].ToString()))
                    continue;

                foreach (DictionaryEntry entry in Diets)
                {
                    if (entry.Key.ToString().Equals(dtRec.Rows[i]["C"].ToString()))
                    {
                        dDataAll[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        if (dtRec.Rows[i]["SEX"].ToString().Equals("M"))
                            dDataMale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));
                        else
                            dDataFemale[Convert.ToInt32(entry.Value.ToString())].Add(Convert.ToDouble(dtRec.Rows[i]["WEIGHT"].ToString()));

                        break;
                    }

                }
            }

            int meanLoop = 0;
            foreach (DictionaryEntry de in Diets)
            {
                engine.SetSymbol("ALL", engine.CreateNumericVector(dDataAll[meanLoop].ToArray()));
                var testResult = engine.Evaluate("median(ALL)").AsNumeric();
                sReturn += de.Key.ToString() + " All = " + testResult[0].ToString() + "\n";
                engine.SetSymbol("MALE", engine.CreateNumericVector(dDataMale[meanLoop].ToArray()));
                testResult = engine.Evaluate("median(MALE)").AsNumeric();
                sReturn += de.Key.ToString() + " Male = " + testResult[0].ToString() + "\n";
                engine.SetSymbol("FEMALE", engine.CreateNumericVector(dDataFemale[meanLoop].ToArray()));
                testResult = engine.Evaluate("median(FEMALE)").AsNumeric();
                sReturn += de.Key.ToString() + " Female = " + testResult[0].ToString() + "\n\n";
                meanLoop++;
            }

            return sReturn;
        }
        public void RenderActiveSubmitStatements(List<UpdatePanel> updatePanels, HtmlTextWriter writer) {
            Debug.Assert(writer != null, "Should always have a writer");
            List<RegisteredScript> entriesToRender = new List<RegisteredScript>();
            // no comparer needed because it will contain ScriptKeys which implement Equals
            ListDictionary uniqueEntries = new ListDictionary();

            // For each entry registered in the page, check and see which ones
            // came from controls within UpdatePanels that are going to be updated.
            Control lastControl = null;
            foreach (RegisteredScript entry in ScriptSubmitStatements) {
                Control child = entry.Control;

                bool isActive = ((lastControl != null) && (child == lastControl)) ||
                    IsControlRegistrationActive(updatePanels, child, true);

                if (isActive) {
                    lastControl = child;
                    ScriptKey scriptKey = new ScriptKey(entry.Type, entry.Key);
                    if (!uniqueEntries.Contains(scriptKey)) {
                        entriesToRender.Add(entry);
                        uniqueEntries.Add(scriptKey, entry);
                    }
                }
            }

            foreach (RegisteredScript activeRegistration in entriesToRender) {
                PageRequestManager.EncodeString(writer, PageRequestManager.OnSubmitToken, null, activeRegistration.Script);
            }
        }
Esempio n. 25
0
		//ExtendedProperties
		//	Per config
		//		Platform : Eg. Any CPU
		//		SolutionConfigurationPlatforms
		//
		SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor)
		{
			string headerComment;
			string version = GetSlnFileVersion (fileName, out headerComment);

			ListDictionary globals = null;
			SolutionFolder folder = null;
			SlnData data = null;
			List<Section> projectSections = null;
			List<string> lines = null;
			
			FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format);

			monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1);
			//Parse the .sln file
			using (StreamReader reader = new StreamReader(fileName)) {
				sol.FileName = fileName;
				sol.ConvertToFormat (projectFormat, false);
				folder = sol.RootFolder;
				sol.Version = "0.1"; //FIXME:
				data = new SlnData ();
				folder.ExtendedProperties [typeof (SlnFileFormat)] = data;
				data.VersionString = version;
				data.HeaderComment = headerComment;

				string s = null;
				projectSections = new List<Section> ();
				lines = new List<string> ();
				globals = new ListDictionary ();
				//Parse
				while (reader.Peek () >= 0) {
					s = GetNextLine (reader, lines).Trim ();

					if (String.Compare (s, "Global", true) == 0) {
						ParseGlobal (reader, lines, globals);
						continue;
					}

					if (s.StartsWith ("Project")) {
						Section sec = new Section ();
						projectSections.Add (sec);

						sec.Start = lines.Count - 1;

						int e = ReadUntil ("EndProject", reader, lines);
						sec.Count = (e < 0) ? 1 : (e - sec.Start + 1);

						continue;
					}
				}
			}

			monitor.BeginTask("Loading projects ..", projectSections.Count + 1);
			Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> ();
			List<SolutionItem> sortedList = new List<SolutionItem> ();
			foreach (Section sec in projectSections) {
				monitor.Step (1);
				Match match = ProjectRegex.Match (lines [sec.Start]);
				if (!match.Success) {
					LoggingService.LogDebug (GettextCatalog.GetString (
						"Invalid Project definition on line number #{0} in file '{1}'. Ignoring.",
						sec.Start + 1,
						fileName));

					continue;
				}

				try {
					// Valid guid?
					new Guid (match.Groups [1].Value);
				} catch (FormatException) {
					//Use default guid as projectGuid
					LoggingService.LogDebug (GettextCatalog.GetString (
						"Invalid Project type guid '{0}' on line #{1}. Ignoring.",
						match.Groups [1].Value,
						sec.Start + 1));
					continue;
				}

				string projTypeGuid = match.Groups [1].Value.ToUpper ();
				string projectName = match.Groups [2].Value;
				string projectPath = match.Groups [3].Value;
				string projectGuid = match.Groups [4].Value;

				if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) {
					//Solution folder
					SolutionFolder sfolder = new SolutionFolder ();
					sfolder.Name = projectName;
					MSBuildProjectService.InitializeItemHandler (sfolder);
					MSBuildProjectService.SetId (sfolder, projectGuid);

					List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2);
					DeserializeSolutionItem (sol, sfolder, projLines);
					
					foreach (string f in ReadFolderFiles (projLines))
						sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f));
					
					SlnData slnData = new SlnData ();
					slnData.Extra = projLines.ToArray ();
					sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData;

					items.Add (projectGuid, sfolder);
					sortedList.Add (sfolder);
					
					continue;
				}

				if (projectPath.StartsWith("http://")) {
					monitor.ReportWarning (GettextCatalog.GetString (
						"{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.",
						fileName, sec.Start + 1, projectPath));
					data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count));
					continue;
				}

				string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath);
				if (String.IsNullOrEmpty (path)) {
					monitor.ReportWarning (GettextCatalog.GetString (
						"Invalid project path found in {0} : {1}", fileName, projectPath));
					LoggingService.LogWarning (GettextCatalog.GetString (
						"Invalid project path found in {0} : {1}", fileName, projectPath));
					continue;
				}

				projectPath = Path.GetFullPath (path);
				
				SolutionEntityItem item = null;
				
				try {
					item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate {
						return MSBuildProjectService.LoadItem (monitor, projectPath, projTypeGuid, projectGuid);
					});
					
					if (item == null) {
						LoggingService.LogWarning (GettextCatalog.GetString (
							"Unknown project type guid '{0}' on line #{1}. Ignoring.",
							projTypeGuid,
							sec.Start + 1));
						monitor.ReportWarning (GettextCatalog.GetString (
							"{0}({1}): Unsupported or unrecognized project : '{2}'.", 
							fileName, sec.Start + 1, projectPath));
						continue;
					}

					MSBuildProjectHandler handler = (MSBuildProjectHandler) item.ItemHandler;
					List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2);
					DataItem it = GetSolutionItemData (projLines);
					handler.SlnProjectContent = projLines.ToArray ();
					handler.ReadSlnData (it);
					
				} catch (Exception e) {
					if (e is UnknownSolutionItemTypeException) {
						var name = ((UnknownSolutionItemTypeException)e).TypeName;
						LoggingService.LogWarning (!string.IsNullOrEmpty (name)?
							  string.Format ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name)
							: string.Format ("Could not load project '{0}' with unknown item type", projectPath));
						monitor.ReportWarning (!string.IsNullOrEmpty (name)?
							  GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name)
							: GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", projectPath));
					} else {
						LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e);
						monitor.ReportWarning (GettextCatalog.GetString (
							"Error while trying to load the project '{0}': {1}", projectPath, e.Message));
					}

					var uitem = new UnknownSolutionItem () {
						FileName = projectPath,
						LoadError = e.Message,
					};
					var h = new MSBuildHandler (projTypeGuid, projectGuid) {
						Item = uitem,
					};
					uitem.SetItemHandler (h);
					item = uitem;
				}
				
				if (!items.ContainsKey (projectGuid)) {
					items.Add (projectGuid, item);
					sortedList.Add (item);
					data.ItemsByGuid [projectGuid] = item;
				} else {
					monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null);
				}
			}
			monitor.EndTask ();

			if (globals != null && globals.Contains ("NestedProjects")) {
				LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor);
				globals.Remove ("NestedProjects");
			}

			//Add top level folders and projects to the main folder
			foreach (SolutionItem ce in sortedList) {
				if (ce.ParentFolder == null)
					folder.Items.Add (ce);
			}

			//FIXME: This can be just SolutionConfiguration also!
			if (globals != null) {
				if (globals.Contains ("SolutionConfigurationPlatforms")) {
					LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines,
						sol, monitor);
					globals.Remove ("SolutionConfigurationPlatforms");
				}

				if (globals.Contains ("ProjectConfigurationPlatforms")) {
					LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines,
						sol, monitor);
					globals.Remove ("ProjectConfigurationPlatforms");
				}

				if (globals.Contains ("MonoDevelopProperties")) {
					LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines,	sol, monitor);
					globals.Remove ("MonoDevelopProperties");
				}
				
				ArrayList toRemove = new ArrayList ();
				foreach (DictionaryEntry e in globals) {
					string name = (string) e.Key;
					if (name.StartsWith ("MonoDevelopProperties.")) {
						int i = name.IndexOf ('.');
						LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor);
						toRemove.Add (e.Key);
					}
				}
				foreach (object key in toRemove)
					globals.Remove (key);
			}

			//Save the global sections that we dont use
			List<string> globalLines = new List<string> ();
			foreach (Section sec in globals.Values)
				globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count));

			data.GlobalExtra = globalLines;
			monitor.EndTask ();
			return folder;
		}
Esempio n. 26
0
 private void ApplySourceDataTemplate(ReportType reportType, ListDictionary reportParameters, ReportTemplate template)
 {
     int fromElection = -1;
     if (reportParameters.Contains(PRN_ELECTION))
     {
         fromElection = _electionManager.SourceData.GetElectionIndex(
             (Election)reportParameters[PRN_ELECTION]);
     }
     var toElection = fromElection != -1 ?
         fromElection + 1 : _electionManager.SourceData.Elections.Length;
     fromElection = fromElection == -1 ? 0 : fromElection;
     var tables = new List<BaseTableHolder>();
     for (int i = fromElection; i < toElection; i++)
     {
         var election = _electionManager.SourceData.Elections[i];
         Table headerTable = null;
         Table footerTable = null;
         Table bodyTable = null;
         if (election.Protocol.FontType != FontType.Default)
             template.Font = election.Protocol.FontType;
         if (election.Protocol.FontSize > 0)
             template.FontSize = election.Protocol.FontSize;
         ProtocolText protocolTemplate = election.Protocol.GetProtocolTemplate(
             reportType == ReportType.ElectionProtocol);
         if (protocolTemplate == null)
             return;
         if (protocolTemplate.ProtocolLines.Length > 0)
         {
             var headers = new Dictionary<PageSection, List<BasePlainElement>>();
             foreach (PageSection section in Enum.GetValues(typeof(PageSection)))
             {
                 headers[section] = new List<BasePlainElement>();
             }
             try
             {
                 ApplyStandartTemplates(protocolTemplate, election, headers);
                 template.PageHeader = new BasePlainElement[headers[PageSection.PageHeader].Count];
                 headers[PageSection.PageHeader].CopyTo(template.PageHeader);
                 if (toElection - fromElection > 1)
                 {
                     template.Header = new BasePlainElement[0];
                     headerTable = new Table
                     {
                         Columns = new[]
                             {
                                 new ColDefinition
                                     {
                                         Width = 100,
                                         Align = null,
                                     },
                             },
                         Body = headers[PageSection.Header].ToArray(),
                     };
                     template.Footer = new BasePlainElement[0];
                     headers[PageSection.Footer].Add(
                         new LineClause
                         {
                             Columns = new[] { new LinePart { Text = "" } },
                             NewPage = true,
                             ResetPageNumber = true
                         });
                     footerTable = new Table
                     {
                         Columns = new[]
                             {
                                 new ColDefinition
                                     {
                                         Width = 100,
                                         Align = null,
                                     },
                             },
                         Body = headers[PageSection.Footer].ToArray(),
                     };
                 }
                 else
                 {
                     template.Header = new BasePlainElement[headers[PageSection.Header].Count];
                     headers[PageSection.Header].CopyTo(template.Header);
                     template.Footer = new BasePlainElement[headers[PageSection.Footer].Count];
                     headers[PageSection.Footer].CopyTo(template.Footer);
                 }
                 template.PageFooter = new BasePlainElement[headers[PageSection.PageFooter].Count];
                 headers[PageSection.PageFooter].CopyTo(template.PageFooter);
             }
             catch (Exception ex)
             {
                 _printingManager.Logger.LogError(Message.PrintingReportHeadersBuildFailed, ex);
             }
         }
         if (protocolTemplate.VoteLines != null && protocolTemplate.VoteLines.Length > 0)
         {
             try
             {
                 bodyTable = new Table
                 {
                     Columns = new[]
                     {
                         new ColDefinition {Width = election.Protocol.NumberWidth},
                         new ColDefinition {Width = election.Protocol.NameWidth},
                         new ColDefinition {Width = election.Protocol.ValueWidth},
                         new ColDefinition {Width = election.Protocol.TextValueWidth},
                     }
                 };
                 var tableEntry = CreateProtocolBodyTable(
                     protocolTemplate,
                     election,
                     reportType == ReportType.ElectionProtocol,
                     (bool)reportParameters[PRN_PRINT_RESULTS]);
                 bodyTable.Body = tableEntry.ToArray();
             }
             catch (Exception ex)
             {
                 _printingManager.Logger.LogError(Message.PrintingReportBodyBuildFailed, ex);
             }
         }
         if (headerTable != null)
         {
             tables.Add(headerTable);
         }
         if (bodyTable != null)
         {
             tables.Add(bodyTable);
         }
         if (footerTable != null)
         {
             tables.Add(footerTable);
         }
     }
     template.Body = tables.ToArray();
 }
Esempio n. 27
0
		/// <summary>
		/// Emit attribute for Attributable symbol
		/// </summary>
		public void Emit (ListDictionary allEmitted)
		{
			CustomAttributeBuilder cb = Resolve ();
			if (cb == null)
				return;

			AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
			if ((usage_attr.ValidOn & Target) == 0) {
				Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
					      "It is valid on `{1}' declarations only",
					GetSignatureForError (), GetValidTargets ());
				return;
			}

			try {
				foreach (Attributable target in targets)
					target.ApplyAttributeBuilder (this, cb, PredefinedAttributes.Get);
			} catch (Exception e) {
				Error_AttributeEmitError (e.Message);
				return;
			}

			if (!usage_attr.AllowMultiple && allEmitted != null) {
				if (allEmitted.Contains (this)) {
					ArrayList a = allEmitted [this] as ArrayList;
					if (a == null) {
						a = new ArrayList (2);
						allEmitted [this] = a;
					}
					a.Add (this);
				} else {
					allEmitted.Add (this, null);
				}
			}

			if (!RootContext.VerifyClsCompliance)
				return;

			// Here we are testing attribute arguments for array usage (error 3016)
			if (Owner.IsClsComplianceRequired ()) {
				if (PosArguments != null)
					PosArguments.CheckArrayAsAttribute (context.Compiler);
			
				if (NamedArguments == null)
					return;

				NamedArguments.CheckArrayAsAttribute (context.Compiler);
			}
		}
		void UpdateObject (WidgetParser parser, string topType, XmlElement objectElem, ITypeSymbol widgetClass, ITypeSymbol wrapperClass)
		{
			if (widgetClass.DeclaredAccessibility == Accessibility.Public)
				objectElem.RemoveAttribute ("internal");
			else
				objectElem.SetAttribute ("internal", "true");

			ListDictionary properties = new ListDictionary ();
			ListDictionary events = new ListDictionary ();
			
			parser.CollectMembers (widgetClass, true, topType, properties, events);
			if (wrapperClass != null)
				parser.CollectMembers (wrapperClass, false, null, properties, events);
			
			foreach (IPropertySymbol prop in properties.Values)
				MergeProperty (parser, objectElem, prop);
			
			foreach (IEventSymbol ev in events.Values)
				MergeEvent (parser, objectElem, ev);
			
			// Remove old properties
			ArrayList toDelete = new ArrayList ();
			foreach (XmlElement xprop in objectElem.SelectNodes ("itemgroups/itemgroup/property")) {
				if (!properties.Contains (xprop.GetAttribute ("name")))
					toDelete.Add (xprop);
			}
			
			// Remove old signals
			foreach (XmlElement xevent in objectElem.SelectNodes ("signals/itemgroup/signal")) {
				if (!events.Contains (xevent.GetAttribute ("name")))
					toDelete.Add (xevent);
			}
			
			foreach (XmlElement el in toDelete) {
				XmlElement pe = (XmlElement) el.ParentNode;
				pe.RemoveChild (el);
				if (pe.ChildNodes.Count == 0)
					pe.ParentNode.RemoveChild (pe);
			}
		}
Esempio n. 29
0
        public void Test01()
        {
            ListDictionary ld;

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

            ld = new ListDictionary();


            if (ld == null)
            {
                Assert.False(true, string.Format("Error, dictionary is null after default ctor"));
            }

            if (ld.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count = {0} after default ctor", ld.Count));
            }

            if (ld["key"] != null)
            {
                Assert.False(true, string.Format("Error, Item(some_key) returned non-null after default ctor"));
            }

            System.Collections.ICollection keys = ld.Keys;
            if (keys.Count != 0)
            {
                Assert.False(true, string.Format("Error, Keys contains {0} keys after default ctor", keys.Count));
            }

            System.Collections.ICollection values = ld.Values;
            if (values.Count != 0)
            {
                Assert.False(true, string.Format("Error, Values contains {0} items after default ctor", values.Count));
            }

            //
            // [] Add(string, string)
            //
            ld.Add("Name", "Value");
            if (ld.Count != 1)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 1", ld.Count));
            }
            if (String.Compare(ld["Name"].ToString(), "Value") != 0)
            {
                Assert.False(true, string.Format("Error, Item() returned unexpected value"));
            }

            //
            // [] Clear()
            //
            ld.Clear();
            if (ld.Count != 0)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 0 after Clear()", ld.Count));
            }
            if (ld["Name"] != null)
            {
                Assert.False(true, string.Format("Error, Item() returned non-null value after Clear()"));
            }

            //
            // [] elements not overriding Equals()
            //
            ld.Clear();
            Hashtable lbl = new Hashtable();
            Hashtable lbl1 = new Hashtable();
            ArrayList b = new ArrayList();
            ArrayList b1 = new ArrayList();
            ld.Add(lbl, b);
            ld.Add(lbl1, b1);
            if (ld.Count != 2)
            {
                Assert.False(true, string.Format("Error, Count returned {0} instead of 2", ld.Count));
            }
            if (!ld.Contains(lbl))
            {
                Assert.False(true, string.Format("Error, doesn't contain 1st special item"));
            }
            if (!ld.Contains(lbl1))
            {
                Assert.False(true, string.Format("Error, doesn't contain 2nd special item"));
            }
            if (ld.Values.Count != 2)
            {
                Assert.False(true, string.Format("Error, Values.Count returned {0} instead of 2", ld.Values.Count));
            }

            ld.Remove(lbl1);
            if (ld.Count != 1)
            {
                Assert.False(true, string.Format("Error, failed to remove item"));
            }
            if (ld.Contains(lbl1))
            {
                Assert.False(true, string.Format("Error, failed to remove special item"));
            }
        }
Esempio n. 30
0
        public void Test01()
        {
            IntlStrings intl;
            ListDictionary ld;

            // simple string values
            string[] values =
            {
                "",
                " ",
                "a",
                "aA",
                "text",
                "     SPaces",
                "1",
                "$%^#",
                "2222222222222222222222222",
                System.DateTime.Today.ToString(),
                Int32.MaxValue.ToString()
            };

            // keys for simple string values
            string[] keys =
            {
                "zero",
                "oNe",
                " ",
                "",
                "aa",
                "1",
                System.DateTime.Today.ToString(),
                "$%^#",
                Int32.MaxValue.ToString(),
                "     spaces",
                "2222222222222222222222222"
            };

            int cnt = 0;            // Count

            // initialize IntStrings
            intl = new IntlStrings();


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

            ld = new ListDictionary();

            // [] Remove() on empty dictionary
            //
            cnt = ld.Count;
            Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); });

            cnt = ld.Count;
            ld.Remove("some_string");
            if (ld.Count != cnt)
            {
                Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
            }

            cnt = ld.Count;
            ld.Remove(new Hashtable());
            if (ld.Count != cnt)
            {
                Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)"));
            }

            // [] add simple strings and Remove()
            //

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

            for (int i = 0; i < len; i++)
            {
                cnt = ld.Count;
                ld.Remove(keys[i]);
                if (ld.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                if (ld.Contains(keys[i]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            // Intl strings
            // [] Add Intl strings and Remove()
            //

            string[] intlValues = new string[len * 2];

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

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


            cnt = ld.Count;
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);
            }
            if (ld.Count != (cnt + len))
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len));
            }

            for (int i = 0; i < len; i++)
            {
                //
                cnt = ld.Count;
                ld.Remove(intlValues[i + len]);
                if (ld.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                if (ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            // [] Case sensitivity
            //

            string[] intlValuesLower = new string[len * 2];

            // fill array with unique strings
            //
            for (int i = 0; i < len * 2; i++)
            {
                intlValues[i] = intlValues[i].ToUpper();
            }

            for (int i = 0; i < len * 2; i++)
            {
                intlValuesLower[i] = intlValues[i].ToLower();
            }

            ld.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //
            for (int i = 0; i < len; i++)
            {
                // uppercase key

                cnt = ld.Count;
                ld.Remove(intlValues[i + len]);
                if (ld.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, returned: failed to remove item", i));
                }
                if (ld.Contains(intlValues[i + len]))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }

            ld.Clear();
            //
            // will use first half of array as values and second half as keys
            //
            for (int i = 0; i < len; i++)
            {
                ld.Add(intlValues[i + len], intlValues[i]);     // adding uppercase strings
            }

            //  LD is case-sensitive by default
            for (int i = 0; i < len; i++)
            {
                // lowercase key
                cnt = ld.Count;
                ld.Remove(intlValuesLower[i + len]);
                if (!caseInsensitive && ld.Count != cnt)
                {
                    Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i));
                }
            }


            //
            // [] Remove() on LD with case-insensitive comparer
            //
            ld = new ListDictionary(new InsensitiveComparer());

            len = values.Length;
            ld.Clear();
            string kk = "key";
            for (int i = 0; i < len; i++)
            {
                ld.Add(kk + i, values[i]);
            }
            if (ld.Count != len)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
            }

            for (int i = 0; i < len; i++)
            {
                cnt = ld.Count;
                ld.Remove(kk.ToUpper() + i);
                if (ld.Count != cnt - 1)
                {
                    Assert.False(true, string.Format("Error, failed to remove item", i));
                }
                if (ld.Contains(kk + i))
                {
                    Assert.False(true, string.Format("Error, removed wrong item", i));
                }
            }


            //
            //   [] Remove(null)
            //
            ld = new ListDictionary();
            cnt = ld.Count;
            if (ld.Count < len)
            {
                ld.Clear();
                for (int i = 0; i < len; i++)
                {
                    ld.Add(keys[i], values[i]);
                }
            }

            Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); });

            ld = new ListDictionary();

            ld.Clear();
            ArrayList b = new ArrayList();
            ArrayList b1 = new ArrayList();
            Hashtable lbl = new Hashtable();
            Hashtable lbl1 = new Hashtable();

            ld.Add(lbl, b);
            ld.Add(lbl1, b1);
            if (ld.Count != 2)
            {
                Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2));
            }

            cnt = ld.Count;
            ld.Remove(lbl);
            if (ld.Count != cnt - 1)
            {
                Assert.False(true, string.Format("Error, failed to remove special object"));
            }
            if (ld.Contains(lbl))
            {
                Assert.False(true, string.Format("Error, removed wrong special object"));
            }
        }
Esempio n. 31
0
 public void LoadParameters(ListDictionary reportParameters)
 {
     if (Parameters != null)
     {
         foreach (string parameter in Parameters)
         {
             if (reportParameters.Contains(parameter))
             {
                 s_parser.AddParameter(parameter, reportParameters[parameter]);
             }
         }
     }
 }