BinarySearch() public method

public BinarySearch ( Object value ) : int
value Object
return int
Example #1
0
        public Form1()
        {
            InitializeComponent();
            ArrayList folderyMuzyczne, folderyNiemuzyczne, utworyGrane;

            folderyMuzyczne = new ArrayList();
            folderyNiemuzyczne = new ArrayList();
            utworyGrane = new ArrayList();

            StreamReader czytnik = new StreamReader("test.txt");
            string linia = czytnik.ReadLine();
            string[] dane = linia.Split(';');

            Song piosenka = new Song(dane[0], dane[1], dane[2]);

            int numer = utworyGrane.BinarySearch(piosenka);
            if (numer < 0)
            {
                utworyGrane.Add(piosenka);
            }
            else
            {
                piosenka = (Song)utworyGrane[numer];
                piosenka.nadania++;
                utworyGrane[numer] = piosenka;
            }
        }
Example #2
0
 private void SaveButton_Click(object sender, EventArgs e)
 {
     if (SubjectBox.Text.Length == 0)
     {
         MessageBox.Show("Cannot proceed with empty name");
         return;
     }
     ArrayList list = new ArrayList((string[])Host.SubjectList.DataSource);
     list.Sort();
     int id = list.BinarySearch(SubjectBox.Text);
     if (id >= 0)
     {
         MessageBox.Show("Subject with that name already exists!");
         return;
     }
     id = ~id;
     list.Insert(id, SubjectBox.Text);
     string[] n = new string[list.Count];
     list.CopyTo(n);
     Host.SubjectBox2.AutoCompleteCustomSource.Add(SubjectBox.Text);
     Host.SubjectList.DataSource = n;
     Host.RenewSubjectList();
     Host.SubjectList.SelectedItem = SubjectBox.Text;
     this.Close();
 }
Example #3
0
        // in the middle
        private string findElement()
        {
            string winner;
            ArrayList al = new ArrayList();
            LinkedList<int> ll = new LinkedList<int>();
            al = insertInHeadAL(al);
            ll = insertInHeadLL(ll);

            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            al.BinarySearch(al.Count / 2);
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            Console.WriteLine("\n\n=================================================================================");
            Console.WriteLine("Time to find element in the middle of ArrayList with {0} elements: {1}", al.Count, ts);

            stopWatch.Reset();
            stopWatch.Start();
            ll.Find(ll.Count / 2);
            stopWatch.Stop();
            TimeSpan ts2 = stopWatch.Elapsed;

            Console.WriteLine("Time to find element in the middle of LinkedList with {0} elements: {1}", ll.Count, ts2);
            if (ts > ts2)
            {
                Console.WriteLine("\tLinkedList is quicker!");
                return winner = "LinkedList";
            }
            else
            {
                Console.WriteLine("\tArrayList is quicker!");
                return winner = "ArrayList";
            }
        }
        // ----------------------------------------
        /// <summary>
        /// Finding all ancestors (all boxes box) with given box type in Ferda Archive tree structure
        /// </summary>
        /// <param name="Box">Box in archive, for which function searches the ancestors</param>
        /// <param name="ID">type of searched boxes (string identifier)</param>
        /// <returns></returns>
        public static IBoxModule[] ListAncestBoxesWithID(IBoxModule Box, string ID)
        {
            ArrayList MyBoxes = new ArrayList();
            IBoxModule[] Ancestors = Box.ConnectionsFrom().ToArray();
            foreach (IBoxModule b in Ancestors)
            {
                if (b.MadeInCreator.Identifier == ID)  // this ancestor has desired type
                    MyBoxes.Add(b);
                else  // ancestor doesn't have desired type. Further we searche among it's ancestors (recurse)
                {
                    IBoxModule[] b_ancestors = ListAncestBoxesWithID(b, ID);  // recurse
                    foreach (IBoxModule bb in b_ancestors)
                        MyBoxes.Add(bb);
                }
            }
            // eliminating the duplicites
            MyBoxes.Sort();
            IBoxModule[] SortedBoxes = (IBoxModule[])MyBoxes.ToArray(typeof(IBoxModule));
            ArrayList MyUniqueBoxes = new ArrayList();
            foreach (IBoxModule bbb in SortedBoxes)
            {
                if (MyUniqueBoxes.BinarySearch(bbb) < 0)
                    MyUniqueBoxes.Add(bbb);
            }

            IBoxModule[] resultArray = (IBoxModule[])MyUniqueBoxes.ToArray(typeof(IBoxModule));
            return resultArray;
        }
Example #5
0
        public void arrayList()
        {
            ArrayList a = new ArrayList() { "a" ,"b" };

            foreach (var item in (IEnumerable)a)
                Console.WriteLine(item.ToString());

            Console.WriteLine(a.BinarySearch("b"));
        }
