Пример #1
0
        /// <summary>
        ///    <para>Gets or sets the delegate for the specified key.</para>
        /// </summary>
        public Delegate this[object key]
        {
            get
            {
                ListEntry e = null;
                if (_parent == null || _parent.CanRaiseEventsInternal)
                {
                    e = Find(key);
                }

                if (e != null)
                {
                    return e.Handler;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                ListEntry e = Find(key);
                if (e != null)
                {
                    e.Handler = value;
                }
                else
                {
                    _head = new ListEntry(key, value, _head);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Gets or sets the <see cref="System.Delegate"/> with the specified key.
        /// </summary>
        /// <param name="key">An delegate to find in the list.</param>
        /// <returns>
        /// The delegate for the specified key, or null if a delegate does not exist.
        /// </returns>
        public Delegate this[string key]
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    ListEntry entry = this.Find(key);

                    if (entry != null)
                    {
                        return entry.Handler;
                    }
                }

                return null;
            }

            set
            {
                if (!string.IsNullOrWhiteSpace(key))
                {
                    ListEntry entry = this.Find(key);
                    if (entry != null)
                    {
                        entry.Handler = value;
                    }
                    else
                    {
                        this.head = new ListEntry(key, value, this.head);
                    }
                }
            }
        }
Пример #3
0
 /// <summary>
 ///    <para>[To be supplied.]</para>
 /// </summary>
 public void AddHandler(object key, Delegate value)
 {
     ListEntry e = Find(key);
     if (e != null)
     {
         e.Handler = Delegate.Combine(e.Handler, value);
     }
     else
     {
         _head = new ListEntry(key, value, _head);
     }
 }
Пример #4
0
    public void WriteDictToRow(Dictionary<string,string> dict, bool bUpdateRow)
    {
        try
        {
            AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

            ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
            ListFeed listFeed = service.Query(listQuery);

            if (!bUpdateRow)
            {
                ListEntry row = new ListEntry();

                foreach (KeyValuePair<string, string> pair in dict)
                {
                    row.Elements.Add(new ListEntry.Custom() { LocalName = pair.Key, Value = pair.Value } );
                }

                service.Insert(listFeed, row);
            }
            else
            {
                ListEntry row = (ListEntry)listFeed.Entries[listFeed.Entries.Count-1];

                foreach (ListEntry.Custom element in row.Elements)
                {
                    foreach (KeyValuePair<string, string> pair in dict)
                    {
                        if (element.LocalName == pair.Key)
                        {
                            element.Value = pair.Value;
                        }
                    }
                }

                row.Update();
            }
        }
        catch (WebException e)
        {
            Debug.LogWarning("WriteDictToRow WebException: " + e);
        }
        catch (Exception e)
        {
            Debug.LogWarning("WriteDictToRow Exception: " + e);
        }
    }
Пример #5
0
        public ListEntry[] ListEntries(int first, int num)
        {
            if (first < 0 || first + num > this.dict.Count)
            {
                throw new ArgumentOutOfRangeException("Invalid range!");
            }

            ListEntry[] list = new ListEntry[num];

            for (int i = first; i <= first + num - 1; i++)
            {
                ListEntry entry = this.sorted[i];
                list[i - first] = entry;
            }

            return list;
        }
 public override bool StorePanelContents()
 {
     for (int i = 0; i < fileTypesListBox.Items.Count; i++)
     {
         bool      newChecked = fileTypesListBox.GetItemChecked(i);
         ListEntry entry      = (ListEntry)fileTypesListBox.Items[i];
         if (entry.InitiallyChecked != newChecked)
         {
             if (newChecked)
             {
                 RegisterFiletypesCommand.RegisterToSharpDevelop(entry.Association);
             }
             else
             {
                 RegisterFiletypesCommand.UnRegisterFiletype(entry.Association.Extension);
             }
         }
     }
     return(true);
 }
        private bool HandleEventSwitch(IItem item, ListEntry listEntry)
        {
            Switch e = item as Switch;

            if (e == null)
            {
                return(false);
            }

            var itemSwitch = GetObjectBy(e.ObjectId) as Switch;

            if (itemSwitch != null)
            {
                itemSwitch.Parse(listEntry.Arguments);
                itemSwitch.UpdateTitle();
                itemSwitch.UpdateSubTitle();
            }

            return(true);
        }
        private bool HandleEventLocomotive(IItem item, ListEntry listEntry)
        {
            Locomotive e = item as Locomotive;

            if (e == null)
            {
                return(false);
            }

            var itemLocomotive = GetObjectBy(e.ObjectId) as Locomotive;

            if (itemLocomotive != null)
            {
                itemLocomotive.Parse(listEntry.Arguments);
                itemLocomotive.UpdateTitle();
                itemLocomotive.UpdateSubTitle();
            }

            return(true);
        }
Пример #9
0
        public ListEntry Insert(ListFeed listFeed, ListEntry listEntry)
        {
            Debug.WriteLine("Try ListInsert");

            return(Service.Insert(listFeed, listEntry));

            /*
             * ListEntry retVal = null;
             * try
             * {
             *  retVal = Service.Insert(listFeed, listEntry);
             * }
             * catch (Google.GData.Client.GDataRequestException ex)
             * {
             *  Debug.WriteLine("ListEntry.Insert fail:" + ex.ToString());
             *  return null;
             * }
             *
             * return retVal;*/
        }
        /// <summary>
        /// Deletes the first row found using nameID
        /// </summary>
        /// <param name="worksheet"></param>
        /// <param name="rowNumber">Row number to be removed</param>
        public static void DeleteRowData(this GS2U_Worksheet worksheet, int rowNumber)
        {
            if (worksheet.GetWorksheetSize().y < rowNumber)
            {
                Debug.Log("Worksheet is smaller than rowNumber to edit");
                return;
            }

            if (rowNumber > 0)
            {
                ListFeed feed = worksheet.LoadListFeedWorksheet();

                ListEntry row = (ListEntry)feed.Entries[rowNumber - 1];

                row.Delete();
            }
            else
            {
                Debug.Log("Invalid Row Number");
            }
        }
Пример #11
0
        void AppendIn(LinkedList <ListEntry> list, ICCUpdatable target, bool paused)
        {
            var listElement = new ListEntry
            {
                Target            = target,
                Paused            = paused,
                MarkedForDeletion = false
            };

            list.AddLast(listElement);

            // update hash entry for quicker access
            var hashElement = new HashUpdateEntry
            {
                Target = target,
                List   = list,
                Entry  = listElement
            };

            hashForUpdates.Add(target, hashElement);
        }
        /// <summary>
        /// Creates a new SpreadsheetsService with the user's specified
        /// authentication credentials and runs all of the Spreadsheets
        /// operations above.
        /// </summary>
        private static void RunSample()
        {
            SpreadsheetsService service = new SpreadsheetsService("exampleCo-exampleApp-1");

            service.setUserCredentials(userName, password);

            // Demonstrate printing all spreadsheets and worksheets.
            PrintAllSpreadsheetsAndWorksheets(service);

            // Demonstrate retrieving the list feed for a single worksheet,
            // with the rows (ordered by position) reversed.
            int            userChoice = GetUserWorksheetChoice();
            WorksheetEntry entry      = allWorksheets[userChoice] as WorksheetEntry;

            RetrieveListFeed(service, entry, true);

            // Demonstrate sending a structured query.
            Console.Write("Enter a structured query to execute: ");
            string queryText = Console.ReadLine();

            StructuredQuery(service, entry, queryText);

            // Demonstrate inserting a new row in the worksheet.
            ListEntry insertedEntry = InsertRow(service, entry);

            // Demonstrate updating the inserted row.
            UpdateRow(service, insertedEntry);

            // Demonstrate deleting the entry.
            insertedEntry.Delete();

            // Demonstrate retrieving a cell feed for a worksheet.
            RetrieveCellFeed(service, entry);

            // Demonstrate a cell range query.
            CellRangeQuery(service, entry);

            // Demonstrate updating a single cell.
            UpdateCell(service, entry);
        }
Пример #13
0
        public void InsertSMSIntoSpreadsheet(WorksheetEntry worksheet, Sms sms)
        {
            // Loop through rows in worksheet
            if (worksheet != null)
            {
                // Define the URL to request the list feed of the worksheet.
                AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

                // Fetch the list feed of the worksheet.
                ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
                ListFeed  listFeed  = _service.Query(listQuery);


                // Create a local representation of the new row.
                ListEntry row = new ListEntry();
                row.Elements.Add(new ListEntry.Custom()
                {
                    LocalName = "number", Value = sms.PhoneNumber
                });
                row.Elements.Add(new ListEntry.Custom()
                {
                    LocalName = "message", Value = sms.Body
                });
                row.Elements.Add(new ListEntry.Custom()
                {
                    LocalName = "date", Value = sms.Date.ToString()
                });
                if (sms.Address != null)
                {
                    row.Elements.Add(new ListEntry.Custom()
                    {
                        LocalName = "address",
                        Value     = sms.Address.ToString()
                    });
                }

                // Send the new row to the API for insertion.
                _service.Insert(listFeed, row);
            }
        }
Пример #14
0
        public void PatchAdd(ListEntry newEntry, string entryIDWithoutPrefix, string groupID = "MODDED")
        {
            //If there's no entry to patch, just add this entry.
            if (!entries.ContainsKey(entryIDWithoutPrefix))
            {
                //Set ID to be the non-prefix version
                if (useGroups)
                {
                    newEntry.values[0] = groupID;
                    newEntry.values[1] = entryIDWithoutPrefix;
                }
                else
                {
                    newEntry.values[0] = entryIDWithoutPrefix;
                }

                //Add the entry
                AddEntry(newEntry);
            }
            else
            {
                //Get Item Entry to add to
                ListEntry patchEntry = entries[entryIDWithoutPrefix];

                int start = 1;
                if (useGroups)
                {
                    start++;
                }

                //Add elements to existing entry
                for (int i = start; i < newEntry.values.Length; i++)
                {
                    patchEntry.values[i] += newEntry.values[i];
                }

                entries[entryIDWithoutPrefix] = patchEntry;
            }
        }
Пример #15
0
 public void AddEntry(ListEntry entry)
 {
     try {
         if (useGroups || shopList)
         {
             //Add entry to entry dictionary
             entries[entry.ID] = entry;
             //entriesByRow[entry.rowNumber] = entry;
         }
         else if (animList)
         {
             animEntries[entry.rowNumber] = entry;
         }
         else
         {
             entries[entry.group] = entry;
             //entriesByRow[entry.rowNumber] = entry;
         }
     } catch (System.Exception e) {
         Debug.LogError(e);
     }
 }
Пример #16
0
        private DomainProperty GetListProperty(RuntimeType objectType, ListEntry entry)
        {
            var itemEntry   = entry.ItemEntry;
            var elementType = GetType(objectType, itemEntry);

            string propertyName = entry.Name.FirstToUpper();

            Type propertyType = GetListType(elementType);

            var propertyInfo = objectType.AddProperty(propertyName, propertyType);

            propertyInfo.AddAttribute(new PropertyRepositoryAttribute());

            var valueEntry = itemEntry as ValueEntry;

            if (valueEntry != null)
            {
                AttachAttributes(propertyInfo, valueEntry);
            }

            return(DomainProperty.Register(propertyName, propertyType, objectType, (o, p) => { return propertyType.CreateInstance(); }, PropertyChangedMode.Definite, elementType));
        }
Пример #17
0
        private void AutoShout_Callback()
        {
            TownCrierEntry tce = GetRandomEntry();

            if (Utility.RandomDouble() > 0.5 || tce == null)              //only spout off about macroers 1/2 the time
            {
                ListEntry le = TCCS.GetRandomEntry();
                if (le != null)
                {
                    tce = new TownCrierEntry(le.Lines, TimeSpan.FromMinutes(1), Serial.MinusOne);
                }
            }

            if (tce == null)
            {
                if (m_AutoShoutTimer != null)
                {
                    m_AutoShoutTimer.Stop();
                }

                m_AutoShoutTimer = null;
            }
            else if (m_NewsTimer == null)
            {
                m_NewsTimer = Timer.DelayCall(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(3.0), new TimerStateCallback(ShoutNews_Callback), new object[] { tce, 0 });

                // pla: 12/08/06
                // changed to show a different mesasge in a yellow hue for player messages
                Mobile m = World.FindMobile(tce.Poster);
                if (m != null && m.AccessLevel == AccessLevel.Player)
                {
                    PublicOverheadMessage(MessageType.Regular, 0x36, true, Utility.RandomBool() == true ? "A good citizen proclaims!" : "On behalf of a good citizen!");
                }
                else
                {
                    PublicOverheadMessage(MessageType.Regular, 0x3B2, 502976);                   // Hear ye! Hear ye!
                }
            }
        }
Пример #18
0
        public void TestWithOneEntry()
        {
            var testName = "TestUser";
            var testNumbers = new SortedSet<string> { "+359899777235", "+359888777777" };
            ListEntry[] expected = new ListEntry[] { new ListEntry { Name = testName, Numbers = testNumbers } };

            var testPhoneDatabase = new PhonebookRepository();
            testPhoneDatabase.AddPhone("TestUser", new string[] { "+359899777235" });
            testPhoneDatabase.AddPhone("testuser", new string[] { "+359888777777" });

            var actual = testPhoneDatabase.ListEntries(0, 1);

            Assert.AreEqual(expected.Count(), actual.Count());

            IEnumerator e1 = expected.GetEnumerator();
            IEnumerator e2 = actual.GetEnumerator();

            while (e1.MoveNext() && e2.MoveNext())
            {
                Assert.AreEqual(e1.Current.ToString(), e2.Current.ToString());
            }
        }
Пример #19
0
        public void PatchFromFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new System.IO.FileNotFoundException("File not found at " + path);
            }
            string[] lines = File.ReadAllLines(path);

            for (int i = 0; i < lines.Length; i++)
            {
                List <string> seperatedLines = new List <string>();
                StringUtil.SplitCSV(lines[i], seperatedLines);

                //Create entry
                ListEntry entry = new ListEntry()
                {
                    values = seperatedLines.ToArray()
                };

                string entryIDPrefix        = ATCSVUtil.GetPrefix(entry.ID);
                string entryIDWithoutPrefix = ATCSVUtil.GetWithoutPrefix(entry.ID);

                //Patch adding
                if (entryIDPrefix == patchAddPrefix)
                {
                    PatchAdd(entry, entryIDWithoutPrefix);
                }
                else
                //Patch over
                if (entryIDPrefix == patchOverPrefix)
                {
                    PatchOver(entry, entryIDWithoutPrefix);
                }
                else
                {
                }
            }
        }
