コード例 #1
0
        public KissyKissyAction(bool hasActionCommand, int numAttacks, int damagePerAttack, Elements damageElement,
                                bool piercing, bool sideDirect, HeightStates[] heightsAffected)
        {
            Name = "Kissy-Kissy";

            //None of the enemies that use this move ever perform a charge; it makes sense to me to make it use up a charge
            MoveInfo = new MoveActionData(null, "Absorb health from your opponent.", MoveResourceTypes.FP, 0, CostDisplayTypes.Shown, MoveAffectionTypes.Other,
                                          TargetSelectionMenu.EntitySelectionType.Single, true, heightsAffected, User.GetOpposingEntityType());

            ContactTypes contactType = ContactTypes.SideDirect;

            if (sideDirect == false)
            {
                contactType = ContactTypes.TopDirect;
            }

            DamageInfo = new DamageData(damagePerAttack, damageElement, piercing, contactType, ContactProperties.None, null, false, false,
                                        DefensiveActionTypes.None, DamageEffects.None);

            SetMoveSequence(new KissyKissySequence(this, numAttacks));

            EnableActionCommand = hasActionCommand;

            if (hasActionCommand == true)
            {
                //If Kissy-Kissy has an Action Command, it can't be Guarded or Superguarded
                DamageInfo.DefensiveOverride = DefensiveActionTypes.Guard | DefensiveActionTypes.Superguard;

                actionCommand = new MashButtonCommand(MoveSequence, 100d, 10d, MashButtonCommand.InfiniteTime, Microsoft.Xna.Framework.Input.Keys.A);
            }
        }
コード例 #2
0
 public SiteContact(ContactTypes type, String siteID)
     : base(Table, Database.Instance)
 {
     PrimaryKeyColumns = PrimaryKeys;
     int contactNum = 0;
     switch (type)
     {
         case ContactTypes.Foreman:
             contactNum = 0;
             break;
         case ContactTypes.Supervisor1:
             contactNum = 1;
             break;
         case ContactTypes.Supervisor2:
             contactNum = 2;
             break;
         case ContactTypes.SupplyAuth:
             contactNum = 3;
             break;
     }
     SetValue(Fields.contactType.ToString(), contactNum);
     SetValue(Fields.siteID.ToString(), siteID);
     SetValue(Fields.Name.ToString(), "");
     SetValue(Fields.Email.ToString(), "");
     SetValue(Fields.Phone.ToString(), "");
     isNew = true;
 }
コード例 #3
0
        public async Task <IActionResult> PutContactTypes([FromRoute] int id, [FromBody] ContactTypes contactTypes)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != contactTypes.ContactTypeID)
            {
                return(BadRequest());
            }

            _context.Entry(contactTypes).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ContactTypesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #4
0
        static void Main(string[] args)
        {
            Dictionary <string, Person> dict = new Dictionary <string, Person>();

            ContactTypes contactSimple    = ContactTypes.Billing;
            ContactTypes multipleContacts = ContactTypes.Work | ContactTypes.Home;


            KeyValuePair <string, string> t     = new KeyValuePair <string, string>("key", "value");
            Dictionary <string, string>   dict2 = new Dictionary <string, string>()
            {
                { "key1", "val1" },
                { "key2", "val2" }
            };


            System.Text.StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 1000; i++)
            {
                builder.AppendFormat("loop i is {0}", i.ToString());
                builder.AppendLine("tyaye");
                builder.AppendLine("tyaye");
            }

            Test tst = new Test();


            Person    steven = new Person("Steven", 17);
            Person    jemel  = new Person("Jemel", 83);
            SuperHero batman = new SuperHero("Batman", 35, "None!?");



            var x = 0;
        }
コード例 #5
0
        public IActionResult AddContact([FromForm] ContactPM model)
        {
            var user = _phoneBookContext.Users.Include(q => q.ContactTypes).FirstOrDefault(p => p.ID == model.UserID);

            if (user != null)
            {
                if (user.ContactTypes == null)
                {
                    ContactTypes contactTypes = new ContactTypes();
                    contactTypes.Email    = model.Email;
                    contactTypes.Phone    = model.Phone;
                    contactTypes.Location = model.Location;
                    contactTypes.UserID   = model.UserID;

                    _phoneBookContext.ContactTypes.Add(contactTypes);
                    _phoneBookContext.SaveChanges();

                    return(Ok($"ID'si {model.UserID} olan kişiye iletişim bilgisi eklendi!"));
                }
                else
                {
                    return(BadRequest($"ID'si {model.UserID} olan kişinin zaten iletişim bilgisi var!(güncelleme istenmemiş)"));
                }
            }
            else
            {
                return(BadRequest($"ID'si {model.UserID} olan kişi bulunamadı!"));
            }
        }
コード例 #6
0
 private void LoadPickerData()
 {
     try
     {
         ContactTypes = AppData.ConfigModel.ContactTypes(AppData.PropertyModel.SelectedProperty.Organisation);
         foreach (var res in ContactTypes.OrderBy(x => x.Description).ToList())
         {
             Pkr_CustomerType.Items.Add(res.Description);
         }
         if (AppData.PropertyModel.SelectedRecord.Record.Record.Customers.Count > 0)
         {
             Pkr_CustomerType.SelectedIndex =
                 Pkr_CustomerType.Items.IndexOf(
                     AppData.PropertyModel.SelectedRecord.Record.Record.Customers[0].CustomerTypeDescription);
         }
         else
         {
             Pkr_CustomerType.SelectedIndex = 0;
         }
     }
     catch (Exception ex)
     {
         LogTracking.LogTrace(ex.ToString());
     }
 }
コード例 #7
0
        /// <summary>
        /// Determines the result of contact, based on the type of contact made, when it's made with this entity.
        /// <para>Contacts that aren't a Success are prioritized over any Payback.
        /// If a ContactResult of Success is found, then the Payback for this entity is added if it exists
        /// and the ContactResult becomes a PartialSuccess.</para>
        /// </summary>
        /// <param name="attacker">The entity attacking this one</param>
        /// <param name="contactType">The type of contact made with this entity</param>
        /// <returns>A ContactResultInfo containing the result of the interaction</returns>
        public ContactResultInfo GetContactResult(BattleEntity attacker, ContactTypes contactType)
        {
            ContactResultInfo contactResultInfo = Interactions.GetContactResult(attacker, contactType, GetAllPhysAttributes(), attacker.EntityProperties.GetContactExceptions(contactType));

            //On a Success, check if this Entity has any Payback and add it if so
            if ((contactResultInfo.ContactResult == ContactResult.Success || contactResultInfo.ContactResult == ContactResult.PartialSuccess) && HasPayback() == true)
            {
                PaybackHolder paybackholder;

                //Factor in the contact's Payback on a PartialSuccess
                if (contactResultInfo.ContactResult == ContactResult.PartialSuccess)
                {
                    paybackholder = GetPayback(contactResultInfo.Paybackholder);
                }
                //Get only the BattleEntity's Payback on a Success
                else
                {
                    paybackholder = GetPayback();
                }

                //Since there's Payback, the result is now a PartialSuccess
                contactResultInfo.ContactResult = ContactResult.PartialSuccess;
                contactResultInfo.Paybackholder = paybackholder;
            }

            return(contactResultInfo);
        }