Example #6
0
        static void Main(string[] args)
        {
            Console.WriteLine("Basic Array List Testing:");
            ArrayList al = new ArrayList();
            al.Add("Hello");
            al.Add("World");
            al.Add(5);
            al.Add(new FileStream("deleteme", FileMode.Create));

            Console.WriteLine("The array has " + al.Count + " items");

            foreach (object o in al)
            {
                Console.WriteLine(o.ToString());
            }

            Console.WriteLine("\nRemove, Insert and Sort Testing:");
            al = new ArrayList();
            al.Add("Hello");
            al.Add("World");
            al.Add("this");
            al.Add("is");
            al.Add("a");
            al.Add("test");

            Console.WriteLine("\nBefore:");
            foreach (object s in al)
                Console.WriteLine(s.ToString());


            al.Remove("test");
            al.Insert(4, "not");

            al.Sort();

            Console.WriteLine("\nAfter:");
            foreach (object s in al)
                Console.WriteLine(s.ToString());

            al.Sort(new reverseSorter());
            Console.WriteLine("\nReversed:");
            foreach (object s in al)
                Console.WriteLine(s.ToString());

            al.Reverse();
            Console.WriteLine("\nReversed again, different method:");
            foreach (object s in al)
                Console.WriteLine(s.ToString());

            Console.WriteLine("\nBinary Search Example:");
            al = new ArrayList();
            al.AddRange(new string[] { "Hello", "World", "this", "is", "a", "test" });
            foreach (object s in al)
                Console.Write(s + " ");
            Console.WriteLine("\n\"this\" is at index: " + al.BinarySearch("this"));
        }
Example #7
0
        public void TestStandardArrayList()
        {
            //
            // Construct array list.
            //
            ArrayList list = new ArrayList();
            // Add items to the lists.
            for (int ii = 0; ii < strHeroes.Length; ++ii)
                list.Add(strHeroes[ii]);

            // Verify items added to list.
            Assert.Equal(strHeroes.Length, list.Count);

            //
            // []  Use BinarySearch to find selected items.
            //
            // Search and verify selected items.
            for (int ii = 0; ii < strFindHeroes.Length; ++ii)
            {
                // Locate item.
                int ndx = list.BinarySearch(strFindHeroes[ii]);
                Assert.True(ndx >= 0);

                // Verify item.
                Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii]));
            }

            // Return Value;
            // The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number,
            // which is the bitwise complement of the index of the next element.

            list = new ArrayList();
            for (int i = 0; i < 100; i++)
                list.Add(i);
            list.Sort();

            Assert.Equal(100, ~list.BinarySearch(150));

            //[]null - should return -1
            Assert.Equal(-1, list.BinarySearch(null));

            //[]we can add null as a value and then search it!!!
            list.Add(null);
            list.Sort();
            Assert.Equal(0, list.BinarySearch(null));

            //[]duplicate values, always return the first one
            list = new ArrayList();
            for (int i = 0; i < 100; i++)
                list.Add(5);

            list.Sort();
            //remember this is BinarySeearch
            Assert.Equal(49, list.BinarySearch(5));
        }
        static void Main(string[] args)
        {
            ArrayList al = new ArrayList();
            al.Add("Paris");
            al.Add("Ottowa");
            al.AddRange(new string[] { "Rome", "Tokyo", "Tunis", "Canberra" });

            Console.WriteLine("Count:    {0}", al.Count);
            Console.WriteLine("Capacity: {0}", al.Capacity);

            Console.WriteLine("Print values using foreach");
            PrintValues(al);
            Console.WriteLine("Print values using IEnumerator");
            PrintValuesByEnumerator(al);

            // Get second item in list as string
            string str = (string)al[1];    // need to cast, would also unbox if stored type was value type
            Console.WriteLine("al[1] = {0}", str);

            // Get first three items
            ArrayList firstThree = al.GetRange(0, 3);
            PrintValues(firstThree);

            // Remove next two
            al.RemoveRange(3, 2);
            PrintValues(al);

            // Get, insert and remove
            object itemOne = al[1];
            al.Insert(1, "Moscow");
            al.RemoveAt(2);
            PrintValues(al);

            // Sort
            al.Sort();
            PrintValues(al);

            // Search
            int targetIndex = al.BinarySearch("Moscow");
            Console.WriteLine("Index of Moscow: {0}", targetIndex);

            // Trim capacity
            al.TrimToSize();
            Console.WriteLine("Count:    {0}", al.Count);
            Console.WriteLine("Capacity: {0}", al.Capacity);

            // Creates a new ArrayList with five elements and initialize each element with a value.
            ArrayList al2 = ArrayList.Repeat("Boston", 5);   // static method
            PrintValues(al2);
        }
 private void SaveButton_Click(object sender, EventArgs e)
 {
     if ((string)CurrentSubject == SubjectBox.Text)
     {
         this.Close();
         return;
     }
     //string[] list = (string[])Host.SubjectList.DataSource;
     ArrayList list = new ArrayList((string[])Host.SubjectList.DataSource);
     int id = list.BinarySearch(CurrentSubject);
     list.RemoveAt(id);
     id = list.BinarySearch(SubjectBox.Text);
     if (id >= 0)
     {
         MessageBox.Show("Subject with that name already exists!");
         return;
     }
     id = ~id;
     list.Insert(id, SubjectBox.Text);
     string[] n = new string[list.Count];
     list.CopyTo(n);
     Host.SubjectList.DataSource = n;
     //change all subjects with that name
     foreach (DataRow row in Host.MainDataTable.Rows)
     {
         if (row["Subject"].ToString() == (string)CurrentSubject)
         {
             row["Subject"] = SubjectBox.Text;
         }
     }
     Host.SubjectBox2.AutoCompleteCustomSource.Remove((string)CurrentSubject);
     Host.SubjectBox2.AutoCompleteCustomSource.Add(SubjectBox.Text);
     Host.RenewSubjectList();
     Host.SubjectList.SelectedItem = SubjectBox.Text;
     this.Close();
 }