Пример #20
0
        public bool AddPhone(string name, IEnumerable<string> nums)
        {
            string nameToLower = name.ToLowerInvariant();
            ListEntry entry;
            bool isNewEntry = !this.dict.TryGetValue(nameToLower, out entry);
            if (isNewEntry)
            {
                entry = new ListEntry();
                entry.Name = name;
                entry.Numbers = new SortedSet<string>();
                this.dict.Add(nameToLower, entry);

                this.sorted.Add(entry);
            }

            foreach (var num in nums)
            {
                this.multidict.Add(num, entry);
            }

            entry.Numbers.UnionWith(nums);
            return isNewEntry;
        }
        void _termTableListBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            if (_termTableListBox.Items.Count > 0 && e.Index >= 0)
            {
                ListEntry entry = (ListEntry)_termTableListBox.Items[e.Index];

                if (entry != null)
                {
                    Color color;

                    if (entry.IsValid)
                    {
                        color = e.ForeColor;
                    }
                    else
                    {
                        color = Color.FromKnownColor(KnownColor.GrayText);
                    }
                    entry.DrawAbbreviatedPath(e.Font, color, e.Bounds, e.Graphics);
                }
            }
        }
Пример #22
0
    //================================================================================
    // Logic
    //================================================================================

    /// <summary>
    ///     Adds a player to the Leaderboard.
    /// </summary>
    /// <param name="player">GamePlayer to add</param>
    public void AddPlayer(GamePlayer player)
    {
        Transform listEntryTransform = Instantiate(listEntryPrefab);
        ListEntry listEntry          = listEntryTransform.GetComponent <ListEntry>();

        listEntry.setPlayerName(player.playerName);
        listEntry.setPlayerTime(player.getLifeTime());
        listEntryTransform.SetParent(playerList);
        // Add as first element inside visible list
        listEntryTransform.SetAsFirstSibling();

        // listEntryTransform gets instantiated with size (100,100,100) although prefab has size of (1,1,1) ???!!!!!
        listEntryTransform.localScale    = new Vector3(1f, 1f, 1f);
        listEntryTransform.localPosition = listEntryTransform.localPosition - new Vector3(0, 0, listEntryTransform.localPosition.z);

        ListEntry[] listEntries  = playerList.GetComponentsInChildren <ListEntry>();
        int         tableEntries = listEntries.Length;

        for (int i = 0; i < tableEntries; i++)
        {
            listEntries[i].setRank(i + 1);
        }
    }