コード例 #8
0
        /// <summary>
        /// Gets the result of a ContactType on a set of PhysicalAttributes
        /// </summary>
        /// <param name="attacker">The BattleEntity performing the attack</param>
        /// <param name="contactType">The ContactType performed</param>
        /// <param name="physAttributes">The set of PhysicalAttributes to test against</param>
        /// <param name="attributesToIgnore">A set of PhysicalAttributes to ignore</param>
        /// <returns>A ContactResultInfo of the interaction</returns>
        public static ContactResultInfo GetContactResult(BattleEntity attacker, ContactTypes contactType, PhysicalAttributes[] physAttributes, params PhysicalAttributes[] attributesToIgnore)
        {
            //Return the default value
            if (ContactTable.ContainsKey(contactType) == false || physAttributes == null)
            {
                Debug.LogWarning($"{nameof(physAttributes)} array is null or {nameof(ContactTable)} does not contain the ContactType {contactType}!");
                return(ContactResultInfo.Default);
            }

            //Look through the attributes and find the first match
            for (int i = 0; i < physAttributes.Length; i++)
            {
                Dictionary <PhysicalAttributes, ContactResultInfo> tableForContact = ContactTable[contactType];
                PhysicalAttributes attribute = physAttributes[i];

                //If this attribute is ignored, move onto the next
                if (attributesToIgnore?.Contains(attribute) == true)
                {
                    continue;
                }

                if (tableForContact.ContainsKey(attribute) == true)
                {
                    ContactResultInfo contactResult = tableForContact[attribute];
                    //If the ContactResult is a Success if the entity has the same PhysicalAttribute as the one tested, set its result to Success
                    if (contactResult.SuccessIfSameAttr == true && attacker.EntityProperties.HasPhysAttributes(true, attribute) == true)
                    {
                        contactResult.ContactResult = ContactResult.Success;
                    }
                    return(contactResult);
                }
            }

            return(ContactResultInfo.Default);
        }
コード例 #9
0
		public List<ContactType> Get(ContactTypes request)
		{
			ContactTypeRepository repository = GetContactTypeRepository();
			List<ContactTypeEntity> entities = repository.Read();

			return entities.TranslateToResponse();
		}
コード例 #10
0
ファイル: User.cs プロジェクト: robertabbottwegmans/CMX-Weg
 /// <summary>
 ///     Determines if this instance of <see cref="User" /> is also a contact for an organization.  Users are considered a
 ///     contact if any of the fields typically associated with a Contact record are present.
 /// </summary>
 public bool IsUserAlsoContact()
 {
     return(AssociatedEntities != null && AssociatedEntities.Any() ||
            ContactTypes != null && ContactTypes.Any() ||
            !string.IsNullOrEmpty(PrimaryPhoneNumber) ||
            !string.IsNullOrEmpty(MobilePhoneNumber) ||
            !string.IsNullOrEmpty(Title) ||
            PhysicalAddress != null && !PhysicalAddress.IsEmpty());
 }
コード例 #11
0
        /// <summary>
        /// Returns a set of PhysicalAttributes to ignore when the BattleEntity makes contact
        /// </summary>
        /// <param name="contactType">The type of contact this BattleEntity made</param>
        /// <returns>An array of PhysicalAttributes this BattleEntity can ignore when making contact, otherwise an empty array</returns>
        public PhysicalAttributes[] GetContactExceptions(ContactTypes contactType)
        {
            //Return an empty array if no exceptions exist for this type of contact
            if (ContactExceptions.ContainsKey(contactType) == false)
            {
                return(new PhysicalAttributes[0]);
            }

            return(ContactExceptions[contactType].ToArray());
        }
コード例 #12
0
        /// <summary>
        /// Method used to add a contact by absolute position
        /// </summary>
        /// <param name="position">Absolute position of contact <see cref="PointF"/></param>
        /// <param name="contactType">Contact type to create <see cref="ContactTypes"/></param>
        /// <param name="heading"></param>
        /// <param name="speed"></param>
        /// <param name="altitude"></param>
        /// <returns></returns>
        protected IReferencePoint CreateContactAtPoint(PointF position, ContactTypes contactType, double heading = 0.00, double speed = 0.00, double altitude = 0.00)
        {
            var contactFactory = new ContactCreator();
            var newContact     = contactFactory.Create(RadarReceiver, position, heading, altitude, speed, contactType);

            Logger.Info($"Creating contact: {contactType} as a plotted contact at {position}");
            newContact.ReferencePointChanged += NewContact_ReferencePointChanged;
            RadarReceiver.AddContact(newContact);
            newContact.Start();
            return(newContact);
        }
コード例 #13
0
        public EditProfileVM GetEditProfileVM()
        {
            var user   = AuthService.CurrentUser;
            var result =
                new EditProfileVM
            {
                User = AuthService.CurrentUser,
            };

            SetDictionaries(result);

            if (result.User != null)
            {
                var contactsVM = result.Contacts;
                if (user.IsCompany)
                {
                    contactsVM.Phone = GetContact(user.Company.UserContacts,
                                                  ContactTypes.Phone);
                    contactsVM.Mobile =
                        GetContact(user.Company.UserContacts, ContactTypes.Mobile);
                    contactsVM.WorkPhone =
                        GetContact(user.Company.UserContacts, ContactTypes.WorkPhone);
                    result.UserAddress = user.Company.UserAddresses.FirstOrDefault();
                }
                else
                {
                    result.UserAddress = user.UserAddresses.FirstOrDefault();

                    contactsVM.Socials = GetSocials(user.UserContacts);

                    InitPhones(user, contactsVM);
                }
            }
            else
            {
                result.User = new User();
            }

            if (result.UserAddress == null)
            {
                result.UserAddress = new UserAddress();
            }
            if (result.Company == null)
            {
                result.Company = new Company();
            }
            result.ContactTypes = UserContractTypeService.GetAll()
                                  .Where(uct => ContactTypes.ForProfile().Contains(uct.ContactTypeID))
                                  .ToList();


            return(result);
        }
コード例 #14
0
        public async Task <IActionResult> PostContactTypes([FromBody] ContactTypes contactTypes)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.ContactTypes.Add(contactTypes);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetContactTypes", new { id = contactTypes.ContactTypeID }, contactTypes));
        }
コード例 #15
0
        /// <summary>
        /// Adds a contact exception to the entity
        /// </summary>
        /// <param name="contactType"></param>
        /// <param name="physAttribute"></param>
        public void AddContactException(ContactTypes contactType, PhysicalAttributes physAttribute)
        {
            //Add a new key if one doesn't exist
            if (ContactExceptions.ContainsKey(contactType) == false)
            {
                ContactExceptions.Add(contactType, new List <PhysicalAttributes>());
            }

            //Add to the list
            ContactExceptions[contactType].Add(physAttribute);

            Debug.Log($"Added contact exception on {Entity.Name} for the {physAttribute} PhysicalAttribute during {contactType} contact!");
        }
コード例 #16
0
 protected override void Init()
 {
     RuleFor(x => x.Contact).Must((contact, x) =>
     {
         if (x.IsEmpty())
         {
             return(true);
         }
         var regexp = new Regex(ContactTypes.GetRegExp(contact.ContactTypeID));
         return(regexp.IsMatch(x));
     }
                                  ).WithMessage("Не верный формат");
 }