Example #10
0
        static void Main(string[] args)
        {
            ArrayList l = new ArrayList();
            l.Add("Gateau");
            l.Insert(0, "patate");
            //l.RemoveAt(0);

            Console.WriteLine(l.Contains("Gateau"));

            foreach (object o in l)
                Console.WriteLine(o);

            l.BinarySearch("Gateau");

        }
Example #11
0
        void IIdentifierCreationService.ValidateIdentifier(Activity activity, string identifier)
        {
            if (identifier == null)
                throw new ArgumentNullException("identifier");
            if (activity == null)
                throw new ArgumentNullException("activity");

            if (activity.Name.ToLower(CultureInfo.InvariantCulture).Equals(identifier.ToLower(CultureInfo.InvariantCulture)))
                return;

            ArrayList identifiers = new ArrayList();
            Activity rootActivity = GetRootActivity(activity);
            identifiers.AddRange(GetIdentifiersInCompositeActivity(rootActivity as CompositeActivity));
            identifiers.Sort();
            if (identifiers.BinarySearch(identifier.ToLower(CultureInfo.InvariantCulture), StringComparer.OrdinalIgnoreCase) >= 0)
                throw new ArgumentException(string.Format("Duplicate Component Identifier {0}", identifier));
        }
Example #12
0
        public TopicInfoArray Intersect(ArrayList topicInfoArrayToIntersect)
        {
            TopicInfoArray answer = new TopicInfoArray();
            this.Array.Sort(null);
            topicInfoArrayToIntersect.Sort(null);

            foreach(TopicVersionInfo topicInfo in this.Array)
            {
                if(topicInfoArrayToIntersect.BinarySearch(topicInfo) >= 0)
                {
                    if( answer.Array.BinarySearch(topicInfo) < 0 )
                    {
                        answer.Add(topicInfo);
                    }
                }
            }

            return answer;
        }
        static void Sample4()
        {
            ArrayList myList = new ArrayList();

            myList.Add(new MyObject() { ID = 4 });
            myList.Add(new MyObject() { ID = 1 });
            myList.Add(new MyObject() { ID = 5 });
            myList.Add(new MyObject() { ID = 3 });
            myList.Add(new MyObject() { ID = 2 });

            myList.Sort();
            int foundIndex = myList.BinarySearch(new MyObject() { ID = 4 });

            if (foundIndex >= 0)
            {
                Debug.WriteLine(((MyObject)myList[foundIndex]).ID.ToString());
            }
            else
            {
                Debug.WriteLine("Element not found");
            }
        }
Example #14
0
        /// <summary>
        /// Counter signatures should all contain a reference to the parent signature SignatureValue element
        /// </summary>
        /// <returns>If the function returns true the check was OK</returns>
        public virtual bool CheckCounterSignaturesReference()
        {
            CounterSignatureCollection counterSignatureCollection;
            XadesSignedXml counterSignature;
            string referenceUri;
            ArrayList parentSignatureValueChain;
            bool referenceToParentSignatureFound;
            bool retVal;

            retVal = true;
            parentSignatureValueChain = new ArrayList();
            parentSignatureValueChain.Add("#" + this.signatureValueId);
            counterSignatureCollection = this.XadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection;
            for (int counterSignatureCounter = 0; (retVal == true) && (counterSignatureCounter < counterSignatureCollection.Count); counterSignatureCounter++)
            {
                counterSignature = counterSignatureCollection[counterSignatureCounter];
                referenceToParentSignatureFound = false;
                for (int referenceCounter = 0; referenceToParentSignatureFound == false && (referenceCounter < counterSignature.SignedInfo.References.Count); referenceCounter++)
                {
                    referenceUri = ((Reference)counterSignature.SignedInfo.References[referenceCounter]).Uri;
                    if (parentSignatureValueChain.BinarySearch(referenceUri) >= 0)
                    {
                        referenceToParentSignatureFound = true;
                    }
                    parentSignatureValueChain.Add("#" + counterSignature.SignatureValueId);
                    parentSignatureValueChain.Sort();
                }
                retVal = referenceToParentSignatureFound;
            }
            if (retVal == false)
            {
                throw new CryptographicException("CheckCounterSignaturesReference() failed on at least one counter signature");
            }
            retVal = true;

            return retVal;
        }
Example #15
0
		public void BinarySearch_Null ()
		{
			ArrayList al = new ArrayList ();
			al.Add (this);
			Assert.AreEqual (-1, al.BinarySearch (null), "null");
		}
Example #16
0
		public void BinarySearch_CountOverflow ()
		{
			ArrayList al = new ArrayList ();
			al.Add (this);
			al.BinarySearch (1, Int32.MaxValue, this, null);
		}
Example #17
0
		public void BinarySearch_IndexOverflow ()
		{
			ArrayList al = new ArrayList ();
			al.Add (this);
			al.BinarySearch (Int32.MaxValue, 1, this, null);
		}