Пример #23
0
        public float getContact(int index)
        {
            ArrayList list = new ArrayList();

            if (!SensorsDictionary.TryGetValue(SensorTypes.ContactSensorArray, out list))
            {
                throw new NoInstanceException();
            }

            if (list.Count == 0 || list.Count < index + 1)
            {
                throw new IndexOutOfRangeException();
            }

            ListEntry le    = (ListEntry)list[index];
            float     value = Defines.INVALID_FLOAT;

            if (le.Adapter.AdapterType == AdapterTypes.ContactSensorArrayAdapter)
            {
                ContactSensorArrayAdapter adapter = (ContactSensorArrayAdapter)le.Adapter;
                if (adapter.get(le.BeginOffset))
                {
                    value = 1;
                }
                else
                {
                    value = 0;
                }
            }

            if (value == Defines.INVALID_FLOAT)
            {
                throw new InvalidValueException("Cannot get true value.");
            }

            return(value);
        }
Пример #24
0
    /// <summary>
    /// Instantiates a new scoreboard list entry
    /// </summary>
    private void AddListItem(ListEntry entry, bool shouldHighlight)
    {
        Transform       listItem  = Instantiate <Transform>(_entryTemplate, _container);
        TextMeshProUGUI rank      = listItem.GetChild(0).GetComponent <TextMeshProUGUI>();
        TextMeshProUGUI name      = listItem.GetChild(1).GetComponent <TextMeshProUGUI>();
        TextMeshProUGUI time      = listItem.GetChild(2).GetComponent <TextMeshProUGUI>();
        TextMeshProUGUI attempts  = listItem.GetChild(3).GetComponent <TextMeshProUGUI>();
        TextMeshProUGUI timeswaps = listItem.GetChild(4).GetComponent <TextMeshProUGUI>();

        rank.text      = String.Format("#{0:D6}", entry.rank);
        name.text      = entry.name;
        time.text      = GameTimer.FormatTime(entry.time);
        attempts.text  = entry.attempts.ToString();
        timeswaps.text = entry.timeswaps.ToString();

        if (shouldHighlight)
        {
            rank.color      = _userHighlight;
            name.color      = _userHighlight;
            time.color      = _userHighlight;
            attempts.color  = _userHighlight;
            timeswaps.color = _userHighlight;
        }
    }