コード例 #17
0
        private void plotPanel_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContactTypes contactType      = ContactTypes.AirUnknown;
                var          typeToPlot       = $"{selectType.Text}{selectClass.Text}";
                var          absolutePosition = new PointF(e.X, e.Y);

                if (Enum.TryParse(typeToPlot, out contactType))
                {
                    var newContact = CreateContactAtPoint(absolutePosition, contactType, decimal.ToInt32(contactCourse.Value), decimal.ToInt32(contactSpeed.Value));
                    RefreshContactList();
                }
            }
        }
コード例 #18
0
 public async Task KeyValues()
 {
     var contactTypes = new ContactTypes();
     var keyValues = await contactTypes.KeyValuesAsync();
     int count = 0;
     int oldId = 0;
     string oldName = null;
     foreach (var keyValue in keyValues)
     {
         int id = int.Parse(keyValue.Key);
         Assert.Greater(id, oldId);
         oldId = id;
         Assert.False(string.IsNullOrEmpty(keyValue.Value));
         Assert.AreNotEqual(oldName, keyValue.Value);
         oldName = keyValue.Value;
         count++;
     }
     Assert.AreEqual(20, count);
 }
コード例 #19
0
        private List <UserContact> GetSocials(EntitySet <UserContact> contacts)
        {
            var allSocials      = ContactTypes.GetAllSocialServices();
            var currentContacts = contacts
                                  .Where(x => allSocials.Contains(x.ContactTypeID));
            var forAdd = allSocials.Where(x =>
                                          currentContacts.All(y => y.ContactTypeID != x));

            if (forAdd.Any())
            {
                var userContacts = UserContractTypeService.GetByPK(forAdd.Cast <object>())
                                   .ToList()
                                   .Select(x => new UserContact {
                    ContactTypeID   = x.ContactTypeID,
                    UserContactType = x
                });
                currentContacts = currentContacts.Union(userContacts).ToList();
            }
            return(currentContacts.OrderBy(x => allSocials.IndexOf(x.ContactTypeID)).ToList());
        }
コード例 #20
0
        public void RemoveContactException(ContactTypes contactType, PhysicalAttributes physAttribute)
        {
            if (ContactExceptions.ContainsKey(contactType) == false)
            {
                Debug.LogError($"Cannot remove {physAttribute} from the exception list on {Entity.Name} for {contactType} because no list exists!");
                return;
            }

            bool removed = ContactExceptions[contactType].Remove(physAttribute);

            if (removed == true)
            {
                Debug.Log($"Removed {physAttribute} attribute exception on {Entity.Name} for {contactType} contact!");
            }

            //If there are no PhysicalAttributes in the exceptions list for this ContactType, remove the key
            if (ContactExceptions[contactType].Count == 0)
            {
                ContactExceptions.Remove(contactType);
            }
        }
コード例 #21
0
        public static void AddContacts(User user, Student student)
        {
            var email = user.Email;

            if (student.StudentEmails.All(se => se.Email != email))
            {
                student.StudentEmails.Add(CreateStudentEmail(email));
            }

            var phones = user.UserContacts.ToList()
                         .Where(uc => !uc.Contact.IsEmpty() &&
                                ContactTypes.Phones().Contains(uc.ContactTypeID) &&
                                student.StudentPhones.All(sp => sp.PhoneNumber != uc.Contact));

            foreach (var phone in phones)
            {
                var phoneTypeTC = ContactTypes.GetPhoneTypeTC(phone.ContactTypeID);
                var phoneNumber = phone.Contact;
                student.StudentPhones.Add(CreateStudentPhone(phoneTypeTC, phoneNumber));
            }
        }
コード例 #22
0
        public static Contact Create(ContactTypes contactType)
        {
            switch (contactType)
            {
            case ContactTypes.Organization:
                return(new OrganizationContact());

            case ContactTypes.Person:
                return(new PersonContact());

            case ContactTypes.User:
                return(new UserContact());

            case ContactTypes.Carrier:
                return(new CarrierContact());

            case ContactTypes.Provider:
                return(new ProviderContact());

            default:
                throw new UnexpectedSwitchValueException(contactType);
            }
        }
コード例 #23
0
 public virtual Contact GetContactByType(ContactTypes contactType)
 {
     return(this.Contacts.Single(x => x.Contact.ContactTypeID == contactType).Contact);
 }
コード例 #24
0
        /// <summary>
        /// Load a contact from a file.
        /// </summary>
        /// <param name="fileName">The file that contains the contact data to load.</param>
        /// <exception cref="InvalidDataException">
        /// The specified file exists but doesn't doesn't represent a valid contact.
        /// </exception>
        /// <exception cref="FileNotFoundException">
        /// The specified file couldn't be found.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        /// The specified file couldn't be opened for an unknown reason.  It may be that it's
        /// opened within incompatible sharing permissions.  Retrying the operation at a later
        /// time may succeed.
        /// </exception>
        public Contact(string fileName)
        {
            Verify.IsNotNull(fileName, "fileName");
            Verify.IsApartmentState(ApartmentState.STA, _exceptionStringBadThreadId);

            // make the path absolute.
            fileName = IOPath.GetFullPath(fileName);

            _contactProperties = ContactLoader.GetContactFromFile(fileName);
            _sharedProperties = true;

            // Only really need to compute the hash if we change the contact...
            _sourceHash = _contactProperties.StreamHash;
            Path = fileName;
            Id = ContactId.GetRuntimeId(ContactIds.Default.Value, Path);
            _originalName = Names.Default.FormattedName;
            _type = GetTypeFromExtension(fileName);
        }
コード例 #25
0
        private void SaveDetails()
        {
            try
            {
                SRiCustomer customer = new SRiCustomer();
                if (ContactsDetails.Count == 0)
                {
                    customer.Name         = Lbl_Name.Text;
                    customer.RecordKeyVal = "";
                    customer.KeyVal       = "";
                    customer.Address      = EdAddress.Text;
                    Contact = new List <SRiContact>()
                    {
                        new SRiContact()
                        {
                            ContactType        = "PHONEH",
                            ContactDescription = "Phone",
                            ContactAddress     = Lbl_Phone.Text,
                            SRRecKeyVal        = "",
                            CustomerKeyVal     = "",
                            KeyVal             = ""
                        },
                        new SRiContact()
                        {
                            ContactType        = "EMAIL",
                            ContactDescription = "Email",
                            ContactAddress     = Lbl_Email.Text,
                            SRRecKeyVal        = "",
                            CustomerKeyVal     = "",
                            KeyVal             = ""
                        },
                        new SRiContact()
                        {
                            ContactType        = "MOBILE",
                            ContactDescription = "Mobile",
                            ContactAddress     = Lbl_Moblie.Text,
                            SRRecKeyVal        = "",
                            CustomerKeyVal     = "",
                            KeyVal             = ""
                        }
                    };
                    customer.CustomerType = ContactTypes.Where(x => x.Description == Pkr_CustomerType.Items[Pkr_CustomerType.SelectedIndex]).Select(x => x.Code).FirstOrDefault();
                    customer.Contacts     = Contact;

                    AppData.PropertyModel.SelectedRecord.Record.Record.Customers.Add(customer);
                }
                else
                {
                    if (AppData.PropertyModel.SelectedRecord.Record.Record.Customers.Count > 0)
                    {
                        foreach (var item in AppData.PropertyModel.SelectedRecord.Record.Record.Customers)
                        {
                            item.Name         = Lbl_Name.Text;
                            item.Address      = EdAddress.Text;
                            item.CustomerType =
                                ContactTypes.Where(
                                    x => x.Description == Pkr_CustomerType.Items[Pkr_CustomerType.SelectedIndex])
                                .Select(x => x.Code)
                                .FirstOrDefault();
                            foreach (var contcat in item.Contacts)
                            {
                                if (contcat.ContactType == "PHONEH")
                                {
                                    contcat.ContactAddress = Lbl_Phone.Text;
                                }
                                if (contcat.ContactType == "EMAIL")
                                {
                                    contcat.ContactAddress = Lbl_Email.Text;
                                }
                                if (contcat.ContactType == "MOBILE")
                                {
                                    contcat.ContactAddress = Lbl_Moblie.Text;
                                }
                            }
                        }
                    }
                }
                AppData.PropertyModel.SelectedRecord.CreateMappings();
                Exception error;
                AppData.PropertyModel.SaveCustomer(out error);
                _customerLists  = new CreateCustomerList();
                ContactsDetails = _customerLists.Details;
                // update UI in Listview
                SplitView.CenterPopupContent.DismisPopup();
                UpdateContact?.Invoke(ContactsDetails);
            }
            catch (Exception ex)
            {
                LogTracking.LogTrace(ex.ToString());
            }
        }