Example #18
0
		public void TestBinarySearch ()
		{
			{
				bool errorThrown = false;
				try {
					ArrayList al1 = new ArrayList ();
					String [] s1 = { "This", "is", "a", "test" };
					al1.AddRange (s1);
					al1.BinarySearch (42);
				} catch (InvalidOperationException) {
					// this is what .NET throws
					errorThrown = true;
				} catch (ArgumentException) {
					// this is what the docs say it should throw
					errorThrown = true;
				} catch (Exception e) {
					Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
				}
				Assert.IsTrue (errorThrown, "search-for-wrong-type error not thrown");
			}

			{
				char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
				ArrayList al1 = new ArrayList (arr);
				Assert.IsTrue (al1.BinarySearch ('c') >= 3, "couldn't find elem #1");
				Assert.IsTrue (al1.BinarySearch ('c') < 6, "couldn't find elem #2");
			}
			{
				char [] arr = { 'a', 'b', 'b', 'd', 'd', 'd', 'e', 'e' };
				ArrayList al1 = new ArrayList (arr);
				Assert.AreEqual (-4, al1.BinarySearch ('c'), "couldn't find next-higher elem");
			}
			{
				char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
				ArrayList al1 = new ArrayList (arr);
				Assert.AreEqual (-9, al1.BinarySearch ('e'), "couldn't find end");
			}

		}
Example #19
0
		public void TestAddRange ()
		{
			{
				bool errorThrown = false;
				try {
					ArrayList al1 =
						ArrayList.FixedSize (new ArrayList ());
					String [] s1 = { "Hi!" };
					al1.AddRange (s1);
				} catch (NotSupportedException) {
					errorThrown = true;
				} catch (Exception e) {
					Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
				}
				Assert.IsTrue (errorThrown, "add to fixed size error not thrown");
			}
			{
				bool errorThrown = false;
				try {
					ArrayList al1 =
						ArrayList.ReadOnly (new ArrayList ());
					String [] s1 = { "Hi!" };
					al1.AddRange (s1);
				} catch (NotSupportedException) {
					errorThrown = true;
				} catch (Exception e) {
					Assert.Fail ("Incorrect exception thrown at 2: " + e.ToString ());
				}
				Assert.IsTrue (errorThrown, "add to read only error not thrown");
			}
			{
				bool errorThrown = false;
				try {
					ArrayList al1 = new ArrayList ();
					al1.AddRange (null);
				} catch (ArgumentNullException) {
					errorThrown = true;
				} catch (Exception e) {
					Assert.Fail ("Incorrect exception thrown at 3: " + e.ToString ());
				}
				Assert.IsTrue (errorThrown, "add to read only error not thrown");
			}

			{
				ArrayList a1 = new ArrayList ();
				Assert.AreEqual (0, a1.Count, "ArrayList should start empty");
				char [] coll = { 'a', 'b', 'c' };
				a1.AddRange (coll);
				Assert.AreEqual (3, a1.Count, "ArrayList has wrong elements");
				a1.AddRange (coll);
				Assert.AreEqual (6, a1.Count, "ArrayList has wrong elements");
			}

			{
				ArrayList list = new ArrayList ();

				for (int i = 0; i < 100; i++) {
					list.Add (1);
				}

				Assert.AreEqual (49, list.BinarySearch (1), "BinarySearch off-by-one bug");
			}
		}
Example #20
0
		public void BinarySearch3_EmptyList ()
		{
			Comparer comparer = new Comparer ();
			ArrayList list = new ArrayList ();
			Assert.AreEqual (-1, list.BinarySearch (0, 0, 0, comparer), "BinarySearch");
			// bug 77030 - the comparer isn't called for an empty array/list
			Assert.IsTrue (!comparer.Called, "Called");
		}
Example #21
0
		public void BinarySearch1_EmptyList ()
		{
			ArrayList list = new ArrayList ();
			Assert.AreEqual (-1, list.BinarySearch (0), "BinarySearch");
		}
Example #22
0
		private void SetCachedString(ArrayList cache, int sortedItemCount, int shift, int mask, string value)
		{
			if (value == null)
			{
				this.Value &= ~(mask << shift);
			}
			else
			{
				// first, look for a predefined class name.  binary searching is faster
				int index = cache.BinarySearch(0, sortedItemCount, value, null);
				if (index < 0)
				{
					index = cache.IndexOf(value, sortedItemCount);
					if (index < 0)
					{
						index = cache.Add(value);
					}
				}
					
				this.Value = ((index + 1) << shift) | (this.Value & ~(mask << shift));
			}
		}