Пример #25
0
        public float[] getContact()
        {
            ArrayList list = new ArrayList();

            if (!SensorsDictionary.TryGetValue(SensorTypes.ContactSensorArray, out list))
            {
                throw new NoInstanceException();
            }

            float[] ret = new float[list.Count];
            for (int index = 0; index < list.Count; index++)
            {
                ListEntry le = (ListEntry)list[index];
                ret[index] = Defines.INVALID_FLOAT;

                if (le.Adapter.AdapterType == AdapterTypes.ContactSensorArrayAdapter)
                {
                    ContactSensorArrayAdapter adapter = (ContactSensorArrayAdapter)le.Adapter;
                    if (adapter.get(le.BeginOffset))
                    {
                        ret[index] = 1;
                    }
                    else
                    {
                        ret[index] = 0;
                    }
                }

                if (ret[index] == Defines.INVALID_FLOAT)
                {
                    throw new InvalidValueException("Cannot get true value.");
                }
            }

            return(ret);
        }
        /// <summary>
        /// Sets the list view on the List tab
        /// </summary>
        /// <param name="feed">The feed providing the data</param>
        void SetListListView(ListFeed feed)
        {
            this.listListView.Items.Clear();
            this.listListView.Columns.Clear();
            this.editUriTable.Clear();

            this.listListView.Columns.Add("", 80, HorizontalAlignment.Center);

            AtomEntryCollection entries = feed.Entries;

            for (int i = 0; i < entries.Count; i++)
            {
                ListEntry entry = entries[i] as ListEntry;

                ListViewItem item = new ListViewItem();
                item.Text = (i + 1).ToString();

                if (entry != null)
                {
                    ListEntry.CustomElementCollection elements = entry.Elements;
                    for (int j = 0; j < elements.Count; j++)
                    {
                        item.SubItems.Add(elements[j].Value);

                        if (listListView.Columns.Count - 2 < j)
                        {
                            listListView.Columns.Add(elements[j].LocalName, 80, HorizontalAlignment.Center);
                        }
                    }


                    listListView.Items.Add(item);
                    this.editUriTable.Add(item.Text, entry);
                }
            }
        }
Пример #27
0
 public static void MakeAllEntriesCriminal()
 {
     try             //safety net
     {
         if (TCCS.TheList != null)
         {
             if (TCCS.TheList.Count > 0)
             {
                 for (int i = 0; i < TCCS.TheList.Count; i++)
                 {
                     ListEntry entry = (ListEntry)TCCS.TheList[i];
                     if (entry.Type == ListEntryType.PJUM && entry.Enabled)
                     {
                         if (entry.Mobile != null)
                         {
                             entry.Mobile.Criminal = true;
                         }
                     }
                 }
             }
         }
     }
     catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); }
 }
Пример #28
0
        private void createServerCertifiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateServerDialog dialog = new CreateServerDialog();

              if (dialog.ShowDialog() == DialogResult.OK)
              {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "Save Server Certificate";
            saveDialog.CheckPathExists = true;
            saveDialog.Filter = Files.CertificateFileFilter;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
              ServerCertificate certificate = new ServerCertificate(dialog.FullName);
              certificate.CreateSelfSignature();

              SignatureRequest request = new SignatureRequest(dialog.FullName, string.Empty, string.Empty);
              Secure<SignatureRequest> signedRequest = new Secure<SignatureRequest>(request, CaCertificate, certificate);

              CertificateAuthorityEntry entry = new CertificateAuthorityEntry(signedRequest);
              entry.Sign(CaCertificate, DateTime.Now, dialog.ValidUntil);
              certificate.AddSignature(entry.Response.Value.Signature);

              string entryFileName = DataPath(entry.Certificate.Id.ToString() + ".pi-ca-entry");
              entry.Save(DataPath(entryFileName));

              ListEntry listEntry = new ListEntry(entryFileName, entry, CaCertificate);
              Entries.Add(listEntry);
              this.entryListView.Items.Add(listEntry.CreateItem(CaCertificate));

              certificate.Save(saveDialog.FileName);
            }
              }
        }
Пример #29
0
        private void editDetails(ListEntry le)
        {
            string _details = null;
            if (le.Value != null)
                _details = le.Value;

            if (InputBox(Application.ProductName, "Edit Details: ", ref _details) == System.Windows.Forms.DialogResult.OK)
            {
                le.Value = _details;
                _changed = true;
            }
        }
Пример #30
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     this.head = null;
 }
Пример #31
0
 /// <summary>
 ///    <para>[To be supplied.]</para>
 /// </summary>
 public void Dispose()
 {
     _head = null;
 }
Пример #32
0
        public void TestWithSeveralEntries()
        {
            var testNameOne = "TestUserOne";
            var testNameTwo = "TestUserTwo";
            var testNumbersOne = new SortedSet<string> { "+359899777235" };
            var testNumbersTwo = new SortedSet<string> { "+359888777777" };

            ListEntry listEntryOne = new ListEntry { Name = testNameOne, Numbers = testNumbersOne };
            ListEntry listEntryTwo = new ListEntry { Name = testNameTwo, Numbers = testNumbersTwo };
            ListEntry[] expected = new ListEntry[] { listEntryOne, listEntryTwo };

            var testPhoneDatabase = new PhonebookRepository();
            testPhoneDatabase.AddPhone("TestUserOne", new string[] { "+359899777235" });
            testPhoneDatabase.AddPhone("TestUserTwo", new string[] { "+359888777777" });

            var actual = testPhoneDatabase.ListEntries(0, 2);

            Assert.AreEqual(expected.Count(), actual.Count());

            IEnumerator e1 = expected.GetEnumerator();
            IEnumerator e2 = actual.GetEnumerator();

            while (e1.MoveNext() && e2.MoveNext())
            {
                Assert.AreEqual(e1.Current.ToString(), e2.Current.ToString());
            }
        }
Пример #33
0
 public static void Add(this ListEntry listRow, KeyValuePair <string, string> kv)
 {
     Add(listRow, kv.Key, kv.Value);
 }