コード例 #26
0
 public Contact(ContactTypes tp, string contact)
 {
     ContactType     = tp;
     ContactGegevens = contact;
 }
コード例 #27
0
ファイル: ContactWatcher.cs プロジェクト: cystbear/contacts
            private void _PopulateKnownContacts(ContactTypes type)
            {
                Assert.IsNotNull(_loader);
                Assert.IsNotNull(_dispatcher);
                Assert.IsTrue(_dispatcher.CheckAccess());
                Assert.IsNotNull(_knownContacts);
                Assert.AreEqual(0, _knownContacts.Count);

                // Go through all contacts associated with the manager and make the mapping of file paths to the ContactIds. 
                foreach (var entry in _loader.GetPropertiesCollection(type))
                {
                    // Not using these contacts for very long.  Don't need the ContactManager parameter.
                    using (var contact = new Contact(null, entry.Value, entry.Key))
                    {
                        ContactInfo info = default(ContactInfo);
                        info.Id = contact.Id;
                        string pathNormalized = contact.Path.ToUpperInvariant();
                        info.LastWrite = File.GetLastWriteTime(pathNormalized);
                        _knownContacts.Add(pathNormalized, info);
                    }
                }
            }
コード例 #28
0
ファイル: ContactManager.cs プロジェクト: cystbear/contacts
        public IList<Contact> GetContactCollection(ContactTypes typeFilter)
        {
            _Validate(false);
            IList<Contact> list = new List<Contact>();
            foreach (KeyValuePair<string, IContactProperties> prop in _contactCache.GetPropertiesCollection(typeFilter))
            {
                Contact c = new Contact(this, prop.Value, prop.Key);
                list.Add(c);
            }

            return list;
        }
コード例 #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="startAbsolutePosition">Absolute position where the contact is plotted from</param>
        /// <param name="contactType"></param>
        /// <param name="polarCoord">Bearing and range from absolute position for the new contact</param>
        /// <param name="heading"></param>
        /// <param name="speed"></param>
        /// <param name="altitude"></param>
        /// <returns></returns>
        public IReferencePoint CreateContactAtPolarCoordinate(PointF startAbsolutePosition, ContactTypes contactType, PolarCoordinate polarCoord, double heading = 0.00, double speed = 0.00, double altitude = 0.00)
        {
            var relativePosition    = startAbsolutePosition.GetRelativePosition(RadarReceiver.ViewPortExtent);
            var newRelativePosition = CoordinateConverter.CalculatePointFromDegrees(relativePosition, polarCoord, CoordinateConverter.ROUND_DIGITS);
            var newAbsolutePosition = newRelativePosition.GetAbsolutePosition(RadarReceiver.ViewPortExtent);

            return(CreateContactAtPoint(newAbsolutePosition, contactType, heading, speed, altitude));
        }
コード例 #30
0
        /// <summary>
        /// Gets the result of a ContactType on a set of PhysicalAttributes.
        /// </summary>
        /// <param name="attackerPhysAttributes">The attacker's set of PhysicalAttributes.</param>
        /// <param name="contactType">The ContactType performed.</param>
        /// <param name="contactProperty">The ContactProperty of the contact.</param>
        /// <param name="victimPaybacks">The victim's set of Paybacks to test against.</param>
        /// <param name="attackerContactExceptions">The attacker's contact exceptions; the set PhysicalAttributes to ignore.</param>
        /// <returns>A ContactResultInfo of the interaction.</returns>
        public static ContactResultInfo GetContactResult(IList <PhysicalAttributes> attackerPhysAttributes, ContactTypes contactType, ContactProperties contactProperty, IList <PaybackHolder> victimPaybacks, params PhysicalAttributes[] attackerContactExceptions)
        {
            //Return the default value
            if (victimPaybacks == null || victimPaybacks.Count == 0)
            {
                return(ContactResultInfo.Default);
            }

            /*0. Initialize a list of Paybacks, called PaybackList
             * 1. Go through all of the Victim's Paybacks
             *   2. Check if the Payback's PaybackContacts contains the ContactType of the attack
             *      3a. If so, check if the Attacker has any ContactExceptions for the Payback's PhysAttribute
             *         4a. If so, ignore it and continue
             *         4b. If not, check if the Payback covers any of the attack's ContactProperties
             *            5a. If so, check if the Attacker has the same PhysAttribute as the Payback's
             *               6a. If so, examine the SamePhysAttrResult and go to 7a
             *               6b. If not, examine the PaybackContactResult and go to 7a
             *                  7a. If the ContactResult is a Failure, return that Payback value
             *                  7b. If the ContactResult is a Success, ignore it and continue
             *                  7c. If the ContactResult is a PartialSuccess, add it to PaybackList and continue
             *         4c. If not, ignore it and continue
             *      3b. If not, continue */

            //The Paybacks that will be combined
            List <PaybackHolder> combinedPaybacks = new List <PaybackHolder>();

            //Look through the Paybacks
            for (int i = 0; i < victimPaybacks.Count; i++)
            {
                PaybackHolder payback = victimPaybacks[i];

                //Check if the Payback covers this ContactType
                if (payback.PaybackContacts != null && payback.PaybackContacts.Contains(contactType) == true)
                {
                    //If there are contact exceptions for this PhysicalAttribute, ignore this Payback
                    if (attackerContactExceptions.Contains(payback.PhysAttribute) == true)
                    {
                        continue;
                    }

                    //Check if the Payback covers the ContactProperty
                    if (payback.ContactProperties != null && payback.ContactProperties.Contains(contactProperty) == false)
                    {
                        continue;
                    }

                    ContactResult contactResult = payback.PaybackContactResult;

                    //Check if the Attacker has the PhysicalAttribute the Payback is associated with, and adjust the ContactResult if so
                    if (attackerPhysAttributes.Contains(payback.PhysAttribute) == true)
                    {
                        contactResult = payback.SamePhysAttrResult;
                    }

                    //If a Failure, use this Payback
                    if (contactResult == ContactResult.Failure)
                    {
                        return(new ContactResultInfo(payback, contactResult));
                    }
                    //If a PartialSuccess, add it to the list
                    else if (contactResult == ContactResult.PartialSuccess)
                    {
                        combinedPaybacks.Add(payback);
                    }
                }
            }

            //Combine all the Paybacks in the list
            PaybackHolder finalPayback = PaybackHolder.CombinePaybacks(combinedPaybacks);

            return(new ContactResultInfo(finalPayback, finalPayback.PaybackContactResult));
        }