Example #23
0
        //string textToFind, Scope scope, SearchFunctions searchFunctions, FindReplaceOptions options)
        public static void RunFind()
        {
            m_foundLocations.Clear();

            switch (searchFunctions)
            {
                case SearchFunctions.AllFunctions:
                    ArrayList openFunctions = new ArrayList(Project.Instance.Functions.Count);

                    // Process open functions first
                    for (int tabCounter = 0; tabCounter < Controller.Instance.MainForm.UcFunctions.tabStrip1.Tabs.Count; tabCounter++)
                    {
                        FunctionInfo function = Controller.Instance.MainForm.UcFunctions.GetFunctionScreenByTabIndex(tabCounter).CurrentFunction;
                        openFunctions.Add(function.Name);
                        SyntaxEditor editor = Controller.Instance.MainForm.UcFunctions.GetFunctionScreenByTabIndex(tabCounter).syntaxEditor1;
                        FindInText(editor.Text, Options.FindText, scope, function, function.IsTemplateFunction, Options);
                    }
                    openFunctions.Sort();
                    // Process remaining functions
                    for (int functionCounter = 0; functionCounter < Project.Instance.Functions.Count; functionCounter++)
                    {
                        FunctionInfo function = Project.Instance.Functions[functionCounter];

                        // Don't add functions that have already been added as open functions
                        if (openFunctions.BinarySearch(function.Name) < 0)
                        {
                            FindInText(function.Body, Options.FindText, scope, function, function.IsTemplateFunction, Options);
                        }
                    }
                    break;
                case SearchFunctions.CurrentFunction:
                    if (Controller.Instance.MainForm.UcFunctions != null &&
                        Controller.Instance.MainForm.UcFunctions.tabStrip1.Tabs.Count > 0)
                    {
                        FunctionInfo function = Controller.Instance.MainForm.UcFunctions.GetCurrentlyDisplayedFunctionPage().CurrentFunction;
                        SyntaxEditor editor = Controller.Instance.MainForm.UcFunctions.GetCurrentlyDisplayedFunctionPage().syntaxEditor1;
                        FindInText(editor.Text, Options.FindText, scope, function, function.IsTemplateFunction, Options, editor.SelectedView.Selection.StartOffset, false);
                    }
                    break;
                case SearchFunctions.OpenFunctions:
                    if (Controller.Instance.MainForm.UcFunctions != null &&
                            Controller.Instance.MainForm.UcFunctions.tabStrip1.Tabs.Count > 0)
                    {
                        for (int tabCounter = 0; tabCounter < Controller.Instance.MainForm.UcFunctions.tabStrip1.Tabs.Count; tabCounter++)
                        {
                            FunctionInfo function = Controller.Instance.MainForm.UcFunctions.GetFunctionScreenByTabIndex(tabCounter).CurrentFunction;
                            SyntaxEditor editor = Controller.Instance.MainForm.UcFunctions.GetFunctionScreenByTabIndex(tabCounter).syntaxEditor1;
                            FindInText(editor.Text, Options.FindText, scope, function, function.IsTemplateFunction, Options);
                        }
                    }
                    break;
                default:
                    throw new NotImplementedException("Not coded yet.");
            }
        }
Example #24
0
        /// <summary>
        /// Check if CertificateValues match CertificateRefs
        /// </summary>
        /// <returns>If the function returns true the check was OK</returns>
        public virtual bool CheckCertificateValuesMatchCertificateRefs()
        {
            SHA1Managed sha1Managed;
            UnsignedSignatureProperties unsignedSignatureProperties;
            ArrayList certDigests;
            byte[] certDigest;
            int index;
            bool retVal;

            //TODO: Similar test should be done for XML based (Other) certificates, but as the check needed is not known, there is no implementation
            retVal = true;
            unsignedSignatureProperties = this.XadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties;
            if ((unsignedSignatureProperties.CompleteCertificateRefs != null) && (unsignedSignatureProperties.CompleteCertificateRefs.CertRefs != null) &&
                (unsignedSignatureProperties.CertificateValues != null))
            {
                certDigests = new ArrayList();
                foreach (Cert cert in unsignedSignatureProperties.CompleteCertificateRefs.CertRefs.CertCollection)
                {
                    certDigests.Add(Convert.ToBase64String(cert.CertDigest.DigestValue));
                }
                certDigests.Sort();
                foreach (EncapsulatedX509Certificate encapsulatedX509Certificate in unsignedSignatureProperties.CertificateValues.EncapsulatedX509CertificateCollection)
                {
                    sha1Managed = new SHA1Managed();
                    certDigest = sha1Managed.ComputeHash(encapsulatedX509Certificate.PkiData);
                    index = certDigests.BinarySearch(Convert.ToBase64String(certDigest));
                    if (index >= 0)
                    {
                        certDigests.RemoveAt(index);
                    }
                }
                if (certDigests.Count != 0)
                {
                    throw new CryptographicException("Not all CertificateRefs correspond to CertificateValues");
                }
            }

            return retVal;
        }
Example #25
0
        private bool CheckHashDataInfosOfSigAndRefsTimeStamp(TimeStamp timeStamp)
        {
            UnsignedSignatureProperties unsignedSignatureProperties;
            bool signatureValueHashDataInfoFound = false;
            bool allSignatureTimeStampHashDataInfosFound = false;
            bool completeCertificateRefsHashDataInfoFound = false;
            bool completeRevocationRefsHashDataInfoFound = false;

            ArrayList signatureTimeStampIds = new ArrayList();

            bool retVal = true;

            unsignedSignatureProperties = this.XadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties;

            foreach (TimeStamp signatureTimeStamp in unsignedSignatureProperties.SignatureTimeStampCollection)
            {
                signatureTimeStampIds.Add("#" + signatureTimeStamp.EncapsulatedTimeStamp.Id);
            }
            signatureTimeStampIds.Sort();
            foreach (HashDataInfo hashDataInfo in timeStamp.HashDataInfoCollection)
            {
                if (hashDataInfo.UriAttribute == "#" + this.signatureValueId)
                {
                    signatureValueHashDataInfoFound = true;
                }
                int signatureTimeStampIdIndex = signatureTimeStampIds.BinarySearch(hashDataInfo.UriAttribute);
                if (signatureTimeStampIdIndex >= 0)
                {
                    signatureTimeStampIds.RemoveAt(signatureTimeStampIdIndex);
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.CompleteCertificateRefs.Id)
                {
                    completeCertificateRefsHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.CompleteRevocationRefs.Id)
                {
                    completeRevocationRefsHashDataInfoFound = true;
                }
            }
            if (signatureTimeStampIds.Count == 0)
            {
                allSignatureTimeStampHashDataInfosFound = true;
            }
            retVal = signatureValueHashDataInfoFound && allSignatureTimeStampHashDataInfosFound && completeCertificateRefsHashDataInfoFound && completeRevocationRefsHashDataInfoFound;

            return retVal;
        }