Пример #34
0
        public void Display(ListEntry listEntry, CertificateStorage storage, Certificate caCertificate, IEnumerable<ListEntry> allListEntries)
        {
            this.certificate = listEntry.Certificate;
              this.request = listEntry.Request;

              this.idTextBox.Text = this.certificate.Id.ToString();
              this.typeTextBox.Text = this.certificate.TypeText;
              this.nameTextBox.Text = this.request.FullName;
              this.emailAddressTextBox.Text = this.request.EmailAddress;
              this.cantonTextBox.Text = this.certificate is VoterCertificate ? GroupList.GetGroupName(((VoterCertificate)this.certificate).GroupId) : "N/A";
              this.fingerprintTextBox.Text = this.certificate.Fingerprint;
              this.language = this.certificate.Language;
              this.validFromPicker.MinDate = DateTime.Now;
              this.validFromPicker.MaxDate = DateTime.Now.AddMonths(6);
              this.validFromPicker.Value = DateTime.Now;

              bool requestValid = true;

              if (this.request is SignatureRequest2)
              {
            SignatureRequest2 request2 = (SignatureRequest2)this.request;
            ListEntry signingListEntry = allListEntries.Where(le => le.Certificate.IsIdentic(request2.SigningCertificate)).FirstOrDefault();
            requestValid &= signingListEntry != null;

            this.signedByIdTextBox.Text = request2.SigningCertificate.Id.ToString();
            this.signedByTypeTextBox.Text = request2.SigningCertificate.TypeText;
            this.signedByCantonTextBox.Text = request2.SigningCertificate is VoterCertificate ? GroupList.GetGroupName(((VoterCertificate)request2.SigningCertificate).GroupId) : "N/A";
            this.signedByFingerprintTextBox.Text = request2.SigningCertificate.Fingerprint;

            if (signingListEntry != null)
            {
              requestValid &= signingListEntry.Certificate.Fingerprint == request2.SigningCertificate.Fingerprint;

              this.signedByNameTextBox.Text = signingListEntry.Request.FullName;
              this.signedByEmailAddressTextBox.Text = signingListEntry.Request.EmailAddress;
              this.validUntilPicker.Value = request2.SigningCertificate.ExpectedValidUntil(storage, DateTime.Now);
              this.validUntilPicker.MinDate = DateTime.Now;
              this.validUntilPicker.MaxDate = this.validUntilPicker.Value;
              this.printButton.Enabled = true;
            }
            else
            {
              this.signedByNameTextBox.Text = "N/A";
              this.signedByEmailAddressTextBox.Text = "N/A";
              this.validUntilPicker.MinDate = DateTime.Now;
              this.validUntilPicker.MaxDate = DateTime.Now.AddYears(3).AddMonths(6);
              this.printButton.Enabled = false;
            }

            var result = request2.SigningCertificate.Validate(storage);
            requestValid &= result == CertificateValidationResult.Valid;
            this.signedByStatusTextBox.Text = result.ToString();
            this.signedByStatusTextBox.BackColor = result == CertificateValidationResult.Valid ? Color.Green : Color.Red;

            bool signatureValid = request2.IsSignatureValid();
            requestValid &= signatureValid;
            this.signedBySignatureTextBox.Text = signatureValid ? "Valid" : "Invalid";
            this.signedBySignatureTextBox.BackColor = signatureValid ? Color.Green : Color.Red;
              }
              else
              {
            this.signedByIdTextBox.Text = "N/A";
            this.signedByFingerprintTextBox.Text = "N/A";
            this.signedByNameTextBox.Text = "N/A";
            this.signedByEmailAddressTextBox.Text = "N/A";
            this.signedByStatusTextBox.Text = "N/A";
            this.signedBySignatureTextBox.Text = "N/A";
            this.signedByCantonLabel.Text = "N/A";
            this.signedByTypeLabel.Text = "N/A";
            this.printButton.Enabled = false;
            this.validUntilPicker.Value = DateTime.Now.AddYears(3);
              }

              if (requestValid && listEntry.VerifyRequestSimple())
              {
            LibraryResources.Culture = Language.English.ToCulture();
            this.reasonComboBox.Items.Add(LibraryResources.RefusedFingerprintNoMatch);
            this.reasonComboBox.Items.Add(LibraryResources.RefusedPersonHasAlready);
            this.reasonComboBox.Items.Add(LibraryResources.RefusedRequestForgotten);
            this.reasonComboBox.Items.Add(LibraryResources.RefusedRequestLost);
            this.reasonComboBox.Items.Add(LibraryResources.RefusedRequestNotValid);

            if (certificate is VoterCertificate)
            {
              this.reasonComboBox.Items.Add(LibraryResources.RefusedPersonNoPirate);
            }
            else
            {
              this.reasonComboBox.Items.Add(LibraryResources.RefusedPersonNotInOffice);
            }
              }
              else
              {
            this.refuseRadioButton.Checked = true;
            this.acceptSignRadioButton.Enabled = false;
              }

              CheckValid();
        }
 public Task Remove(ListEntry entry)
 {
     _context.Remove(entry);
     return Task.CompletedTask;
 }
 public async Task<ListEntry> Add(ListEntry entry)
 {
     await _context.ListEntries.AddAsync(entry);
     return entry;
 }
        /// <summary>
        /// Gets the measurement value.
        /// </summary>
        /// <param name="energyEntry">The energy entry.</param>
        /// <param name="serverId">The server id required for ECC signature verification.</param>
        /// <param name="publicKey">The public key required for ECC signature verification.</param>
        /// <returns>
        /// The measurementValue structure based on a SmlListEntry.
        /// </returns>
        private static MeasurementValue GetMeasurementValue(ListEntry energyEntry, byte[] serverId = null, byte[] publicKey = null)
        {
            var counterValueUnscaled = Convert.ToInt64(energyEntry.Value);
            var scaler = energyEntry.Scaler;
            double? counterValueScaled = counterValueUnscaled;
            if (scaler < 0)
            {
                while (scaler++ < 0)
                {
                    counterValueScaled = counterValueScaled / 10;
                }
            }
            else
            {
                while (scaler-- > 0)
                {
                    counterValueScaled = counterValueScaled * 10;
                }
            }

            var mv = new MeasurementValue
               {
                   DataValue = counterValueScaled,
                   ObisValue = (long)(ulong)energyEntry.Name,
                   Unit = string.Format("{0}", energyEntry.Unit),
                   ValueTime = energyEntry.Time != null ? energyEntry.Time.UtcTime : DateTime.MinValue,
                   ValueSignature = energyEntry.Signature,
                   SignatureVerificationStatus = (int)SignatureVerificationResult.Unchecked
               };

            if (energyEntry.Status != null)
            {
                mv.StatusWord = (EdlStatusWord)energyEntry.Status;
            }

            // set an EDL 'invalid timestamp' to C# DateTime = null
            if (mv.ValueTime < new DateTime(1970, 1, 2) || mv.ValueTime > new DateTime(2100, 1, 1))
            {
                mv.ValueTime = null;
            }

            // Check the ECC signature
            if (mv.ValueSignature != null && mv.ValueTime != null && mv.ValueSignature.Length == 50 && publicKey != null && serverId != null)
            {
                //var verificationSvc = new EdlFormDataVerificationService();
                //var bdi = new EdlFormBillingDataItem();
                //bdi.BillingLocalDateTime = mv.ValueTime.Value;
                //bdi.CounterValue = counterValueUnscaled;
                //bdi.CounterValueScaler = scaler.Value;
                //bdi.EventLogCounter =
                //   BitConverter.ToUInt16(
                //      energyEntry.Signature.Skip(48).Take(2).Reverse().ToArray(), 0);
                //bdi.ObisCode = energyEntry.Name.ToArray();
                //bdi.PublicKey = publicKey;
                //bdi.ServerId = serverId;
                //bdi.Signature = mv.ValueSignature.Take(48).ToArray();

                // set result value

                /*mv.SignatureVerificationStatus = (int)(verificationSvc.VerifyFormBillingData(bdi) ?
                                                          SignatureVerificationResult.Valid :
                                                          SignatureVerificationResult.Invalid);*/
            }

            return mv;
        }