コード例 #31
0
        /// <summary>Internal only constructor for Contact.</summary>
        /// <param name="manager"></param>
        /// <param name="properties"></param>
        /// <param name="fileName"></param>
        internal Contact(ContactManager manager, IContactProperties properties, string fileName)
        {
            Assert.IsNotNull(properties);
            Verify.IsNeitherNullNorEmpty(fileName, "fileName");

            // Caller should have ensured this is canonicalized...
            Assert.AreEqual(fileName, IOPath.GetFullPath(fileName));

            _manager = manager;
            _contactProperties = properties;
            _sharedProperties = true;
            _sourceHash = _contactProperties.StreamHash;
            _type = GetTypeFromExtension(fileName);
            Path = fileName;
            Id = ContactId.GetRuntimeId(ContactIds.Default.Value, Path);
            _originalName = Names.Default.FormattedName;
        }
コード例 #32
0
        public static InteractionResult GetDamageInteractionOld(InteractionParamHolder interactionParam)
        {
            InteractionResult finalInteractionResult = new InteractionResult();

            BattleEntity attacker    = interactionParam.Attacker;
            BattleEntity victim      = interactionParam.Victim;
            ContactTypes contactType = interactionParam.ContactType;
            Elements     element     = interactionParam.DamagingElement;

            StatusChanceHolder[] statuses = interactionParam.Statuses;
            int  damage   = interactionParam.Damage;
            bool piercing = interactionParam.Piercing;

            //Get contact results
            ContactResultInfo contactResultInfo = victim.EntityProperties.GetContactResult(attacker, contactType);
            ContactResult     contactResult     = contactResultInfo.ContactResult;

            //Retrieve an overridden type of Elemental damage to inflict based on the Victim's PhysicalAttributes
            //(Ex. The Ice Power Badge only deals Ice damage to Fiery entities)
            ElementOverrideHolder newElement = attacker.EntityProperties.GetTotalElementOverride(victim);

            if (newElement.Element != Elements.Invalid)
            {
                //Add the number of element overrides to the damage if the element used already exists as an override and the victim has a Weakness
                //to the Element. This allows Badges such as Ice Power to deal more damage if used in conjunction with attacks
                //that deal the same type of damage (Ex. Ice Power and Ice Smash deal 2 additional damage total rather than 1).
                //If any new knowledge is discovered to improve this, this will be changed
                //Ice Power is the only Badge of its kind across the first two PM games that does anything like this
                if (element == newElement.Element && victim.EntityProperties.HasWeakness(element) == true)
                {
                    damage += newElement.OverrideCount;
                }

                element = newElement.Element;
            }

            /*Get the total damage dealt to the Victim. The amount of Full or Half Payback damage dealt to the Attacker
             * uses the resulting damage value from this because Payback uses the total damage that would be dealt to the Victim.
             * This occurs before factoring in elemental resistances/weaknesses from the Attacker*/
            ElementDamageResultHolder victimElementDamage = GetElementalDamage(victim, element, damage);

            int unscaledVictimDamage = victimElementDamage.Damage;

            //Subtract damage reduction (P-Up, D-Down and P-Down, D-Up Badges)
            unscaledVictimDamage -= victim.BattleStats.DamageReduction;

            //Check if the attack hit. If not, then don't consider defensive actions
            bool attackHit = interactionParam.CantMiss == true ? true : attacker.AttemptHitEntity(victim);

            //Defense added from Damage Dodge Badges upon a successful Guard
            int damageDodgeDefense = 0;

            //Defensive actions take priority. If the attack didn't hit, don't check for defensive actions
            BattleGlobals.DefensiveActionHolder?victimDefenseData = null;
            if (attackHit == true)
            {
                victimDefenseData = victim.GetDefensiveActionResult(unscaledVictimDamage, statuses, interactionParam.DamageEffect);
            }

            if (victimDefenseData.HasValue == true)
            {
                unscaledVictimDamage = victimDefenseData.Value.Damage;
                statuses             = victimDefenseData.Value.Statuses;
                //If the Defensive action dealt damage and the contact was direct
                //the Defensive action has caused a Failure for the Attacker (Ex. Superguarding)
                if ((contactType == ContactTypes.TopDirect || contactType == ContactTypes.SideDirect) && victimDefenseData.Value.ElementHolder.HasValue == true)
                {
                    contactResult = ContactResult.Failure;
                }

                //Factor in the additional Guard defense for all DefensiveActions (for now, at least)
                damageDodgeDefense = victim.GetEquippedBadgeCount(BadgeGlobals.BadgeTypes.DamageDodge);
            }

            //Subtract Defense on non-piercing damage
            if (piercing == false)
            {
                int totalDefense = victim.BattleStats.TotalDefense + damageDodgeDefense;
                unscaledVictimDamage -= totalDefense;
            }

            int scaledVictimDamage = unscaledVictimDamage;

            //Factor in Double Pain for the Victim
            scaledVictimDamage *= (1 + victim.GetEquippedBadgeCount(BadgeGlobals.BadgeTypes.DoublePain));

            //Factor in Last Stand for the Victim, if the Victim is in Danger or Peril
            if (victim.IsInDanger == true)
            {
                //PM rounds down, whereas TTYD rounds up. We're going with the latter
                //TTYD always ceilings the value (Ex. 3.2 turns to 4)
                int lastStandDivider = (1 + victim.GetEquippedBadgeCount(BadgeGlobals.BadgeTypes.LastStand));
                scaledVictimDamage = (int)Math.Ceiling(scaledVictimDamage / (float)lastStandDivider);
            }

            /*If the Victim is Invincible, ignore all damage and Status Effects
             * If the Attacker is Invincible, ignore all Payback damage and Status Effects
             *
             * It won't ignore the Payback's effects automatically; that has to be done manually by adding
             * contact exceptions or something else*/

            //Clamp Victim damage
            scaledVictimDamage = UtilityGlobals.Clamp(scaledVictimDamage, BattleGlobals.MinDamage, BattleGlobals.MaxDamage);

            #region Victim Damage Dealt

            //Calculating damage dealt to the Victim
            if (contactResult == ContactResult.Success || contactResult == ContactResult.PartialSuccess)
            {
                //Get the Status Effects to inflict on the Victim
                StatusChanceHolder[] victimInflictedStatuses = GetFilteredInflictedStatuses(victim, statuses);

                //Check if the Victim is Invincible. If so, ignore all damage and Status Effects
                if (victim.EntityProperties.GetAdditionalProperty <bool>(AdditionalProperty.Invincible) == true)
                {
                    scaledVictimDamage = 0;
                    victimElementDamage.InteractionResult = ElementInteractionResult.Damage;
                    victimInflictedStatuses = null;
                }

                finalInteractionResult.VictimResult = new InteractionHolder(victim, scaledVictimDamage, element,
                                                                            victimElementDamage.InteractionResult, contactType, piercing, victimInflictedStatuses, attackHit, DamageEffects.None);
            }

            #endregion

            #region Attacker Damage Dealt

            //Calculating damage dealt to the Attacker
            if (contactResult == ContactResult.Failure || contactResult == ContactResult.PartialSuccess)
            {
                //The damage the Attacker dealt to the Victim
                int           damageDealt   = unscaledVictimDamage;
                PaybackHolder paybackHolder = contactResultInfo.Paybackholder;

                //Override the PaybackHolder with a Defensive Action's results, if any
                if (victimDefenseData.HasValue == true && victimDefenseData.Value.ElementHolder.HasValue == true)
                {
                    damageDealt   = victimDefenseData.Value.ElementHolder.Value.Damage;
                    paybackHolder = new PaybackHolder(PaybackTypes.Constant, victimDefenseData.Value.ElementHolder.Value.Element, damageDealt);
                }

                //Get the damage done to the Attacker, factoring in Weaknesses/Resistances
                ElementDamageResultHolder attackerElementDamage = GetElementalDamage(attacker, paybackHolder.Element, damageDealt);

                //Get Payback damage - Payback damage is calculated after everything else, including Constant Payback.
                //However, it does NOT factor in Double Pain or any sort of Defense modifiers.
                int paybackDamage = paybackHolder.GetPaybackDamage(attackerElementDamage.Damage);

                //If Constant Payback, update the damage value to use the element
                if (paybackHolder.PaybackType == PaybackTypes.Constant)
                {
                    paybackDamage = GetElementalDamage(attacker, paybackHolder.Element, paybackDamage).Damage;
                }

                //Clamp Attacker damage
                attackerElementDamage.Damage = UtilityGlobals.Clamp(paybackDamage, BattleGlobals.MinDamage, BattleGlobals.MaxDamage);

                //Get the Status Effects to inflict
                StatusChanceHolder[] attackerInflictedStatuses = GetFilteredInflictedStatuses(attacker, paybackHolder.StatusesInflicted);

                //Check if the Attacker is Invincible. If so, ignore all damage and Status Effects
                if (attacker.EntityProperties.GetAdditionalProperty <bool>(AdditionalProperty.Invincible) == true)
                {
                    attackerElementDamage.Damage            = 0;
                    attackerElementDamage.InteractionResult = ElementInteractionResult.Damage;
                    attackerInflictedStatuses = null;
                }

                finalInteractionResult.AttackerResult = new InteractionHolder(attacker, attackerElementDamage.Damage, paybackHolder.Element,
                                                                              attackerElementDamage.InteractionResult, ContactTypes.None, true, attackerInflictedStatuses, true, DamageEffects.None);
            }

            #endregion

            return(finalInteractionResult);
        }