Example #26
0
        private bool CheckHashDataInfosOfArchiveTimeStamp(TimeStamp timeStamp)
        {
            UnsignedSignatureProperties unsignedSignatureProperties;
            SignedProperties signedProperties;

            bool allReferenceHashDataInfosFound = false;
            bool signedInfoHashDataInfoFound = false;
            bool signedPropertiesHashDataInfoFound = false;
            bool signatureValueHashDataInfoFound = false;
            bool allSignatureTimeStampHashDataInfosFound = false;
            bool completeCertificateRefsHashDataInfoFound = false;
            bool completeRevocationRefsHashDataInfoFound = false;
            bool certificatesValuesHashDataInfoFound = false;
            bool revocationValuesHashDataInfoFound = false;
            bool allSigAndRefsTimeStampHashDataInfosFound = false;
            bool allRefsOnlyTimeStampHashDataInfosFound = false;
            bool allArchiveTimeStampHashDataInfosFound = false;
            bool allOlderArchiveTimeStampsFound = false;

            ArrayList referenceIds = new ArrayList();
            ArrayList signatureTimeStampIds = new ArrayList();
            ArrayList sigAndRefsTimeStampIds = new ArrayList();
            ArrayList refsOnlyTimeStampIds = new ArrayList();
            ArrayList archiveTimeStampIds = new ArrayList();

            bool retVal = true;

            unsignedSignatureProperties = this.XadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties;
            signedProperties = this.XadesObject.QualifyingProperties.SignedProperties;

            foreach (Reference reference in this.Signature.SignedInfo.References)
            {
                if (reference.Uri != "#" + signedProperties.Id)
                {
                    referenceIds.Add(reference.Uri);
                }
            }
            referenceIds.Sort();
            foreach (TimeStamp signatureTimeStamp in unsignedSignatureProperties.SignatureTimeStampCollection)
            {
                signatureTimeStampIds.Add("#" + signatureTimeStamp.EncapsulatedTimeStamp.Id);
            }
            signatureTimeStampIds.Sort();
            foreach (TimeStamp sigAndRefsTimeStamp in unsignedSignatureProperties.SigAndRefsTimeStampCollection)
            {
                sigAndRefsTimeStampIds.Add("#" + sigAndRefsTimeStamp.EncapsulatedTimeStamp.Id);
            }
            sigAndRefsTimeStampIds.Sort();
            foreach (TimeStamp refsOnlyTimeStamp in unsignedSignatureProperties.RefsOnlyTimeStampCollection)
            {
                refsOnlyTimeStampIds.Add("#" + refsOnlyTimeStamp.EncapsulatedTimeStamp.Id);
            }
            refsOnlyTimeStampIds.Sort();
            allOlderArchiveTimeStampsFound = false;
            for (int archiveTimeStampCounter = 0; !allOlderArchiveTimeStampsFound && (archiveTimeStampCounter < unsignedSignatureProperties.ArchiveTimeStampCollection.Count); archiveTimeStampCounter++)
            {
                TimeStamp archiveTimeStamp = unsignedSignatureProperties.ArchiveTimeStampCollection[archiveTimeStampCounter];
                if (archiveTimeStamp.EncapsulatedTimeStamp.Id == timeStamp.EncapsulatedTimeStamp.Id)
                {
                    allOlderArchiveTimeStampsFound = true;
                }
                else
                {
                    archiveTimeStampIds.Add("#" + archiveTimeStamp.EncapsulatedTimeStamp.Id);
                }
            }

            archiveTimeStampIds.Sort();
            foreach (HashDataInfo hashDataInfo in timeStamp.HashDataInfoCollection)
            {
                int index = referenceIds.BinarySearch(hashDataInfo.UriAttribute);
                if (index >= 0)
                {
                    referenceIds.RemoveAt(index);
                }
                if (hashDataInfo.UriAttribute == "#" + this.signedInfoIdBuffer)
                {
                    signedInfoHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + signedProperties.Id)
                {
                    signedPropertiesHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + this.signatureValueId)
                {
                    signatureValueHashDataInfoFound = true;
                }
                index = signatureTimeStampIds.BinarySearch(hashDataInfo.UriAttribute);
                if (index >= 0)
                {
                    signatureTimeStampIds.RemoveAt(index);
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.CompleteCertificateRefs.Id)
                {
                    completeCertificateRefsHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.CompleteRevocationRefs.Id)
                {
                    completeRevocationRefsHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.CertificateValues.Id)
                {
                    certificatesValuesHashDataInfoFound = true;
                }
                if (hashDataInfo.UriAttribute == "#" + unsignedSignatureProperties.RevocationValues.Id)
                {
                    revocationValuesHashDataInfoFound = true;
                }
                index = sigAndRefsTimeStampIds.BinarySearch(hashDataInfo.UriAttribute);
                if (index >= 0)
                {
                    sigAndRefsTimeStampIds.RemoveAt(index);
                }
                index = refsOnlyTimeStampIds.BinarySearch(hashDataInfo.UriAttribute);
                if (index >= 0)
                {
                    refsOnlyTimeStampIds.RemoveAt(index);
                }
                index = archiveTimeStampIds.BinarySearch(hashDataInfo.UriAttribute);
                if (index >= 0)
                {
                    archiveTimeStampIds.RemoveAt(index);
                }
            }
            if (referenceIds.Count == 0)
            {
                allReferenceHashDataInfosFound = true;
            }
            if (signatureTimeStampIds.Count == 0)
            {
                allSignatureTimeStampHashDataInfosFound = true;
            }
            if (sigAndRefsTimeStampIds.Count == 0)
            {
                allSigAndRefsTimeStampHashDataInfosFound = true;
            }
            if (refsOnlyTimeStampIds.Count == 0)
            {
                allRefsOnlyTimeStampHashDataInfosFound = true;
            }
            if (archiveTimeStampIds.Count == 0)
            {
                allArchiveTimeStampHashDataInfosFound = true;
            }

            retVal = allReferenceHashDataInfosFound && signedInfoHashDataInfoFound && signedPropertiesHashDataInfoFound &&
                signatureValueHashDataInfoFound && allSignatureTimeStampHashDataInfosFound && completeCertificateRefsHashDataInfoFound &&
                completeRevocationRefsHashDataInfoFound && certificatesValuesHashDataInfoFound && revocationValuesHashDataInfoFound &&
                allSigAndRefsTimeStampHashDataInfosFound && allRefsOnlyTimeStampHashDataInfosFound && allArchiveTimeStampHashDataInfosFound;

            return retVal;
        }
		private void btnDone_Click(object sender, EventArgs e)
		{
			if (_HasChangedUsers )
			{
				BPCompanyGroups BPCompanyGroups = new BPCompanyGroups();
			
				if (_HasChangedUsers )
				{
					DSCompanyGroups = BPCompanyGroups.SelectCompanyGroupPermissionsByCompanyGroupID(CompanyGroupID);
					ArrayList perms = new ArrayList(PermList);
					perms.Sort();

					//Remove Duplicates
					if (perms.Count > 1)
					{
						int iLast,iCurrent;
						iLast = (int) perms[0];
						for (int i=1; i<perms.Count; i++)
						{
							iCurrent = (int) perms[i];

							if (iCurrent == iLast)
							{
								perms.RemoveAt(i);
							}
							iLast = iCurrent;
						}
					}

					int searchIndex;
					foreach (BECompanyGroups.tbl_CompanyGroupPermissionsRow groupPerm in DSCompanyGroups.tbl_CompanyGroupPermissions)
					{
						searchIndex = perms.BinarySearch(groupPerm.CompanyPermissionID);
						if (searchIndex < 0)
							//if (Array.BinarySearch(groupPerm.PermissionID))
						{
							//Not Found
							groupPerm.Delete();
						}
						else
						{
							perms.RemoveAt(searchIndex);
						}
					}

					foreach (int i in perms)
					{
						BECompanyGroups.tbl_CompanyGroupPermissionsRow groupPerm;
						groupPerm = DSCompanyGroups.tbl_CompanyGroupPermissions.FindByCompanyGroupIDCompanyPermissionID(CompanyGroupID, i);
						if(groupPerm == null)
						{
							groupPerm = DSCompanyGroups.tbl_CompanyGroupPermissions.Newtbl_CompanyGroupPermissionsRow();
							groupPerm.CompanyGroupID = CompanyGroupID;
							groupPerm.CompanyPermissionID = i;
							groupPerm.CompanyGroupPermissionValue = 2;
							DSCompanyGroups.tbl_CompanyGroupPermissions.Addtbl_CompanyGroupPermissionsRow(groupPerm);
						}

						//The first value for a permission should always be 1.
						groupPerm.CompanyGroupPermissionValue = 2;
					}
				}

				BPCompanyGroups.UpdateCompanyGroupPermissions(DSCompanyGroups);
				DSCompanyGroups = BPCompanyGroups.SelectCompanyGroupPermissionsByCompanyGroupID(CompanyGroupID);
				dgPermissions.DataBind();
			}
			pnlAssign.Visible = false;
			pnlPermissions.Visible = true;

			tab1.Attributes["class"] = "";
			tab2.Attributes["class"] = "current";
		}