Пример #38
0
 //default first page constructor
 public ListEntryGump(Mobile owner, ListEntry listentry) : this(owner, listentry, 0)
 {
 }
Пример #39
0
 public TSODataDefinitionWrapper(ListEntry item)
 {
     Item = item;
 }
Пример #40
0
        private void createAdminCertificateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateAdminDialog dialog = new CreateAdminDialog();

              if (dialog.ShowDialog() == DialogResult.OK)
              {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "Save Admin Certificate";
            saveDialog.CheckPathExists = true;
            saveDialog.Filter = Files.CertificateFileFilter;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
              string fullName = string.Format("{0} {1}, {2}", dialog.FirstName, dialog.FamilyName, dialog.Function);
              AdminCertificate certificate = new AdminCertificate(Language.English, dialog.Passphrase, fullName);
              certificate.CreateSelfSignature();

              SignatureRequest request = new SignatureRequest(dialog.FirstName, dialog.FamilyName, dialog.EmailAddress);
              Secure<SignatureRequest> signedRequest = new Secure<SignatureRequest>(request, CaCertificate, certificate);

              CertificateAuthorityEntry entry = new CertificateAuthorityEntry(signedRequest);
              entry.Sign(CaCertificate, DateTime.Now, dialog.ValidUntil);
              certificate.AddSignature(entry.Response.Value.Signature);

              string entryFileName = DataPath(entry.Certificate.Id.ToString() + ".pi-ca-entry");
              entry.Save(DataPath(entryFileName));

              ListEntry listEntry = new ListEntry(entryFileName, entry, CaCertificate);
              Entries.Add(listEntry);
              this.entryListView.Items.Add(listEntry.CreateItem(CaCertificate));

              certificate.Save(saveDialog.FileName);
            }
              }
        }
Пример #41
0
 public Row(ListEntry entry)
 {
     this.entry = entry;
 }
Пример #42
0
 internal WorksheetRow(ListFeed feed, ListEntry entry)
 {
     _entry = entry;
     _feed  = feed;
 }
        public override void Log(LoggingEntery LE)
        {
            IniFile Ini = new IniFile(Path.Combine(Environment.CurrentDirectory, "GoogleDocs.ini"));

            // nir start
            ////////////////////////////////////////////////////////////////////////////
            // STEP 1: Configure how to perform OAuth 2.0
            ////////////////////////////////////////////////////////////////////////////

            // TODO: Update the following information with that obtained from
            // https://code.google.com/apis/console. After registering
            // your application, these will be provided for you.

            //string CLIENT_ID = "339569043085-6k0io9kdubi7a3g3jes4m76t614fkccr.apps.googleusercontent.com";

            // This is the OAuth 2.0 Client Secret retrieved
            // above.  Be sure to store this value securely.  Leaking this
            // value would enable others to act on behalf of your application!
            //string CLIENT_SECRET = "wWC4Wcb12RbQg4YuGWJtkh4j";

            // Space separated list of scopes for which to request access.
            //string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";

            // This is the Redirect URI for installed applications.
            // If you are building a web application, you have to set your
            // Redirect URI at https://code.google.com/apis/console.
            //tring REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";

            ////////////////////////////////////////////////////////////////////////////
            // STEP 2: Set up the OAuth 2.0 object
            ////////////////////////////////////////////////////////////////////////////

            // OAuth2Parameters holds all the parameters related to OAuth 2.0.
            OAuth2Parameters parameters = new OAuth2Parameters();

            // Set your OAuth 2.0 Client Id (which you can register at
            // https://code.google.com/apis/console).
            parameters.ClientId = Ini.IniReadValue(ConnectSection, "ClientID");

            // Set your OAuth 2.0 Client Secret, which can be obtained at
            // https://code.google.com/apis/console.
            parameters.ClientSecret = Ini.IniReadValue(ConnectSection, "ClientSecret");

            // Set your Redirect URI, which can be registered at
            // https://code.google.com/apis/console.
            parameters.RedirectUri = Ini.IniReadValue(ConnectSection, "RedirectURI");

            // Set your refresh token
            parameters.RefreshToken = Ini.IniReadValue(ConnectSection, "RefreshToken");
            parameters.AccessToken  = Ini.IniReadValue(ConnectSection, "LastAccessToken");

            // Set the scope for this particular service.
            parameters.Scope = Ini.IniReadValue(ConnectSection, "Scope");

            // Get the authorization url.  The user of your application must visit
            // this url in order to authorize with Google.  If you are building a
            // browser-based application, you can redirect the user to the authorization
            // url.
            //string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
            //Console.WriteLine(authorizationUrl);
            //Console.WriteLine("Please visit the URL above to authorize your OAuth "
            //  + "request token.  Once that is complete, type in your access code to "
            //  + "continue...");

            ////////////////////////////////////////////////////////////////////////////
            // STEP 4: Get the Access Token
            ////////////////////////////////////////////////////////////////////////////

            // Once the user authorizes with Google, the request token can be exchanged
            // for a long-lived access token.  If you are building a browser-based
            // application, you should parse the incoming request token from the url and
            // set it in OAuthParameters before calling GetAccessToken().
            OAuthUtil.RefreshAccessToken(parameters);//parameters.AccessToken;
            Ini.IniWriteValue(ConnectSection, "LastAccessToken", parameters.AccessToken);
            // Console.WriteLine("OAuth Access Token: " + accessToken);

            ////////////////////////////////////////////////////////////////////////////
            // STEP 5: Make an OAuth authorized request to Google
            ////////////////////////////////////////////////////////////////////////////

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "OctoTipPlus", parameters);
            SpreadsheetsService myService = new SpreadsheetsService("OctoTipPlus");

            myService.RequestFactory = requestFactory;
            // nir end

            string User     = Ini.IniReadValue("UserLogin", "User");
            string Password = Ini.IniReadValue("UserLogin", "Password");

            //	SpreadsheetsService myService = new SpreadsheetsService("MySpreadsheetIntegration-v1");
            //myService.setUserCredentials(User,Password);

            SpreadsheetQuery Squery = new SpreadsheetQuery();
            string           Sender = LE.Sender;

            Squery.Title = Sender;
            Squery.Exact = true;
            SpreadsheetFeed Sfeed;

            try
            {
                Sfeed = myService.Query(Squery);
            }
            catch (Google.GData.Client.InvalidCredentialsException e)
            {
                throw(new Exception(string.Format("Credentials error in google acount for user:{0}", User), e));
            }


            if (Sfeed.Entries.Count == 0)
            {
                //DriveService service1 = new DriveService();

                //service.SetAuthenticationToken(parameters.AccessToken);//.setUserCredentials(User,Password);
                //Google.GData.Client.GOAuth2RequestFactory requestf =  new Google.GData.Client.GOAuth2RequestFactory(null, "OctoTipPlus",parameters);
                OAuthUtil.RefreshAccessToken(parameters);                //parameters.AccessToken;
                Ini.IniWriteValue(ConnectSection, "LastAccessToken", parameters.AccessToken);
                Google.GData.Documents.DocumentsService service = new Google.GData.Documents.DocumentsService("OctoTipPlus");
                GOAuth2RequestFactory requestFactory2           =
                    new GOAuth2RequestFactory(null, "OctoTipPlus", parameters);
                service.RequestFactory = requestFactory2;
                //service.RequestFactory=requestf;
                // Instantiate a DocumentEntry object to be inserted.
                Google.GData.Documents.DocumentEntry entry = new Google.GData.Documents.DocumentEntry();

                // Set the document title
                entry.Title.Text = LE.Sender;

                // Add the document category
                entry.Categories.Add(Google.GData.Documents.DocumentEntry.SPREADSHEET_CATEGORY);

                // Make a request to the API and create the document.
                Google.GData.Documents.DocumentEntry newEntry = service.Insert(
                    Google.GData.Documents.DocumentsListQuery.documentsBaseUri, entry);

                Squery       = new SpreadsheetQuery();
                Squery.Title = Sender;
                Squery.Exact = true;
                Sfeed        = myService.Query(Squery);
            }


            SpreadsheetEntry spreadsheet = (SpreadsheetEntry)Sfeed.Entries[0];

            WorksheetEntry ProtocolWorksheetEntry = null;


            AtomLink link = spreadsheet.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);

            WorksheetQuery Wquery = new WorksheetQuery(link.HRef.ToString());
            WorksheetFeed  Wfeed  = myService.Query(Wquery);

            foreach (WorksheetEntry worksheet in Wfeed.Entries)
            {
                if (worksheet.Title.Text == LE.SubSender)
                {
                    ProtocolWorksheetEntry = worksheet;
                }
            }


            if (ProtocolWorksheetEntry == null)
            {
                // cteate new worksheet
                WorksheetEntry worksheet = new WorksheetEntry();
                worksheet.Title.Text = LE.SubSender;
                worksheet.Cols       = 3;
                worksheet.Rows       = 5;

                // Send the local representation of the worksheet to the API for
                // creation.  The URL to use here is the worksheet feed URL of our
                // spreadsheet.
                WorksheetFeed wsFeed = spreadsheet.Worksheets;
                ProtocolWorksheetEntry = myService.Insert(wsFeed, worksheet);



                CellFeed cellFeed = ProtocolWorksheetEntry.QueryCellFeed();

                CellEntry cellEntry = new CellEntry(1, 1, DateHeader);
                cellFeed.Insert(cellEntry);
                cellEntry = new CellEntry(1, 2, MessageHeader);
                cellFeed.Insert(cellEntry);
            }


            // Define the URL to request the list feed of the worksheet.
            AtomLink listFeedLink = ProtocolWorksheetEntry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

            // Fetch the list feed of the worksheet.
            ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
            ListFeed  listFeed  = myService.Query(listQuery);

            string Message = string.Format("{0}\n{1}", LE.Title, LE.Message);

            // Create a local representation of the new row.
            ListEntry row = new ListEntry();

            row.Elements.Add(new ListEntry.Custom()
            {
                LocalName = DateHeader, Value = DateTime.Now.ToString()
            });
            row.Elements.Add(new ListEntry.Custom()
            {
                LocalName = MessageHeader, Value = Message
            });


            // Send the new row to the API for insertion.
            myService.Insert(listFeed, row);
        }