コード例 #33
0
 /// <summary>
 /// Get the file extensions associated with given ContactTypes.
 /// </summary>
 /// <param name="type">The ContactTypes to get the extensions for.
 /// This can be a bitwise combination of multiple ContactTypes.</param>
 /// <returns>
 /// Returns the file extensions associated with the given ContactType.
 /// If more than one type is contained in the parameter, the multiple
 /// extensions are returned in a string split by the pipe character ('|').
 /// </returns>
 /// <exception cref="System.ArgumentException">
 /// If the given type is ContactTypes.None or contains bits outside the valid
 /// range of ContactTypes.All.
 /// </exception>
 public static string GetExtensionsFromType(ContactTypes type)
 {
     return _GetExtensionsFromType(type, true);
 }
コード例 #34
0
        public IContact CreateContact(ISensor detectedBy, PointF position, double heading, double altitude, double speed, ContactTypes contactType, Action processContact = null)
        {
            Logger.Info($"{detectedBy} requesting to create a {contactType} contact at {position} traveling {heading}° at {speed} knts.");

            var newContact = (IContact)Activator.CreateInstance(typeof(Contact), new object[] { detectedBy, position });

            newContact.Heading              = heading;
            newContact.Altitude             = altitude;
            newContact.Speed                = speed;
            newContact.ContactType          = contactType;
            newContact.CustomUpdateDuration = 2500;
            return(newContact);
        }