Example #28
0
        /// <summary>
        /// Check if RevocationValues match RevocationRefs
        /// </summary>
        /// <returns>If the function returns true the check was OK</returns>
        public virtual bool CheckRevocationValuesMatchRevocationRefs()
        {
            SHA1Managed sha1Managed;
            UnsignedSignatureProperties unsignedSignatureProperties;
            ArrayList crlDigests;
            byte[] crlDigest;
            int index;
            bool retVal;

            //TODO: Similar test should be done for XML based (Other) revocation information and OCSP responses, but to keep the library independent of these technologies, this test is left to appliactions using the library
            retVal = true;
            unsignedSignatureProperties = this.XadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties;
            if ((unsignedSignatureProperties.CompleteRevocationRefs != null) && (unsignedSignatureProperties.CompleteRevocationRefs.CRLRefs != null) &&
                (unsignedSignatureProperties.RevocationValues != null))
            {
                crlDigests = new ArrayList();
                foreach (CRLRef crlRef in unsignedSignatureProperties.CompleteRevocationRefs.CRLRefs.CRLRefCollection)
                {
                    crlDigests.Add(Convert.ToBase64String(crlRef.CertDigest.DigestValue));
                }
                crlDigests.Sort();
                foreach (CRLValue crlValue in unsignedSignatureProperties.RevocationValues.CRLValues.CRLValueCollection)
                {
                    sha1Managed = new SHA1Managed();
                    crlDigest = sha1Managed.ComputeHash(crlValue.PkiData);
                    index = crlDigests.BinarySearch(Convert.ToBase64String(crlDigest));
                    if (index >= 0)
                    {
                        crlDigests.RemoveAt(index);
                    }
                }
                if (crlDigests.Count != 0)
                {
                    throw new CryptographicException("Not all RevocationRefs correspond to RevocationValues");
                }
            }

            return retVal;
        }
 internal static string GenerateUniqueIdentifier(IServiceProvider serviceProvider, string baseIdentifier, string[] existingNames)
 {
     CodeDomProvider provider = null;
     if (serviceProvider != null)
     {
         provider = serviceProvider.GetService(typeof(CodeDomProvider)) as CodeDomProvider;
         if (provider == null)
         {
             IdentifierCreationService service = serviceProvider.GetService(typeof(IIdentifierCreationService)) as IdentifierCreationService;
             if (service != null)
             {
                 provider = service.Provider;
             }
         }
     }
     if (provider != null)
     {
         baseIdentifier = provider.CreateValidIdentifier(baseIdentifier);
     }
     baseIdentifier = baseIdentifier.Replace('.', '_');
     baseIdentifier = baseIdentifier.Replace('/', '_');
     baseIdentifier = baseIdentifier.Replace('(', '_');
     baseIdentifier = baseIdentifier.Replace(')', '_');
     baseIdentifier = baseIdentifier.Replace(" ", "");
     ArrayList list = new ArrayList(existingNames);
     int num = 1;
     string str = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { baseIdentifier, num });
     list.Sort();
     while (list.BinarySearch(str.ToLowerInvariant(), StringComparer.OrdinalIgnoreCase) >= 0)
     {
         str = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { baseIdentifier, num });
         num++;
     }
     return str;
 }
        private void DeleteEmptyColumns( int beginingBalanceRowIndex, int endingBalanceRowIndex, ArrayList instantColumnIndex, ArrayList durationColumnIndex )
        {
            //Handle instance columns
            ArrayList emptyColumns = new ArrayList();
            ArrayList cashBalances = new ArrayList();
            if( beginingBalanceRowIndex != -1 )
            {
                foreach( Cell c in ( this.Rows[ beginingBalanceRowIndex ] as InstanceReportRow ).Cells )
                {
                    if( c.NumericAmount != 0 )
                        cashBalances.Add( c.NumericAmount );
                }
            }
            if( endingBalanceRowIndex != -1 )
            {
                foreach( Cell c in ( this.Rows[ endingBalanceRowIndex ] as InstanceReportRow ).Cells )
                {
                    if( c.NumericAmount != 0 )
                        cashBalances.Add( c.NumericAmount );
                }
            }

            cashBalances.Sort();

            foreach( int colIndex in instantColumnIndex )
            {
                bool empty = true;
                foreach( InstanceReportRow irr in this.Rows )
                {
                    Cell c = irr.Cells[ colIndex ] as Cell;
                    //					if( c.IsNumeric )
                    //					{
                    decimal amount = c.NumericAmount;
                    if( amount != 0 && cashBalances.BinarySearch( amount ) < 0 )
                    {
                        empty = false;
                        break;
                    }
                    //					}
                    //					else
                    //					{
                    //						if( !string.IsNullOrEmpty( c.NonNumericTextHeader ) )
                    //						{
                    //							empty = false;
                    //							break;
                    //						}
                    //					}
                }

                if( empty )
                {
                    emptyColumns.Add( colIndex );
                }
            }

            //Handle duration columns

            foreach( int colIndex in durationColumnIndex )
            {
                bool hasCashData = false;
                foreach( InstanceReportRow irr in this.Rows )
                {
                    Cell c = irr.Cells[ colIndex ] as Cell;
                    //					if( c.IsNumeric )
                    //					{
                    decimal amount = c.NumericAmount;
                    if( amount != 0 && irr.Label.ToLower().IndexOf( "cash" ) >= 0 )
                    {
                        hasCashData = true;
                        break;
                    }
                    //					}
                    //					else
                    //					{
                    //						if( !string.IsNullOrEmpty( c.NonNumericTextHeader ) )
                    //						{
                    //							hasCashData = true;
                    //							break;
                    //						}
                    //					}
                }

                if( !hasCashData )
                {
                    emptyColumns.Add( colIndex );
                }
            }

            //Remove empty columns
            emptyColumns.Sort();

            for( int index = emptyColumns.Count - 1; index >= 0; index-- )
            {
                int colIndex = (int)emptyColumns[ index ];

                //delete columns
                this.Columns.RemoveAt( colIndex );

                //delete cells
                foreach( InstanceReportRow irr in this.Rows )
                {
                    irr.Cells.RemoveAt( colIndex );
                }
            }
        }