Пример #44
0
 /// <summary>
 /// リストにエントリを追加する
 /// </summary>
 /// <param name="name">名前(大文字小文字は同一視されるが、小文字でないとAPIが400エラーで例外投げる)</param>
 /// <param name="value">値</param>
 public static void Add(this ListEntry listRow, string name, int value)
 {
     Add(listRow, name, value.ToString());
 }
Пример #45
0
        private void RemoveUpdateFromHash(ListEntry entry)
        {
            HashUpdateEntry element;
            if (m_pHashForUpdates.TryGetValue(entry.Target, out element))
            {
                // list entry
                element.List.Remove(entry);
                element.Entry = null;

                // hash entry
                m_pHashForUpdates.Remove(entry.Target);

                element.Target = null;
            }
        }
Пример #46
0
 public ListEntry(object key, Delegate handler, ListEntry next)
 {
     Next = next;
     Key = key;
     Handler = handler;
 }
Пример #47
0
        private void PriorityIn(LinkedList<ListEntry> list, ICCSelectorProtocol target, int priority, bool paused)
        {
            var listElement = new ListEntry
                {
                    Target = target,
                    Priority = priority,
                    Paused = paused,
                    MarkedForDeletion = false
                };

            if (list.First == null)
            {
                list.AddFirst(listElement);
            }
            else
            {
                bool added = false;
                for (LinkedListNode<ListEntry> node = list.First; node != null; node = node.Next)
                {
                    if (priority < node.Value.Priority)
                    {
                        list.AddBefore(node, listElement);
                        added = true;
                        break;
                    }
                }

                if (!added)
                {
                    list.AddLast(listElement);
                }
            }

            // update hash entry for quick access
            var hashElement = new HashUpdateEntry
                {
                    Target = target,
                    List = list,
                    Entry = listElement
                };

            m_pHashForUpdates.Add(target, hashElement);
        }
 public void Init()
 {
     entry = new ListEntry();
 }
Пример #49
0
        private void AppendIn(LinkedList<ListEntry> list, ICCSelectorProtocol target, bool paused)
        {
            var listElement = new ListEntry
                {
                    Target = target,
                    Paused = paused,
                    MarkedForDeletion = false
                };

            list.AddLast(listElement);

            // update hash entry for quicker access
            var hashElement = new HashUpdateEntry
                {
                    Target = target,
                    List = list,
                    Entry = listElement
                };

            m_pHashForUpdates.Add(target, hashElement);
        }