コード例 #35
0
        public static void SendSubmissionEmail(Contact contactEntity, ContactTypes contactFormType)
        {
            string       toAddress    = contactFormType == ContactTypes.ContactUs ? Settings.ContactSubmissionEmailAddress : contactFormType == ContactTypes.HomeValuationRequest ? Settings.HomeValuationEmailAddress : Settings.MaintenanceRequestEmailAddress;
            string       templatePath = contactFormType == ContactTypes.ContactUs ? EmailTemplates.ContactSubmission : contactFormType == ContactTypes.HomeValuationRequest ? EmailTemplates.HomeValuation : EmailTemplates.MaintenanceRequest;
            string       propertyInfo = string.Empty;
            string       microsite    = string.Empty;
            ShowcaseItem showcaseItem = null;

            if (contactEntity.ShowcaseItemID.HasValue)
            {
                showcaseItem = Classes.Showcase.ShowcaseItem.GetByID(contactEntity.ShowcaseItemID.Value, new string[] { "Agent", "Showcase.CMMicrosite", "Team", "Address" });
                if (showcaseItem.AgentID.HasValue)
                {
                    toAddress = showcaseItem.Agent.Email;
                }
                else if (showcaseItem.TeamID.HasValue)
                {
                    toAddress = showcaseItem.Team.Email;
                }
                else
                {
                    toAddress = Classes.Contacts.Settings.DefaultAgentContactEmail;
                }
                templatePath = EmailTemplates.PropertyInfoRequest;
                propertyInfo = showcaseItem.Address.FormattedAddress + (showcaseItem.MlsID.HasValue ? "<br />MLS ID #" + showcaseItem.MlsID : "");
                microsite    = showcaseItem.Showcase.CMMicrosite.Name.ToLower().Replace(" ", "-");
            }
            else if (contactEntity.AgentID.HasValue)
            {
                Classes.Media352_MembershipProvider.User agent = Classes.Media352_MembershipProvider.User.GetByID(contactEntity.AgentID.Value, new[] { "UserOffice.Office" });
                if (agent.UserOffice != null && agent.UserOffice.Any(o => o.Office != null && o.Office.Active))
                {
                    toAddress = agent.Email;
                }
                else
                {
                    toAddress = Classes.Contacts.Settings.DefaultAgentContactEmail;
                }
                templatePath = EmailTemplates.ContactAgentSubmission;
            }
            else if (contactEntity.TeamID.HasValue)
            {
                Classes.Media352_MembershipProvider.Team team = Classes.Media352_MembershipProvider.Team.GetByID(contactEntity.TeamID.Value);
                toAddress    = team.Email;
                templatePath = EmailTemplates.ContactAgentSubmission;
            }

            if (string.IsNullOrWhiteSpace(toAddress))
            {
                return;
            }
            string      contactMethodName = ContactMethod.GetByID(contactEntity.ContactMethodID).Name;
            MailMessage email             = new MailMessage();

            email.IsBodyHtml = true;
            email.From       = new MailAddress(Globals.Settings.FromEmail);
            //TODO: Remove this when done testing.  Put in place to prevent spamming of meybohm agents
            if (System.Web.HttpContext.Current.IsDebuggingEnabled && toAddress.ToLower().EndsWith("@meybohm.com"))
            {
                toAddress = "*****@*****.**";
            }
            email.To.Add(toAddress);
            if (contactFormType == ContactTypes.PropertyInformation && toAddress != Settings.PropertyInfoCCEmailAddress)
            {
                email.CC.Add(Settings.PropertyInfoCCEmailAddress);
            }
            else if (contactFormType == ContactTypes.Agent && toAddress != Settings.AgentContactCCEmailAddress)
            {
                email.CC.Add(Settings.AgentContactCCEmailAddress);
            }

            Classes.StateAndCountry.Address addressEntity = null;
            if (contactEntity.AddressID.HasValue)
            {
                addressEntity = Classes.StateAndCountry.Address.GetByID(contactEntity.AddressID.Value, new string[] { "State" });
            }
            email.Body = EmailTemplateService.HtmlMessageBody(templatePath, new
            {
                FirstName     = contactEntity.FirstName,
                LastName      = contactEntity.LastName,
                Address1      = (addressEntity != null ? addressEntity.Address1 : string.Empty),
                Address2      = (addressEntity != null ? addressEntity.Address2 : string.Empty),
                City          = (addressEntity != null ? addressEntity.City : string.Empty),
                State         = (addressEntity != null ? addressEntity.State.Name : string.Empty),
                Zip           = (addressEntity != null ? addressEntity.Zip : string.Empty),
                Message       = contactEntity.Message,
                ContactMethod = contactMethodName,
                Email         = contactEntity.Email,
                PhoneOrEmail  = (contactEntity.ContactMethodID == (int)ContactMethods.Email ?"": "Phone: " + contactEntity.Phone),
                ContactTime   = ContactTime.GetByID(contactEntity.ContactTimeID).Name,
                PropertyInfo  = propertyInfo,
                Microsite     = microsite
            });
            string subjectText = contactEntity.ShowcaseItemID.HasValue ? "Property Information Request" : contactFormType == ContactTypes.ContactUs ? "Contact Form Submission" : contactFormType == ContactTypes.HomeValuationRequest ? "Home Valuation Request" : contactFormType == ContactTypes.MaintenanceRequest ? "Maintenance Request" : "Contact Agent Submission";

            if (showcaseItem != null)
            {
                if (showcaseItem.ShowcaseID == (int)MeybohmShowcases.AugustaRentalHomes || showcaseItem.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes)
                {
                    subjectText += " - Lease";
                }
            }
            email.Subject = Globals.Settings.SiteTitle + " - " + subjectText;

            // Apply MLS ID and address information to the subject line if this is a property information
            // request.
            if (showcaseItem != null && (showcaseItem.MlsID != null || showcaseItem.Address != null))
            {
                string subjectDetails = "[";

                if (showcaseItem.MlsID != null)
                {
                    subjectDetails += showcaseItem.MlsID;
                }

                if (showcaseItem.MlsID != null && showcaseItem.Address != null)
                {
                    subjectDetails += " - ";
                }

                if (showcaseItem.Address != null)
                {
                    subjectDetails += showcaseItem.Address.Address1;
                }

                subjectDetails += "] Property Information Request";

                if (showcaseItem.ShowcaseID == (int)MeybohmShowcases.AugustaRentalHomes || showcaseItem.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes)
                {
                    subjectDetails += " - Lease";
                }

                email.Subject = subjectDetails;
            }

            SmtpClient smtp = new SmtpClient();

            smtp.Send(email);
        }
コード例 #36
0
 private static bool _IsValidSingleContactType(ContactTypes type, bool isUnknownOK)
 {
     return type == ContactTypes.Contact
         || type == ContactTypes.Organization
         || type == ContactTypes.Group
         || (isUnknownOK
             ? (type == ContactTypes.None)
             : false);
 }
コード例 #37
0
        public static MailContact[] AddContactType(this IEnumerable <MailContact> contacts, ContactTypes type)
        {
            if (contacts == null || !contacts.Any())
            {
                return(new MailContact[] { });
            }
            var list = new List <MailContact>();

            foreach (var contact in contacts)
            {
                contact.ContactType = type;
                list.Add(contact);
            }
            return(list.ToArray());
        }
コード例 #38
0
        private static string _GetExtensionsFromType(ContactTypes type, bool allowMultiset)
        {
            // Verify that the type doesn't contain bits outside the valid range and it contains
            // at least one bit inside the valid range.
            if ((ContactTypes.None != (type & ~ContactTypes.All))
                || (ContactTypes.None == (type & ContactTypes.All)))
            {
                throw new ArgumentException("The provided ContactType is not within the valid range.", "type");
            }

            if (_typeMap.Count == 0)
            {
                _typeMap.Add(ContactTypes.Organization, ".organization");
                _typeMap.Add(ContactTypes.Contact, ".contact");
                _typeMap.Add(ContactTypes.Group, ".group");
            }

            string ext;
            if (!_typeMap.TryGetValue(type, out ext) && allowMultiset)
            {
                ext = null;
                // Not a single value, check if we should try to compose a set.
                if ((type & ContactTypes.All) != 0)
                {
                    var extBuilder = new StringBuilder();
                    foreach (ContactTypes key in _typeMap.Keys)
                    {
                        if ((type & key) != 0)
                        {
                            extBuilder.Append(_typeMap[key]).Append("|");
                        }
                    }
                    // If nothing is returned then it's bad args.
                    if (0 != extBuilder.Length)
                    {
                        ext = extBuilder.ToString(0, extBuilder.Length - 1);
                    }
                }
            }

            // Checked this above.  The type should have yielded a result.
            Assert.Implies(allowMultiset, null != ext);

            return ext;
        }
コード例 #39
0
ファイル: ContactLoader.cs プロジェクト: cystbear/contacts
        public IEnumerable<KeyValuePair<string, IContactProperties>> GetPropertiesCollection(ContactTypes typeFilter)
        {
            if (typeFilter == ContactTypes.None)
            {
                // Not a valid filter.
                // Not appropriate to throw an exception but not going to yield any results.
                yield break;
            }

            // This will throw exceptions for invalid enumeration values.
            string[] extensions = Contact.GetExtensionsFromType(typeFilter).Split('|');
            Assert.AreNotEqual(0, extensions.Length);

            foreach (string ext in extensions)
            {
                // Should be of the format ".extension".  Need to change to "*.extension" for FindFile.
                Assert.AreEqual('.', ext[0]);
                string findExt = "*" + ext;

                // DirectoryInfo.GetDirectories/GetFiles doesn't work here.
                // For one, the recursive version of GetDirectories doesn't check for reparse points,
                //     so it can end up in an infinite loop.
                // Secondly, GetFiles goes through and returns the full list, and since this enumerator
                //     is likely to bail early that's unnecessarily expensive.
                // So instead this is done mostly manually, and FindFirstFile/FindNextFile are P/Invoked.

                foreach (FileInfo file in FileWalker.GetFiles(new DirectoryInfo(_manager.RootDirectory), findExt, _manager.UseSubfolders))
                {
                    string path = file.FullName;
                    string normalizedPath = path.ToUpperInvariant();

                    // Try to find a cached copy of the properties.
                    // If it's not available go to disk.
                    IContactProperties properties;
                    if (!_TryGetCachedFile(normalizedPath, out properties))
                    {
                        DateTime lastModifiedUtc;
                        if (_TryLoadPropertiesFromFile(path, out properties, out lastModifiedUtc))
                        {
                            // If we got a contact from the file then store it so we don't have to
                            // go to disk next time.
                            _fileCache.Add(normalizedPath, new _CacheEntry(path, lastModifiedUtc, properties));
                        }
                    }
                    if (null != properties)
                    {
                        yield return new KeyValuePair<string, IContactProperties>(path, properties);
                    }
                }
            }
        }