Пример #50
0
        public GameDatabaseEntry(ListEntry listEntry)
        {
            _listEntry = listEntry;

            _url = listEntry.Elements[(int)DataBaseColumn.Link].Value;
            _condition = listEntry.Elements[(int)DataBaseColumn.Condition].Value;

            _gameId = int.Parse(_listEntry.Elements[(int)DataBaseColumn.GameID].Value);
            _status = _listEntry.Elements[(int)DataBaseColumn.Status].Value;
            double sellingPrice;
            if (double.TryParse(_listEntry.Elements[(int)DataBaseColumn.SellingPrice].Value, out sellingPrice))
            {
                _sellingPrice = sellingPrice;
            }

            _details = new GameDetailer(_url, _condition);
            //if (!_status.Contains("Sold"))
            {
                Initalize();
            }
        }
Пример #51
0
 public void Append(MimeString value)
 {
     if (value.Length == 0)
         return;
     var count = this.Count;
     if (count == 0) {
         first = value;
         if (overflow == null)
             return;
         ++overflow[0].HeaderCount;
         overflow[0].HeaderTotalLength += value.Length;
     } else if (count < 4096) {
         if (overflow == null) {
             overflow = new ListEntry[8];
             overflow[0].HeaderCount = 1;
             overflow[0].HeaderTotalLength = first.Length;
         } else if (count == overflow.Length) {
             var length = count*2;
             if (length >= 4096)
                 length = 4128;
             var listEntryArray = new ListEntry[length];
             System.Array.Copy(overflow, 0, listEntryArray, 0, overflow.Length);
             overflow = listEntryArray;
         }
         overflow[count].Str = value;
         ++overflow[0].HeaderCount;
         overflow[0].HeaderTotalLength += value.Length;
     } else {
         var index1 = 4096 + count/4096 - 1;
         var index2 = count%4096;
         if (index1 >= overflow.Length)
             throw new MimeException("MIME is too complex (header value is too long)");
         if (overflow[index1].Secondary == null)
             overflow[index1].Secondary = new MimeString[4096];
         overflow[index1].Secondary[index2] = value;
         ++overflow[0].HeaderCount;
         overflow[0].HeaderTotalLength += value.Length;
     }
 }
Пример #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ListEntry"/> class.
 /// </summary>
 /// <param name="key">The unique key.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="next">The next entry.</param>
 public ListEntry(string key, Delegate handler, ListEntry next)
 {
     this.Next = next;
     this.Key = key;
     this.Handler = handler;
 }
Пример #53
0
        public Dictionary <ISweepAndPruneObject, List <ISweepAndPruneObject> > Resolve2()
        {
            Dictionary <ISweepAndPruneObject, List <ISweepAndPruneObject> > dict = new Dictionary <ISweepAndPruneObject, List <ISweepAndPruneObject> >();

            if (!initialized)
            {
                initialized = true;
                startAndEndPoints.Sort(comparer);
            }
            else
            {
                InsertionSortList <ListEntry> .InsertionSort(startAndEndPoints, comparer);
            }

            // TODO: Add check so that s_i < e_i for all entries

            List <T> openList = new List <T>();

            for (int i = 0; i < startAndEndPoints.Count; i++)
            {
                ListEntry le = startAndEndPoints[i];
                if (le.IsStartPoint)            // add object to open list
                {
                    foreach (var o in openList) // TODO: perform precise collision detection
                    {
                        if (le.Object.Min.Y > o.Max.Y || le.Object.Max.Y < o.Min.Y)
                        {
                            continue;
                        }

                        if (duplicateIntersections)
                        {
                            //le.Object.Intersectees.Add(o);
                            //o.Intersectees.Add(le.Object);
                            AddToDictionary(ref dict, le.Object, o);
                            AddToDictionary(ref dict, o, le.Object);
                        }
                        else
                        {
                            // add intersection to object with lowest hashcode
                            if (le.Object.GetHashCode() < o.GetHashCode())
                            {
                                AddToDictionary(ref dict, le.Object, o);
                            }
                            else
                            {
                                AddToDictionary(ref dict, o, le.Object);
                            }
                            //if (le.Object.GetHashCode() < o.GetHashCode())
                            //    le.Object.Intersectees.Add(o);
                            //else
                            //    o.Intersectees.Add(le.Object);
                        }
                    }
                    openList.Add(le.Object);        // TODO: This is quite expensive
                }
                else
                if (!openList.Remove(le.Object))
                {
                    throw new Exception("Removal failed");
                }
            }
            return(dict);
        }
Пример #54
0
 /// <summary>
 /// Adds a delegate to the list.
 /// </summary>
 /// <param name="key">The unique key that owns the event.</param>
 /// <param name="value">The delegate to add to the list.</param>
 public void AddHandler(string key, Delegate value)
 {
     if (!string.IsNullOrEmpty(key) && value != null)
     {
         ListEntry entry = this.Find(key);
         if (entry != null)
         {
             entry.Handler = Delegate.Combine(entry.Handler, value);
         }
         else
         {
             this.head = new ListEntry(key, value, this.head);
         }
     }
 }
Пример #55
0
        private void importRequestsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
              dialog.Title = "Open Signature Requests";
              dialog.CheckPathExists = true;
              dialog.CheckFileExists = true;
              dialog.Multiselect = true;
              dialog.Filter = Files.SignatureRequestFileFilter;

              if (dialog.ShowDialog() == DialogResult.OK)
              {
            List<string> alreadyAddedList = new List<string>();
            List<string> invalidList = new List<string>();

            foreach (string fileName in dialog.FileNames)
            {
              Secure<SignatureRequest> secureSignatureRequest = Serializable.Load<Secure<SignatureRequest>>(fileName);

              if (secureSignatureRequest.VerifySimple())
              {
            if (Entries.Any(listEntry => listEntry.Certificate.Id == secureSignatureRequest.Certificate.Id))
            {
              alreadyAddedList.Add(fileName);
            }
            else
            {
              CertificateAuthorityEntry entry = new CertificateAuthorityEntry(secureSignatureRequest);
              string entryFileName = DataPath(entry.Certificate.Id.ToString() + ".pi-ca-entry");
              entry.Save(DataPath(entryFileName));

              ListEntry listEntry = new ListEntry(entryFileName, entry, CaCertificate);
              Entries.Add(listEntry);
              this.entryListView.Items.Add(listEntry.CreateItem(CaCertificate));
            }
              }
              else
              {
            invalidList.Add(fileName);
              }
            }

            if (invalidList.Count > 0)
            {
              StringBuilder message = new StringBuilder();
              message.AppendLine("The following request are not valid:");
              invalidList.ForEach(invalidRequest => message.AppendLine(invalidRequest));
              MessageForm.Show(message.ToString(), "Pi-Vote CA GUI", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if (alreadyAddedList.Count > 0)
            {
              StringBuilder message = new StringBuilder();
              message.AppendLine("The following request are already in your list:");
              alreadyAddedList.ForEach(invalidRequest => message.AppendLine(invalidRequest));
              MessageForm.Show(message.ToString(), "Pi-Vote CA GUI", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
              }
        }