コード例 #40
0
ファイル: ContactManager.cs プロジェクト: cystbear/contacts
 /// <summary>
 /// Create a new Contact associated with this manager.
 /// </summary>
 /// <param name="type">The type of contact to create.  Must be a valid enumeration value.</param>
 /// <returns>Returns a new Contact associated with this manager.</returns>
 /// <remarks>
 /// This is similar to creating a contact with Contact's constructor, except that CommitChanges
 /// will work despite that there is no file initially backing the contact.  After CommitChanges is
 /// called on the contact can later be loaded by Id with this manager.<para/>
 /// The contact is not considered to be part of this manager until it has been committed.
 /// </remarks>
 public Contact CreateContact(ContactTypes type)
 {
     return new Contact(this, type);
 }
コード例 #41
0
        /// <summary>
        /// Internal only constructor for ContactManager.
        /// </summary>
        /// <param name="manager">The associated ContactManager instance.</param>
        /// <param name="type">The type of the contact to create.</param>
        /// <remarks>
        /// This allows the contacts returned by IContactCollection to be managed by this class.
        /// The manager is associated with the contact, which allows for Save to be called without
        /// the contact being initially backed by a path.
        /// </remarks>
        internal Contact(ContactManager manager, ContactTypes type)
        {
            Verify.IsApartmentState(ApartmentState.STA, _exceptionStringBadThreadId);
            if (!_IsValidSingleContactType(type, false))
            {
                throw new ArgumentException("The provided type must be of a legal single value (also not ContactTypes.None).", "type");
            }

            _manager = manager;

            _contactProperties = new WriteableContactPropertiesAlias();
            // The IContactProperties is disposable by this object.
            //_sharedProperties = false;

            // New contact, no file name associated with the Id.
            Id = ContactId.GetRuntimeId(ContactIds.Default.Value, null);
            // _path = null;

            _originalName = string.Empty;
            _type = type;

            // New contact, so no worries of conflicting changes on save.
            // _sourceHash = null;
        }
コード例 #42
0
 public Contact(ContactTypes type)
     : this((ContactManager)null, type)
 {
 }
コード例 #43
0
        /// <summary>
        /// Load a contact from a stream.
        /// </summary>
        /// <param name="stream">The stream with the Contact contents to load.</param>
        /// <param name="type">
        /// The type of the contact to create.  ContactTypes.None is valid for this constructor.
        /// </param>
        /// <remarks>
        /// This is the only Contact constructor where ContactTypes.None is a valid type parameter.
        /// </remarks>
        public Contact(Stream stream, ContactTypes type)
        {
            Verify.IsNotNull(stream, "stream");
            Verify.IsApartmentState(ApartmentState.STA, _exceptionStringBadThreadId);
            if (!_IsValidSingleContactType(type, true))
            {
                throw new ArgumentException("ContactType must be a valid single value for this constructor (ContactTypes.None is OK).", "type");
            }

            _type = type;

            //
            // Default values are implicitly set by the runtime (CodeAnalysis tools flag unnecessary default initializations).
            //

            // Loading a contact from a stream, so there's no path and the user can't commit changes directly.
            // _sourceHash = null;
            // _path = null;
            // Shouldn't need this either (only used for Commit)
            // _originalName = null;

            stream.Position = 0;

            // No reason to assume that because we're being loaded from a stream that this
            // is going to be modified.  Go ahead and delay building the DOM.
            // CONSDIER: Adding a flag indicating intention to write.
            _contactProperties = new ReadonlyContactProperties(stream);

            // The IContactProperties is disposable by this object.
            //_sharedProperties = false;

            Id = ContactId.GetRuntimeId(ContactIds.Default.Value, null);
        }
コード例 #44
0
ファイル: ContactWatcher.cs プロジェクト: cystbear/contacts
            public ContactWatcherSingular(Dispatcher dispatcher, ContactLoader loader, string directory, ContactTypes type, ContactWatcherEventCallback callback)
            {
                Assert.IsNotNull(dispatcher);
                // It's expected that this is created on the same thread as the manager,
                // so don't need to go through the dispatcher for methods invoked in the constructor.
                Assert.IsTrue(dispatcher.CheckAccess());
                Assert.IsNotNull(loader);
                Assert.IsFalse(string.IsNullOrEmpty(directory));
                Assert.IsNotNull(callback);
                Assert.IsTrue(Enum.IsDefined(typeof(ContactTypes), type));
                Assert.AreNotEqual(ContactTypes.All, type);
                Assert.AreNotEqual(ContactTypes.None, type);

                _dispatcher = dispatcher;
                _rootDirectory = directory;
                _loader = loader;
                _notify = callback;
                _findExtension = "*" + Contact.GetExtensionsFromType(type);

                // This is why creating this object is expensive:
                // In order to be able to give accurate change notifications we need to know all the contacts that are present at the beginning.
                _knownContacts = new Dictionary<string, ContactInfo>();

                // _pushedFrames = 0;
                _frame = new DispatcherFrame
                {
                    Continue = false
                };

                // Create the timer, but only signal it if we're going to need to reprocess an update.
                _timer = new Timer();
                _timer.Tick += delegate
                {
                    if (!_stopProcessing)
                    {
                        // Not invoked by the FileSystemWatcher, so don't push a frame here.
                        _dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)_ReprocessPendingUpdate);
                    }
                };
                _timer.Interval = TimeSpan.FromMilliseconds(_TimerMsDelay);
                _timer.IsEnabled = false;

                _PopulateKnownContacts(type);

                _fileWatch = new FileSystemWatcher(_rootDirectory, _findExtension)
                {
                    IncludeSubdirectories = true,
                    NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Attributes,
                };

                // There's some extra indirection required here because the manager requires thread affinity.
                _fileWatch.Changed += FileSystemWatcher_OnChanged;
                _fileWatch.Created += FileSystemWatcher_OnCreated;
                _fileWatch.Deleted += FileSystemWatcher_OnDeleted;
                _fileWatch.Renamed += FileSystemWatcher_OnRenamed;
                _fileWatch.EnableRaisingEvents = true;
            }
コード例 #45
0
 /// <summary>
 /// Creates a Contact
 /// </summary>
 /// <param name="detectedBy"></param>
 /// <param name="position"></param>
 /// <param name="heading"></param>
 /// <param name="altitude"></param>
 /// <param name="speed"></param>
 /// <param name="contactType"></param>
 /// <param name="processContact"></param>
 /// <returns></returns>
 public Contact Create(ISensor detectedBy, PointF position, double heading, double altitude, double speed, ContactTypes contactType, Action processContact = null)
 {
     return(new Contact(detectedBy, position)
     {
         Heading = heading,
         Altitude = altitude,
         Speed = speed,
         ContactType = contactType
     });
 }