Exemplo n.º 1
1
        public void SyncTestItemsIList(ref IList<TestItem> source, ref IList<TestItem> destination)
        {
            foreach (var item in source)
            {
                var dest = destination.SingleOrDefault(d => d.Id == item.Id);
                if (dest == null)
                {
                    destination.Add(item);
                }
                else
                {
                    if (dest.Sync < item.Sync)
                    {
                         destination[destination.IndexOf(dest)] = item.Clone();
                    }
                }
            }

            foreach (var item in destination)
            {
                var sour = source.SingleOrDefault(s => s.Id == item.Id);
                if (sour == null)
                {
                    source.Add(item);
                }
                else
                {
                    if (sour.Sync < item.Sync)
                    {
                        source[source.IndexOf(sour)] = item.Clone();
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                Entry baseEntry = null;
                if (!string.IsNullOrEmpty(entry.Type)) {
                    // find the base entry
                    baseEntry = entries.SingleOrDefault(e => e.Name.ToLowerInvariant() == entry.Type.ToLowerInvariant());
                }

                RenderEntry(entry, baseEntry);
            }

            Messages.WriteLine("Generating jQueryUI base files.");
            RenderEventHandler();
            RenderBox();
            RenderSize();
            RenderEffectExtensionMethods(entries.Where(e => e.Category == "effects" && e.Name != "effect"));
            RenderInteractionOrWidgetExtensionMethods("Interaction", entries.Where(e => e.Category == "interactions"));
            RenderInteractionOrWidgetExtensionMethods("Widget", entries.Where(e => e.Category == "widgets" && e.Name != "widget"));
            RenderPositionExtensionMethods(entries.Single(e => e.Name == "position"));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                Entry baseEntry = null;
                if (!string.IsNullOrEmpty(entry.Type)) {
                    // find the base entry
                    baseEntry = entries.SingleOrDefault(e => e.Name.ToLower() == entry.Type.ToLower());
                }

                RenderEntry(entry, baseEntry);
            }

            RenderEventHandler();
            RenderJQueryUI();
            RenderWidgetType(entries);
        }
        private async Task AddClaim(ApplicationUser user, IList<Claim> claims, string claim)
        {
            var roleType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";

            if (claims.SingleOrDefault(x => x.Type == roleType && x.Value == claim) == null)
                await _userManager.AddClaimAsync(user, new Claim(roleType, claim, null));
        }
        public void Execute(string[] args, IList<Directory> directoryies)
        {
            if(args.Length != 1)
                throw new ArgumentException();

            string[] fileinfos = args[0].Split('/');

            if(fileinfos.Length != 2)
                throw new ArgumentException();

            var dirname = fileinfos[0];
            var filename = fileinfos[1];

            var targetdir = directoryies.SingleOrDefault(dir =>
            {
                return dir.Name.Equals(dirname);
            });

            if(targetdir == null)
                throw new Exception("Directoryが存在しません");

            if(targetdir.Contains(filename))
                throw new Exception("Fileがすでに存在します");

            targetdir.Add(new File(filename);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initialises a new instance of the <see cref="TableInfo"/> class.
        /// </summary>
        /// <param name="columns">The columns that are mapped for the table.</param>
        /// <param name="identifierStrategy">The identifier strategy used by the table.</param>
        /// <param name="name">The name of the table.</param>
        /// <param name="schema">The database schema the table exists within (e.g. 'dbo'); otherwise null.</param>
        /// <exception cref="ArgumentNullException">Thrown if columns or name are null.</exception>
        /// <exception cref="MappingException">Thrown if no there is a problem with the column mappings.</exception>
        public TableInfo(
            IList<ColumnInfo> columns,
            IdentifierStrategy identifierStrategy,
            string name,
            string schema)
        {
            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.columns = new ReadOnlyCollection<ColumnInfo>(columns);
            this.identifierStrategy = identifierStrategy;
            this.name = name;
            this.schema = schema;

            this.ValidateColumns();

            this.identifierColumn = columns.SingleOrDefault(c => c.IsIdentifier);

            this.insertColumnCount = columns.Count(c => c.AllowInsert);
            this.updateColumnCount = columns.Count(c => c.AllowUpdate);
        }
Exemplo n.º 7
0
        private void RmDir(string dirname, IList<Directory> directoryies)
        {
            var dirobj = directoryies.SingleOrDefault(dir => dir.Name.Equals(dirname));
            if(dirobj == null)
                new Exception("Directoryが存在しません");

            directoryies.Remove(dirobj);
        }
 /// <summary>
 /// Returns the drop down list corresponding to the property, if it exists.
 /// </summary>
 private DropDownList GetDropDownList(
     ModelMetadata propertyMetadata,
     IList <DropDownList> dropDownLists)
 {
     return(dropDownLists?.SingleOrDefault
            (
                d => d.PropertyName == propertyMetadata.PropertyName
            ));
 }
        private IBinaryInfo BuildBinaryInfo(IAddInfo addInfo, IList<IPackageEntry> fileInfos, IPackageEntry binaryFileInfo)
        {
            var binaryInfo = new BinaryInfo(addInfo);

            binaryInfo.Name = Path.GetFileNameWithoutExtension(binaryFileInfo.FullPath);
            binaryInfo.Type = Path.GetExtension(binaryFileInfo.FullPath).Substring(1);
            binaryInfo.File = binaryFileInfo;

            using (var stream = binaryFileInfo.Stream)
            {
                binaryInfo.Hash = binaryStoreManager.ReadBinaryHash(stream);
                stream.Seek(0, SeekOrigin.Begin);
                binaryInfo.SymbolHash = binaryStoreManager.ReadPdbHash(stream);
            }

            string symbolName = Path.ChangeExtension(binaryFileInfo.FullPath, "pdb");
            var symbolFileInfo = fileInfos.SingleOrDefault(s => s.FullPath == symbolName);
            if (symbolFileInfo != null)
            {
                var symbolInfo = new SymbolInfo(binaryInfo);
                symbolInfo.Type = Path.GetExtension(symbolFileInfo.FullPath).Substring(1);
                symbolInfo.File = symbolFileInfo;

                using (var stream = symbolFileInfo.Stream)
                {
                    symbolInfo.Hash = symbolStoreManager.ReadHash(stream);
                }

                symbolInfo.SourceInfos = sourceDiscover.FindSources(fileInfos, binaryInfo, symbolInfo).OrderBy(s => s.KeyPath).ToArray();
                binaryInfo.SymbolInfo = symbolInfo;
            }

            string documentationName = Path.ChangeExtension(binaryFileInfo.FullPath, "xml");
            var documentationFileInfo = fileInfos.SingleOrDefault(s => s.FullPath == documentationName);
            if (documentationFileInfo != null)
            {
                var documentationInfo = new DocumentationInfo(binaryInfo);
                documentationInfo.Type = Path.GetExtension(documentationFileInfo.FullPath).Substring(1);
                documentationInfo.File = documentationFileInfo;
                binaryInfo.DocumentationInfo = documentationInfo;
            }

            return binaryInfo;
        }
Exemplo n.º 10
0
 internal static void ToApplicationRelativeUrl(IList<AttributeNode> attributes, string name)
 {
     var node = attributes.SingleOrDefault(x => x.Name == name);
     if ((node != null) && (!node.Value.StartsWith("#")))
     {
         var newNode = AddMethodCallingToAttributeValue(node, Constants.TOAPPLICATIONRELATIVEURL);
         attributes.Remove(node);
         attributes.Add(newNode);
     }
 }
Exemplo n.º 11
0
 internal static void AddApplyPathModifier(IList<AttributeNode> attributes, string name)
 {
     //Response.ApplyAppPathModifier used not only to add cookie, it also resolves urls with ~.
     var node = attributes.SingleOrDefault(x => x.Name == name);
     if ((node != null)&&(!node.Value.StartsWith("#")))
     {
         var newNode = AddMethodCallingToAttributeValue(AddMethodCallingToAttributeValue(node,Constants.TOAPPLICATIONRELATIVEURL), Constants.APPLYAPPPATHMODIFIER);
         attributes.Remove(node);
         attributes.Add(newNode);
     }
 }
Exemplo n.º 12
0
        private void RmFile(string dirname, string filename, IList<Directory> directoryies)
        {
            var dirobj = directoryies.SingleOrDefault(dir => dir.Name.Equals(dirname));
            if(dirobj == null)
                throw new Exception("Fileが存在しません");

            if(!dirobj.Contains(filename))
                throw new Exception("Fileが存在しません");

            dirobj.Remove(filename);
        }
Exemplo n.º 13
0
 public bool Validate(string username, string password)
 {
     if (_userAccessList?.SingleOrDefault(e => e.Username.Contains(username, StringComparison.InvariantCultureIgnoreCase) && e.IsPassword(password)) != null)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 14
0
        private ConfigSection GetOrCreateSection( IList<ConfigSection> sections, string sectionName )
        {
            var section = sections.SingleOrDefault( sec => sec.Name == sectionName );
            if ( section == null )
            {
                section = new ConfigSection( sectionName );
                sections.Add( section );
            }

            return section;
        }
Exemplo n.º 15
0
        private void MvDir(string dirname, string newdirname, IList<Directory> directoryies)
        {
            bool isExist = directoryies.Any(dir => dir.Name.Equals(newdirname));
            if(isExist)
                throw new Exception("移動先のDirectoryは存在します");

            var dirobj = directoryies.SingleOrDefault(dir => dir.Name.Equals(dirname));
            if(dirobj == null)
                throw new Exception("移動元のDirectoryは存在します");

            dirobj.Name = newdirname;
        }
Exemplo n.º 16
0
 private void AddOrOverwrite( IList<ConfigSection> sections, ConfigSection section )
 {
     var existingSection = sections.SingleOrDefault( sec => sec.Name == section.Name );
     if ( existingSection != null )
     {
         existingSection.Properties.Clear();
         existingSection.Properties.AddRange( section.Properties );
     }
     else
     {
         sections.Add( section );
     }
 }
Exemplo n.º 17
0
        private void MvFile(string dirname, string filename, 
            string newdirname, string newfilename, IList<Directory> directoryies)
        {
            var srcdir = directoryies.SingleOrDefault(dir => dir.Name.Equals(dirname));
            if(srcdir == null)
                throw new Exception("移動元Fileが存在しません");

            if(!srcdir.Contains(filename))
                throw new Exception("移動元Fileが存在しません");

            var dstdir = directoryies.SingleOrDefault(dir => dir.Name.Equals(dirname));
            if(dstdir == null)
                throw new Exception("移動元Fileが存在しません");

            if(!dstdir.Contains(filename))
                throw new Exception("移動元Fileが存在しません");

            var file = srcdir.Get(filename);
            srcdir.Remove(filename);
            file.Name = newfilename;
            dstdir.Add(file);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Parse salary information from the XML of a single TribePad job advert
        /// </summary>
        /// <param name="sourceData">XML for a single job, with a root element of &lt;job&gt;</param>
        /// <returns></returns>
        public async Task <Salary> ParseSalary(string sourceData)
        {
            await EnsureLookups();

            var jobXml = XDocument.Parse(sourceData);

            var salary = new Salary();

            var hourlyFrequencyId = _salaryFrequencies?.SingleOrDefault(x => x.Text == "Hourly")?.LookupValueId;
            var frequencyId       = jobXml.Root.Element("salary_frequency")?.Value;

            if (frequencyId == hourlyFrequencyId)
            {
                if (Decimal.TryParse(jobXml.Root.Element("salary_from").Value, out var salaryFrom))
                {
                    salary.MinimumHourlyRate = salaryFrom;
                }
                if (Decimal.TryParse(jobXml.Root.Element("salary_to").Value, out var salaryTo))
                {
                    salary.MaximumHourlyRate = salaryTo;
                }

                SetSalaryFromData(jobXml, salary,
                                  x => x.MinimumHourlyRate == 0 && x.MaximumHourlyRate == 0,
                                  x => (x.MinimumHourlyRate == x.MaximumHourlyRate || x.MaximumHourlyRate < x.MinimumHourlyRate),
                                  x => $"£{x.MinimumHourlyRate?.ToString("n2")} per annum",
                                  x => $"£{x.MinimumHourlyRate?.ToString("n2")} to £{x.MaximumHourlyRate?.ToString("n2")} per hour"
                                  );
            }
            else
            {
                if (Decimal.TryParse(jobXml.Root.Element("salary_from").Value, out var salaryFrom))
                {
                    salary.MinimumSalary = salaryFrom;
                }
                if (Decimal.TryParse(jobXml.Root.Element("salary_to").Value, out var salaryTo))
                {
                    salary.MaximumSalary = salaryTo;
                }

                SetSalaryFromData(jobXml, salary,
                                  x => x.MinimumSalary == 0 && x.MaximumSalary == 0,
                                  x => (x.MinimumSalary == x.MaximumSalary || x.MaximumSalary < x.MinimumSalary),
                                  x => $"£{x.MinimumSalary?.ToString("n2").Replace(".00", string.Empty)} per annum",
                                  x => $"£{x.MinimumSalary?.ToString("n2").Replace(".00", string.Empty)} to £{x.MaximumSalary?.ToString("n2").Replace(".00", string.Empty)} per annum"
                                  );
            }

            return(salary);
        }
 /// <summary>
 /// Gets the entry.
 /// </summary>
 /// <param name="workingMemory">The working memory.</param>
 /// <param name="contextObjectType">Type of the context object.</param>
 /// <param name="name">The name of the context object.</param>
 /// <returns>A <see cref="ContextEntry"/> or null if no entry exists.</returns>
 public ContextEntry GetEntry( IList<ContextEntry> workingMemory, Type contextObjectType, string name = null )
 {
     return workingMemory.SingleOrDefault (
         r =>
             {
                 var compareType = r.ContextObject.GetType ();
                 if ( r.ContextObject is INHibernateProxy )
                 {
                     var proxy = r.ContextObject as INHibernateProxy;
                     compareType = proxy.HibernateLazyInitializer.PersistentClass;
                 }
                 return compareType.Equals ( contextObjectType ) && ( name == null || r.Name == name );
             } );
 }
        private void SetSalaryFromData(XDocument jobXml, Salary salary,
                                       Func <Salary, bool> salaryIsZero, Func <Salary, bool> maxPayIsLessThanOrEqualToMinPay,
                                       Func <Salary, string> salaryExactValue, Func <Salary, string> salaryRange)
        {
            if (salaryIsZero(salary))
            {
                // 0 can mean 0 was entered, or nothing was entered
                var displayText = jobXml.Root.Element("salaryText")?.Value;
                if (!String.IsNullOrEmpty(displayText))
                {
                    salary.MinimumHourlyRate = null;
                    salary.MaximumHourlyRate = null;
                    salary.MinimumSalary     = null;
                    salary.MaximumSalary     = null;
                    salary.SalaryRange       = displayText;
                }
                else
                {
                    // If no salaryText, is there a pay grade?
                    JobsLookupValue payGrade = null;
                    if (!String.IsNullOrEmpty(_payGradeFieldName))
                    {
                        payGrade = _payGrades?.SingleOrDefault(x => x.LookupValueId == jobXml.Root.Element(_payGradeFieldName)?.Element("answer")?.Value);
                    }

                    // If not, it's voluntary
                    if (payGrade != null)
                    {
                        salary.MinimumHourlyRate = null;
                        salary.MaximumHourlyRate = null;
                        salary.MinimumSalary     = null;
                        salary.MaximumSalary     = null;
                        salary.SalaryRange       = payGrade.Text;
                    }
                    else
                    {
                        salary.SalaryRange = "Voluntary";
                    }
                }
            }
            else if (maxPayIsLessThanOrEqualToMinPay(salary))
            {
                salary.SalaryRange = salaryExactValue(salary);
            }
            else
            {
                salary.SalaryRange = salaryRange(salary);
            }
        }
        private static Dictionary<string, string> GetMapForSubproperty(List<PropInfo> viewModelProps, IList<PropInfo> propsToCompare)
        {
            var map = new Dictionary<string, string>();
            foreach (var vmProp in viewModelProps)
            {
                var match = propsToCompare.SingleOrDefault(x => vmProp.Name.StartsWith(x.Name));

                if (match != null)
                {
                    map.Add(vmProp.Name, string.Format("{0}.{1}", match.Name, vmProp.Name.Replace(match.Name, string.Empty)));
                }
            }

            return map;
        }
Exemplo n.º 22
0
 public override void TakeDamage(IList<PlayerDamage> damages)
 {
     //TODO: Rules clarification: Heroic action turns 9 into 10?
     var interceptorDamages = damages.SingleOrDefault(damage => damage.PlayerDamageType == PlayerDamageType.InterceptorsSingle);
     if (interceptorDamages != null)
     {
         var strongerInterceptorDamages = new PlayerDamage(
             9,
             PlayerDamageType.InterceptorsSingle,
             interceptorDamages.Range,
             interceptorDamages.ZoneLocations);
         damages.Remove(interceptorDamages);
         damages.Add(strongerInterceptorDamages);
         sittingDuck.KnockOutPlayers(new [] {StationLocation.Interceptor});
     }
     base.TakeDamage(damages);
 }
Exemplo n.º 23
0
        /// <summary>
        /// Возвращает цепочку родительских сущностей
        /// </summary>
        /// <param name="entityTypeCode">код типа сущности</param>
        /// <param name="entityId">идентификатор сущности</param>
        /// <param name="parentEntityId">идентификатор родительской сущности</param>
        /// <param name="oneLevel"></param>
        /// <returns>цепочка сущностей</returns>
        internal static IEnumerable <EntityInfo> GetParentsChain(string entityTypeCode, long entityId, long?parentEntityId = null, bool oneLevel = false)
        {
            IList <EntityInfo> result = null;

            using (new QPConnectionScope())
            {
                var dt = Common.GetBreadCrumbsList(QPConnectionScope.Current.DbConnection, QPContext.CurrentUserId, entityTypeCode, entityId, parentEntityId, oneLevel);
                if (dt != null)
                {
                    result = dt.AsEnumerable().Select(EntityInfo.Create).ToList();
                }
            }

            var customerCodeInfo = result?.SingleOrDefault(n => n.Code == EntityTypeCode.CustomerCode);

            if (customerCodeInfo != null)
            {
                customerCodeInfo.Title = QPContext.CurrentCustomerCode;
            }

            return(result);
        }
        /// <summary>
        /// Parse salary information from the XML of a single TribePad job advert
        /// </summary>
        /// <param name="sourceData">XML for a single job, with a root element of &lt;job&gt;</param>
        /// <returns></returns>
        public async Task <Salary> ParseSalary(string sourceData)
        {
            await EnsureLookups();

            var jobXml = XDocument.Parse(sourceData);

            var salary = new Salary();

            var hourlyFrequencyId = _salaryFrequencies?.SingleOrDefault(x => x.Text == "Hourly")?.LookupValueId;
            var frequencyId       = jobXml.Root.Element("salary_frequency")?.Value;

            if (frequencyId == hourlyFrequencyId)
            {
                salary.MinimumHourlyRate = Decimal.Parse(jobXml.Root.Element("salary_from").Value);
                salary.MaximumHourlyRate = Decimal.Parse(jobXml.Root.Element("salary_to").Value);

                SetSalaryFromData(jobXml, salary,
                                  x => x.MinimumHourlyRate == 0 && x.MaximumHourlyRate == 0,
                                  x => (x.MinimumHourlyRate == x.MaximumHourlyRate || x.MaximumHourlyRate < x.MinimumHourlyRate),
                                  x => $"£{x.MinimumHourlyRate?.ToString("n2")} per annum",
                                  x => $"£{x.MinimumHourlyRate?.ToString("n2")} to £{x.MaximumHourlyRate?.ToString("n2")} per hour"
                                  );
            }
            else
            {
                salary.MinimumSalary = Int32.Parse(jobXml.Root.Element("salary_from").Value, CultureInfo.InvariantCulture);
                salary.MaximumSalary = Int32.Parse(jobXml.Root.Element("salary_to").Value, CultureInfo.InvariantCulture);

                SetSalaryFromData(jobXml, salary,
                                  x => x.MinimumSalary == 0 && x.MaximumSalary == 0,
                                  x => (x.MinimumSalary == x.MaximumSalary || x.MaximumSalary < x.MinimumSalary),
                                  x => $"£{x.MinimumSalary?.ToString("n0")} per annum",
                                  x => $"£{x.MinimumSalary?.ToString("n0")} to £{x.MaximumSalary?.ToString("n0")} per annum"
                                  );
            }

            return(salary);
        }
        private void loadBookData(EbooksContext db, GutCatDoc doc, IList<GutBook> newBooks, IList<GutAuthor> newAuthors, IList<LanguageName> newLangNames, IList<LanguageCode> newLangCodes) {
            var gutBook = db.GutBooks.SingleOrDefault(b => b.GutBookId == doc.Id);
            if (gutBook == null) {
                gutBook = new GutBook { GutBookId = doc.Id };
                newBooks.Add(gutBook);
            }
            gutBook.Title = doc.Title;
            var gutAuthor = newAuthors.SingleOrDefault(a => a.Name == doc.Author);
            if (gutAuthor == null) gutAuthor = db.GutAuthors.SingleOrDefault(a => a.Name == doc.Author);
            if (gutAuthor == null && doc.Author != null) {
                gutAuthor = new GutAuthor { Name = doc.Author };
                newAuthors.Add(gutAuthor);
            }
            gutBook.GutAuthor = gutAuthor;

            var langCode = newLangCodes.SingleOrDefault(c => c.Code == doc.Language);
            if (langCode == null) langCode = db.LanguageCodes.SingleOrDefault(c => c.Code == doc.Language);
            if (langCode == null) {
                var langName = newLangNames.SingleOrDefault(n => n.Name == doc.Language);
                if (langName == null) newLangNames.Add(langName = new LanguageName { Name = doc.Language });
                langCode = new LanguageCode { Code = doc.Language };
                langCode.LanguageNames = new Collection<LanguageName>();
                langCode.LanguageNames.Add(langName);
                newLangCodes.Add(langCode);
            }
            gutBook.Language = doc.Language;

            var getUrl = new Func<string, string, string>((url, standard) => url != null && url != standard ? url : null);
            gutBook.EpubUrlImages = getUrl(doc.EpubUrlImages, doc.StandardEpubUrlImages);
            gutBook.StandardEpubUrlImages = doc.EpubUrlImages == doc.StandardEpubUrlImages;
            gutBook.EpubUrlNoImages = getUrl(doc.EpubUrlNoImages, doc.StandardEpubUrlNoImages);
            gutBook.StandardEpubUrlNoImages = doc.EpubUrlNoImages == doc.StandardEpubUrlNoImages;
            gutBook.ThumbnailUrl = getUrl(doc.ThumbnailUrl, doc.StandardThumbnailUrl);
            gutBook.StandardThumbnailUrl = doc.ThumbnailUrl == doc.StandardThumbnailUrl;
            gutBook.CoverUrl = getUrl(doc.CoverUrl, doc.StandardCoverUrl);
            gutBook.StandardCoverUrl = doc.CoverUrl == doc.StandardCoverUrl;
        }
Exemplo n.º 26
0
 private static CampfireState.UserInfo SingleMatch(string target, IList<CampfireState.UserInfo> allUsers, bool smokeSignalCommands)
 {
     // trim off trailing periods so taht references can be at the end of a sentance: "... @Peter."
     string lowered = target.Trim('.').ToLowerInvariant();
     try
     {
         // For reference... if there's only one user who matches... we have a HIT!
         CampfireState.UserInfo referencedUser = allUsers.SingleOrDefault(
             ui => smokeSignalCommands ? ui.PossibleAbbreviations.Any(abbrv => lowered.StartsWith(abbrv)) : ui.PossibleAbbreviations.Contains(lowered));
         if (referencedUser != null)
         {
             return referencedUser;
         }
     }
     catch (InvalidOperationException ex)
     {
         // this means we have multiple people that can match the reference found in the text. Oh well... just skip it
     }
     return null;
 }
Exemplo n.º 27
0
        /// <summary>
        /// Assign a bagdefinition to a player that is eligible.
        /// </summary>
        /// <param name="numberOfBagsToAward"></param>
        /// <param name="bagDefinitions"></param>
        /// <param name="eligiblePlayers">List of Character and Eligibility values</param>
        /// <param name="bagBonuses"></param>
        /// <param name="randomRollBonuses"></param>
        /// <param name="pairingContributionBonuses"></param>
        /// <param name="configSettings"></param>
        /// <returns></returns>
        public List <LootBagTypeDefinition> AssignLootToPlayers(int numberOfBagsToAward,
                                                                List <LootBagTypeDefinition> bagDefinitions, List <KeyValuePair <uint, int> > eligiblePlayers,
                                                                IList <RVRPlayerBagBonus> bagBonuses, Dictionary <uint, int> randomRollBonuses,
                                                                Dictionary <uint, int> pairingContributionBonuses, WorldConfigs configSettings)
        {
            var characterKeepTrackerList = new List <KeepLockTracker>();

            // Preload the tracker
            foreach (var eligiblePlayer in eligiblePlayers)
            {
                var k = new KeepLockTracker {
                    CharacterId = eligiblePlayer.Key, ZoneContribution = eligiblePlayer.Value
                };
                characterKeepTrackerList.Add(k);
            }

            // Sort the bagDefinitions by rarity descending
            bagDefinitions = bagDefinitions.OrderBy(x => x.BagRarity).ToList();
            bagDefinitions.Reverse();


            Logger.Debug($"=== Pairing Contributions");
            foreach (var bonus in pairingContributionBonuses)
            {
                Logger.Debug($"{bonus.Key}:{bonus.Value}");
            }

            Logger.Debug($"Eligible Player Count = {eligiblePlayers.Count()} for maximum {numberOfBagsToAward} Bags");

            if (eligiblePlayers.Count == 0)
            {
                return(null);
            }

            if (bagDefinitions == null)
            {
                Logger.Warn("BagDefinitions is null");
                return(null);
            }

            Logger.Debug($"Assigning loot. Number of Bags : {bagDefinitions.Count} Number of players : {eligiblePlayers.Count}");

            foreach (var lootBagTypeDefinition in bagDefinitions)
            {
                var comparisonDictionary = new Dictionary <uint, int>();
                foreach (var eligiblePlayer in eligiblePlayers)
                {
                    var klt = characterKeepTrackerList.SingleOrDefault(x => x.CharacterId == eligiblePlayer.Key);
                    var randomForCharacter = 0;
                    if ((randomRollBonuses != null) && (configSettings.AllowRandomContribution == "Y"))
                    {
                        if (randomRollBonuses.ContainsKey(eligiblePlayer.Key))
                        {
                            randomForCharacter = randomRollBonuses[eligiblePlayer.Key];
                            if (klt != null)
                            {
                                klt.RandomBonus = randomForCharacter;
                            }
                        }
                    }

                    var pairingContributionForCharacter = 0;
                    if ((pairingContributionBonuses != null) && (configSettings.AllowPairingContribution == "Y"))
                    {
                        if (pairingContributionBonuses.ContainsKey(eligiblePlayer.Key))
                        {
                            pairingContributionForCharacter = pairingContributionBonuses[eligiblePlayer.Key];
                            if (klt != null)
                            {
                                klt.PairingBonus = pairingContributionForCharacter;
                            }
                        }
                    }


                    var characterId = eligiblePlayer.Key;
                    var bonus       = bagBonuses.SingleOrDefault(x => x.CharacterId == characterId);
                    if ((bonus != null) && (configSettings.AllowBagBonusContribution == "Y"))
                    {
                        switch (lootBagTypeDefinition.BagRarity)
                        {
                        case LootBagRarity.White:
                        {
                            comparisonDictionary.Add(characterId, eligiblePlayer.Value + bonus.WhiteBag + randomForCharacter + pairingContributionForCharacter);
                            if (klt != null)
                            {
                                klt.WhiteBagBonus = bonus.WhiteBag;
                            }
                            break;
                        }

                        case LootBagRarity.Green:
                        {
                            comparisonDictionary.Add(characterId, eligiblePlayer.Value + bonus.GreenBag + randomForCharacter + pairingContributionForCharacter);
                            if (klt != null)
                            {
                                klt.GreenBagBonus = bonus.GreenBag;
                            }
                            break;
                        }

                        case LootBagRarity.Blue:
                        {
                            comparisonDictionary.Add(characterId, eligiblePlayer.Value + bonus.BlueBag + randomForCharacter + pairingContributionForCharacter);
                            if (klt != null)
                            {
                                klt.BlueBagBonus = bonus.BlueBag;
                            }
                            break;
                        }

                        case LootBagRarity.Purple:
                        {
                            comparisonDictionary.Add(characterId, eligiblePlayer.Value + bonus.PurpleBag + randomForCharacter + pairingContributionForCharacter);
                            if (klt != null)
                            {
                                klt.PurpleBagBonus = bonus.PurpleBag;
                            }
                            break;
                        }

                        case LootBagRarity.Gold:
                        {
                            comparisonDictionary.Add(characterId, eligiblePlayer.Value + bonus.GoldBag + randomForCharacter + pairingContributionForCharacter);
                            if (klt != null)
                            {
                                klt.GoldBagBonus = bonus.GoldBag;
                            }
                            break;
                        }
                        }
                    }
                    else
                    {
                        comparisonDictionary.Add(characterId, eligiblePlayer.Value + randomForCharacter + pairingContributionForCharacter);
                    }
                    //Logger.Debug($"===== Loot Assignment Bonuses : Character {characterId}, Base {eligiblePlayer.Value} Random {randomForCharacter} Pairing {pairingContributionForCharacter}");
                }

                // Sort the comparison dictionary
                var comparisonList = comparisonDictionary.OrderBy(x => x.Value).ToList();
                comparisonList.Reverse();

                foreach (var keyValuePair in comparisonList)
                {
                    Logger.Debug($"======= Post modification values for comparison : Character {keyValuePair.Key}, Value {keyValuePair.Value}");
                }

                if (comparisonList.Count > 0)
                {
                    lootBagTypeDefinition.Assignee = comparisonList[0].Key;
                    // remove this assignee from future comparisons.
                    eligiblePlayers.RemoveAll(x => x.Key == comparisonList[0].Key);
                    Logger.Info(
                        $"===== Selected player {lootBagTypeDefinition.Assignee} selected for reward. LootBag Id : {lootBagTypeDefinition.LootBagNumber} ({lootBagTypeDefinition.BagRarity}).");
                }
                else
                {
                    Logger.Info(
                        $"===== No player available for reward assignment. LootBag Id : {lootBagTypeDefinition.LootBagNumber} ({lootBagTypeDefinition.BagRarity}).");
                }
            }

            foreach (var keepLockTracker in characterKeepTrackerList)
            {
                Logger.Debug($"===== Loot Assignment Bonuses (KLT) : {keepLockTracker.ToString()}");
                if (configSettings.DebugLootRolls == "Y")
                {
                    var player = Player._Players.SingleOrDefault(x => x.CharacterId == keepLockTracker.CharacterId);
                    if (player != null)
                    {
                        player.SendClientMessage($"{player.Name} Loot Rolls: {keepLockTracker.ToString()}");
                    }
                }
            }

            return(bagDefinitions);
        }
Exemplo n.º 28
0
        private CommentView FindCommentInTree(IList<CommentView> comments, int commentId)
        {
            CommentView comment = comments.SingleOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                foreach (CommentView childComment in comments)
                {
                    comment = FindCommentInTree(childComment.ChildComments, commentId);

                    if (comment != null)
                    {
                        break;
                    }
                }
            }

            return comment;
        }
Exemplo n.º 29
0
        private void ValidateTable(Table expectedTable, IList<Table> result)
        {
            // Table & Name
            var actualTable = result.SingleOrDefault(t => t.Name.Equals(expectedTable.Name));
            Assert.IsNotNull(actualTable);

            // Columns
            Assert.AreEqual(expectedTable.Columns.Count, actualTable.Columns.Count);
            Assert.IsTrue(expectedTable.Columns.All(c => actualTable.Columns.Contains(c)));
        }
Exemplo n.º 30
0
 public static T Get <T>(this IList <T> list, string id) where T : BaseModel
 {
     return(list.SingleOrDefault(t => t.Id == id));
 }
Exemplo n.º 31
0
 public ITestActionResult Get(int key)
 {
     return(Ok(Accounts.SingleOrDefault(e => e.Id == key)));
 }
Exemplo n.º 32
0
        // Returns true if the tracing records are in the correct order, else returns false.
        private static bool ConfirmTracingOrder(IList<ExpectedTraceRecord> expectedRecords, IList<TraceRecord> actualRecords)
        {
            int traceBeginPos = 0;
            foreach (ExpectedTraceRecord expectedRecord in expectedRecords)
            {
                TraceRecord beginTrace = actualRecords.SingleOrDefault(r =>
                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&
                    object.Equals(r.Kind, expectedRecord.TraceKind) 
                    );

                if (!object.ReferenceEquals(beginTrace, actualRecords.ElementAt(traceBeginPos)))
                {
                    return false;
                }
                traceBeginPos++;
            }
            return true;
        }
        public async Task UpdateForDepartmentAsync(int departmentId, DateTime date, IList <DailyHealth> dailyHealths)
        {
            var employeeIds = await _myDbContext.Employees
                              .Where(x => x.DepartmentId == departmentId)
                              .Select(x => x.Id)
                              .ToListAsync();

            var inDb = await _myDbContext.DailyHealths
                       .Where(x => x.Date == date && employeeIds.Contains(x.EmployeeId))
                       .ToListAsync();

            foreach (var dbItem in inDb)
            {
                var one = dailyHealths
                          .SingleOrDefault(x => x.EmployeeId == dbItem.EmployeeId && x.Date == dbItem.Date);

                if (one != null)
                {
                    dbItem.HealthCondition = one.HealthCondition;
                    dbItem.Temperature     = one.Temperature;
                    dbItem.Remark          = one.Remark;

                    _myDbContext.Update(dbItem);
                }
            }

            var dbKeys = inDb.Select(x => new
            {
                x.EmployeeId
                ,
                x.Date
            }).ToList();

            var incomingKeys = dailyHealths.Select(x => new
            {
                x.EmployeeId,
                x.Date
            }).ToList();

            var toAddKeys = incomingKeys.Except(dbKeys);        // todo

            foreach (var addKey in toAddKeys)
            {
                var toAdd = dailyHealths.Single(x => x.EmployeeId == addKey.EmployeeId &&
                                                x.Date == addKey.Date);

                await _myDbContext.AddAsync(toAdd);
            }

            var toRemoveKeys = dbKeys.Except(incomingKeys);     // todo

            foreach (var removeKey in toRemoveKeys)
            {
                var toRemove = inDb.Single(x => x.EmployeeId == removeKey.EmployeeId &&
                                           x.Date == removeKey.Date);

                _myDbContext.Remove(toRemove);
            }

            await _myDbContext.SaveChangesAsync();
        }
Exemplo n.º 34
0
 public static ListItem GetByType(int type)
 {
     return(TypeList.SingleOrDefault(m => m.Value == type.ToString()));
 }
Exemplo n.º 35
0
        // Prepare build directory
        // Set all build related variables
        public override void InitializeJobExtension(IExecutionContext executionContext, IList <Pipelines.JobStep> steps, Pipelines.WorkspaceOptions workspace)
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(executionContext, nameof(executionContext));

            // This flag can be false for jobs like cleanup artifacts.
            // If syncSources = false, we will not set source related build variable, not create build folder, not sync source.
            bool syncSources = executionContext.Variables.Build_SyncSources ?? true;

            if (!syncSources)
            {
                Trace.Info($"{Constants.Variables.Build.SyncSources} = false, we will not set source related build variable, not create build folder and not sync source");
                return;
            }

            // We only support checkout one repository at this time.
            if (!TrySetPrimaryRepositoryAndProviderInfo(executionContext))
            {
                throw new Exception(StringUtil.Loc("SupportedRepositoryEndpointNotFound"));
            }

            executionContext.Debug($"Primary repository: {Repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Name)}. repository type: {Repository.Type}");

            // Set the repo variables.
            if (!string.IsNullOrEmpty(Repository.Id)) // TODO: Move to const after source artifacts PR is merged.
            {
                executionContext.Variables.Set(Constants.Variables.Build.RepoId, Repository.Id);
            }

            executionContext.Variables.Set(Constants.Variables.Build.RepoName, Repository.Properties.Get <string>(Pipelines.RepositoryPropertyNames.Name));
            executionContext.Variables.Set(Constants.Variables.Build.RepoProvider, ConvertToLegacyRepositoryType(Repository.Type));
            executionContext.Variables.Set(Constants.Variables.Build.RepoUri, Repository.Url?.AbsoluteUri);

            var checkoutTask = steps.SingleOrDefault(x => x.IsCheckoutTask()) as Pipelines.TaskStep;

            if (checkoutTask != null)
            {
                if (checkoutTask.Inputs.ContainsKey(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules))
                {
                    executionContext.Variables.Set(Constants.Variables.Build.RepoGitSubmoduleCheckout, Boolean.TrueString);
                }
                else
                {
                    executionContext.Variables.Set(Constants.Variables.Build.RepoGitSubmoduleCheckout, Boolean.FalseString);
                }

                // overwrite primary repository's clean value if build.repository.clean is sent from server. this is used by tfvc gated check-in
                bool?repoClean = executionContext.Variables.GetBoolean(Constants.Variables.Build.RepoClean);
                if (repoClean != null)
                {
                    checkoutTask.Inputs[Pipelines.PipelineConstants.CheckoutTaskInputs.Clean] = repoClean.Value.ToString();
                }
                else
                {
                    if (checkoutTask.Inputs.ContainsKey(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean))
                    {
                        executionContext.Variables.Set(Constants.Variables.Build.RepoClean, checkoutTask.Inputs[Pipelines.PipelineConstants.CheckoutTaskInputs.Clean]);
                    }
                    else
                    {
                        executionContext.Variables.Set(Constants.Variables.Build.RepoClean, Boolean.FalseString);
                    }
                }
            }

            // Prepare the build directory.
            executionContext.Output(StringUtil.Loc("PrepareBuildDir"));
            var            directoryManager = HostContext.GetService <IBuildDirectoryManager>();
            TrackingConfig trackingConfig   = directoryManager.PrepareDirectory(
                executionContext,
                Repository,
                workspace);

            // Set the directory variables.
            executionContext.Output(StringUtil.Loc("SetBuildVars"));
            string _workDirectory = HostContext.GetDirectory(WellKnownDirectory.Work);

            executionContext.SetVariable(Constants.Variables.Agent.BuildDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.System.ArtifactsDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.System.DefaultWorkingDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Common.TestResultsDirectory, Path.Combine(_workDirectory, trackingConfig.TestResultsDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Build.BinariesDirectory, Path.Combine(_workDirectory, trackingConfig.BuildDirectory, Constants.Build.Path.BinariesDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Build.SourcesDirectory, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Build.StagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Build.ArtifactStagingDirectory, Path.Combine(_workDirectory, trackingConfig.ArtifactsDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Build.RepoLocalPath, Path.Combine(_workDirectory, trackingConfig.SourcesDirectory), isFilePath: true);
            executionContext.SetVariable(Constants.Variables.Pipeline.Workspace, Path.Combine(_workDirectory, trackingConfig.BuildDirectory), isFilePath: true);
        }
Exemplo n.º 36
0
 public Coupon GetCoupon(string couponCode)
 {
     return(couponList.SingleOrDefault(r => r.Code == couponCode));
 }
Exemplo n.º 37
0
        public async Task <IStorageHistory> RestoreItemsFromTrashAsync(IList <IStorageItemWithPath> source, IList <string> destination, IProgress <float> progress, IProgress <FileSystemStatusCode> errorCode, CancellationToken cancellationToken)
        {
            var connection = await AppServiceConnectionHelper.Instance;

            if (connection == null || source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal)) || destination.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x)))
            {
                // Fallback to builtin file operations
                return(await filesystemOperations.RestoreItemsFromTrashAsync(source, destination, progress, errorCode, cancellationToken));
            }

            var operationID = Guid.NewGuid().ToString();

            using var r = cancellationToken.Register(CancelOperation, operationID, false);

            EventHandler <Dictionary <string, object> > handler = (s, e) => OnProgressUpdated(s, e, operationID, progress);

            connection.RequestReceived += handler;

            var moveResult = new ShellOperationResult();

            var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
            {
                { "Arguments", "FileOperation" },
                { "fileop", "MoveItem" },
                { "operationID", operationID },
                { "filepath", string.Join('|', source.Select(s => s.Path)) },
                { "destpath", string.Join('|', destination) },
                { "overwrite", false },
                { "HWND", NativeWinApiHelper.CoreWindowHandle.ToInt64() }
            });

            var result = (FilesystemResult)(status == AppServiceResponseStatus.Success &&
                                            response.Get("Success", false));
            var shellOpResult = JsonConvert.DeserializeObject <ShellOperationResult>(response.Get("Result", ""));

            moveResult.Items.AddRange(shellOpResult?.Items ?? Enumerable.Empty <ShellOperationItemResult>());

            if (connection != null)
            {
                connection.RequestReceived -= handler;
            }

            result &= (FilesystemResult)moveResult.Items.All(x => x.Succeeded);

            if (result)
            {
                progress?.Report(100.0f);
                errorCode?.Report(FileSystemStatusCode.Success);

                var movedSources = moveResult.Items.Where(x => x.Succeeded && x.Destination != null && x.Source != x.Destination);
                if (movedSources.Any())
                {
                    var sourceMatch = await movedSources.Select(x => source.SingleOrDefault(s => s.Path == x.Source)).Where(x => x != null).ToListAsync();

                    // Recycle bin also stores a file starting with $I for each item
                    await DeleteItemsAsync(await movedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc })
                                           .Select(src => StorageHelpers.FromPathAndType(
                                                       Path.Combine(Path.GetDirectoryName(src.rSrc.Source), Path.GetFileName(src.rSrc.Source).Replace("$R", "$I", StringComparison.Ordinal)),
                                                       src.oSrc.ItemType)).ToListAsync(), null, null, true, cancellationToken);

                    return(new StorageHistory(FileOperationType.Restore,
                                              sourceMatch,
                                              await movedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc })
                                              .Select(item => StorageHelpers.FromPathAndType(item.rSrc.Destination, item.oSrc.ItemType)).ToListAsync()));
                }
                return(null); // Cannot undo overwrite operation
            }
            else
            {
                // Retry failed operations
                var failedSources = moveResult.Items.Where(x => !x.Succeeded);
                var moveZip       = source.Zip(destination, (src, dest) => new { src, dest });
                var sourceMatch   = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path == x.Source)).Where(x => x != null).ToListAsync();

                return(await filesystemOperations.RestoreItemsFromTrashAsync(
                           await sourceMatch.Select(x => x.src).ToListAsync(),
                           await sourceMatch.Select(x => x.dest).ToListAsync(), progress, errorCode, cancellationToken));
            }
        }
Exemplo n.º 38
0
 public Spartan_Object_Status GetByKey(int?Key, bool ConRelaciones)
 {
     return(list.SingleOrDefault(v => v.Id == Key.Value));
 }
Exemplo n.º 39
0
        public static ETag GetETag(this HttpRequest request, EntityTagHeaderValue entityTagHeaderValue)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (entityTagHeaderValue != null)
            {
                if (entityTagHeaderValue.Equals(EntityTagHeaderValue.Any))
                {
                    return(new ETag {
                        IsAny = true
                    });
                }

                // get the etag handler, and parse the etag
                IETagHandler etagHandler = request.GetRequestContainer().GetRequiredService <IETagHandler>();
                IDictionary <string, object> properties = etagHandler.ParseETag(entityTagHeaderValue) ?? new Dictionary <string, object>();
                IList <object> parsedETagValues         = properties.Select(property => property.Value).AsList();

                // get property names from request
                ODataPath            odataPath = request.ODataFeature().Path;
                IEdmModel            model     = request.GetModel();
                IEdmNavigationSource source    = odataPath.NavigationSource;
                if (model != null && source != null)
                {
                    IList <IEdmStructuralProperty> concurrencyProperties = model.GetConcurrencyProperties(source).ToList();
                    IList <string> concurrencyPropertyNames = concurrencyProperties.OrderBy(c => c.Name).Select(c => c.Name).AsList();
                    ETag           etag = new ETag();

                    if (parsedETagValues.Count != concurrencyPropertyNames.Count)
                    {
                        etag.IsWellFormed = false;
                    }

                    IEnumerable <KeyValuePair <string, object> > nameValues = concurrencyPropertyNames.Zip(
                        parsedETagValues,
                        (name, value) => new KeyValuePair <string, object>(name, value));
                    foreach (var nameValue in nameValues)
                    {
                        IEdmStructuralProperty property = concurrencyProperties.SingleOrDefault(e => e.Name == nameValue.Key);
                        Contract.Assert(property != null);

                        Type clrType = EdmLibHelpers.GetClrType(property.Type, model);
                        Contract.Assert(clrType != null);

                        if (nameValue.Value != null)
                        {
                            Type valueType = nameValue.Value.GetType();
                            etag[nameValue.Key] = valueType != clrType
                                ? Convert.ChangeType(nameValue.Value, clrType, CultureInfo.InvariantCulture)
                                : nameValue.Value;
                        }
                        else
                        {
                            etag[nameValue.Key] = nameValue.Value;
                        }
                    }

                    return(etag);
                }
            }

            return(null);
        }
Exemplo n.º 40
0
 public static bool Exists(this IList <TiersConfig> tiers, string tierName)
 {
     return(tiers.SingleOrDefault(x => x.Name.Equals(tierName, StringComparison.OrdinalIgnoreCase)) != null);
 }
Exemplo n.º 41
0
        public IService <GroupVisitorDTO> CreateGroupService(string connection)
        {
            group1.Visitors = new List <VisitorDTO> {
                visitor1, visitor2
            };
            group2.Visitors = new List <VisitorDTO> {
                visitor3
            };
            group3.Visitors = new List <VisitorDTO> {
                visitor4
            };

            listGroups = new List <GroupVisitorDTO> {
                group1, group2, group3
            };
            Mock <IService <GroupVisitorDTO> > visitor = new Mock <IService <GroupVisitorDTO> >();

            visitor.Setup(m => m.GetAll()).Returns(listGroups);
            visitor.Setup(m => m.GetByIdAsync(It.IsAny <int>())).Returns((int id) => Task.FromResult(listGroups.SingleOrDefault(g => g.Id == id)));

            visitor.Setup(m => m.Create(It.IsAny <GroupVisitorDTO>())).Returns <GroupVisitorDTO>(g => Task.FromResult(new Func <OperationDetails>(() =>
            {
                listGroups.Add(g);
                foreach (VisitorDTO v in g.Visitors)
                {
                    listVisitors.Add(v);
                }
                return(new OperationDetails(true, "test create group", ""));
            }).Invoke()));

            visitor.Setup(m => m.Delete(It.IsAny <int>())).Returns <int>(id => Task.FromResult(new Func <OperationDetails>(() =>
            {
                var removeGroup = listGroups.Where(g => g.Id == id).FirstOrDefault();
                if (removeGroup == null)
                {
                    return(new OperationDetails(false, "test group not found", ""));
                }
                foreach (VisitorDTO v in removeGroup.Visitors)
                {
                    listVisitors.Remove(v);
                }
                listGroups.Remove(removeGroup);
                return(new OperationDetails(true, "test delete group", ""));
            }).Invoke()));

            visitor.Setup(m => m.Update(It.IsAny <GroupVisitorDTO>())).Returns <GroupVisitorDTO>(g => Task.FromResult(new Func <OperationDetails>(() =>
            {
                var removeGroup = listGroups.Where(gr => gr.Id == g.Id).FirstOrDefault();
                if (removeGroup == null)
                {
                    return(new OperationDetails(false, "test group not found", ""));
                }
                foreach (VisitorDTO v in g.Visitors)
                {
                    listVisitors.Remove(v);
                }
                listGroups.Remove(removeGroup);
                foreach (VisitorDTO v in g.Visitors)
                {
                    listVisitors.Add(v);
                }
                listGroups.Add(g);
                return(new OperationDetails(true, "test update group", ""));
            }).Invoke()));

            return(visitor.Object);
        }
 public virtual TEntity Get(int id) => entities.SingleOrDefault(e => e.Id == id);
Exemplo n.º 43
0
        // Returns a list of strings describing all of the expected trace records that were not
        // actually traced.
        // If you experience test failures from this list, it means someone stopped tracing or 
        // changed the content of what was traced.  
        // Update the ExpectedTraceRecords property to reflect what is expected.
        private static IList<string> MissingTraces(IList<ExpectedTraceRecord> expectedRecords, IList<TraceRecord> actualRecords)
        {
            List<string> missing = new List<string>();

            foreach (ExpectedTraceRecord expectedRecord in expectedRecords)
            {
                TraceRecord beginTrace = actualRecords.SingleOrDefault(r =>
                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&
                    r.Kind == TraceKind.Begin
                    );

                if (beginTrace == null)
                {
                    missing.Add(string.Format("Begin category={0}, operator={1}, operation={2}",
                                    expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName));
                }

                TraceRecord endTrace = actualRecords.SingleOrDefault(r =>
                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&
                    r.Kind == TraceKind.End
                    );

                if (endTrace == null)
                {
                    missing.Add(string.Format("End category={0}, operator={1}, operation={2}",
                                    expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName));
                }
            }

            return missing;
        }
Exemplo n.º 44
0
        /// <summary>
        /// 取得 CompnanyName by customerID
        /// </summary>
        /// <param name="customerID">客戶編號</param>
        /// <returns></returns>
        public string GetCompanyName(int customerID)
        {
            Customer customer = Customers.SingleOrDefault(m => m.CustomerID == customerID);

            return((customer != null) ? customer.CompanyName : null);
        }
Exemplo n.º 45
0
 /// <summary>
 ///     Mapping new user vote model based on given place votes and voter id
 /// </summary>
 /// <param name="votes">List of place votes</param>
 /// <param name="userId">Id of a voter</param>
 /// <returns>New user vote model</returns>
 public static UsersVoteModel MapToUsersVoteModel(IList<VoteForPlace> votes, string userId)
 {
     return new UsersVoteModel()
     {
         Id = votes.SingleOrDefault(v => v.UserId == userId)?.Id ?? Guid.Empty,
         WillAttend = votes.SingleOrDefault(v => v.UserId == userId)?.WillAttend.ToString() ?? null
     };
 }
Exemplo n.º 46
0
 public static bool checkHuyNiemYeu(string stockCode,IList<string> listHuyNiemYet)
 {
     bool result = false;
     if (listHuyNiemYet.SingleOrDefault(m => m.Contains(stockCode)) != null)
     {
         result = true;
     }
     return result;
 }
        public void Delete(long id)
        {
            var mealToBeRemoved = _meals.SingleOrDefault(x => x.Id == id);

            _meals.Remove(mealToBeRemoved);
        }
Exemplo n.º 48
0
        internal static IList <Member> PatchMembers(IList <Member> members, PatchOperation operation)
        {
            if (!members.Any())
            {
                members = null;
            }

            if (null == operation)
            {
                return(members);
            }
            if
            (
                !string.Equals(
                    AttributeNames.Members,
                    operation.Path.AttributePath,
                    StringComparison.OrdinalIgnoreCase)
            )
            {
                return(members);
            }


            if
            (
                (
                    operation.Value != null &&
                    operation.Value.Count < 1
                ) ||
                (
                    null == operation.Value &&
                    operation.Name != OperationName.Remove
                )
            )
            {
                return(members);
            }

            if (operation.Name == OperationName.Remove && string.IsNullOrEmpty(operation.Value?.FirstOrDefault()?["value"]?.ToString()))
            {
                return(null);
            }

            Member Member         = null;
            Member MemberExisting = null;

            if (members != null && operation.OperationName != "Add")
            {
                MemberExisting =
                    Member     =
                        members
                        .SingleOrDefault(
                            (Member item) =>
                            string.Equals(operation.Value?.FirstOrDefault()?["value"]?.ToString(), item.Value, StringComparison.Ordinal));
            }
            if (MemberExisting == null)
            {
                MemberExisting = null;
                if (operation.Value.FirstOrDefault().Type == Newtonsoft.Json.Linq.JTokenType.Object)
                {
                    Member = operation.Value.FirstOrDefault().ToObject <Member>();
                }
                else
                {
                    Member =
                        new Member()
                    {
                        //TypeName = "member"
                    };
                }
            }

            string value = operation.Value?.FirstOrDefault()?["value"]?.ToString();

            if
            (
                value != null &&
                OperationName.Remove == operation.Name &&
                string.Equals(value, MemberExisting?.Value, StringComparison.OrdinalIgnoreCase)
            )
            {
                value = null;
            }
            Member.Value = value;

            IList <Member> result;

            if (string.IsNullOrWhiteSpace(Member.Value))
            {
                if (MemberExisting != null)
                {
                    result = members.Where((Member item) => !string.IsNullOrWhiteSpace(item.Value)).ToList();
                }
                else
                {
                    result = members;
                }
                return(result);
            }

            if (MemberExisting != null)
            {
                return(members);
            }


            result =
                new List <Member>
            {
                Member
            };
            if (null == members)
            {
                return(result);
            }

            result = members.Union(result).ToList();
            return(result);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Get the value of a property in a Gdto.
        /// </summary>
        public string GetPropertyValue(IList<KeyValuePair<string, string>> properties, string propertyName)
        {
            try
            {
                if (properties == null)
                {
                    return string.Empty;
                }

                var namePropertyValue = properties
                    .SingleOrDefault(p => string.Equals(p.Key, propertyName, StringComparison.CurrentCultureIgnoreCase))
                    .Value;

                return namePropertyValue ?? string.Empty;
            }
            catch (Exception ex)
            {
                this.logger.Error(ex);
                throw;
            }
        }
Exemplo n.º 50
0
 /// <summary>
 /// Gets the element whose tag matches the one given as a
 /// parameter, type cast to <see cref="CollectionElement"/>.
 /// </summary>
 /// <param name="tag">The tag to search by.</param>
 /// <returns>The element whose tag matches the one given, or null if no matching collection element exists.</returns>
 public CollectionElement?GetCollectionByTag(Guid tag) =>
 m_elements.SingleOrDefault(element => element.TagOfElement == tag) as CollectionElement;
        public void UpdateModel(List <ProjectFirmaModels.Models.PerformanceMeasureActual> currentPerformanceMeasureActuals,
                                IList <ProjectFirmaModels.Models.PerformanceMeasureActual> allPerformanceMeasureActuals,
                                IList <PerformanceMeasureActualSubcategoryOption> allPerformanceMeasureActualSubcategoryOptions,
                                ProjectFirmaModels.Models.Project project,
                                IList <PerformanceMeasureReportingPeriod> allPerformanceMeasureReportingPeriods)
        {
            var currentPerformanceMeasureActualSubcategoryOptions =
                currentPerformanceMeasureActuals.SelectMany(x => x.PerformanceMeasureActualSubcategoryOptions).ToList();
            var performanceMeasureActualsUpdated = new List <ProjectFirmaModels.Models.PerformanceMeasureActual>();

            if (PerformanceMeasureActualSimples != null)
            {
                // Renumber negative indexes for PerformanceMeasureActuals
                RenumberPerformanceMeasureActuals(PerformanceMeasureActualSimples);

                var performanceMeasureReportingPeriodsFromDatabase = HttpRequestStorage.DatabaseEntities.AllPerformanceMeasureReportingPeriods.Local;
                // Completely rebuild the list
                performanceMeasureActualsUpdated = PerformanceMeasureActualSimples.Select(x =>
                {
                    var performanceMeasureReportingPeriod = allPerformanceMeasureReportingPeriods.SingleOrDefault(y => y.PerformanceMeasureReportingPeriodCalendarYear == x.CalendarYear);
                    if (performanceMeasureReportingPeriod == null)
                    {
                        Check.EnsureNotNull(x.PerformanceMeasureID, "We need to have a performance measure.");
                        performanceMeasureReportingPeriod = new PerformanceMeasureReportingPeriod((int)x.PerformanceMeasureID, x.CalendarYear, x.CalendarYear.ToString());
                        performanceMeasureReportingPeriodsFromDatabase.Add(performanceMeasureReportingPeriod);
                        HttpRequestStorage.DatabaseEntities.SaveChanges();
                    }

                    var performanceMeasureActual = new ProjectFirmaModels.Models.PerformanceMeasureActual(x.PerformanceMeasureActualID.GetValueOrDefault(),
                                                                                                          x.ProjectID.GetValueOrDefault(),
                                                                                                          x.PerformanceMeasureID.GetValueOrDefault(),
                                                                                                          x.ActualValue.GetValueOrDefault(),
                                                                                                          performanceMeasureReportingPeriod.PerformanceMeasureReportingPeriodID);
                    if (x.PerformanceMeasureActualSubcategoryOptions != null)
                    {
                        performanceMeasureActual.PerformanceMeasureActualSubcategoryOptions =
                            x.PerformanceMeasureActualSubcategoryOptions.Where(pmavsou => ModelObjectHelpers.IsRealPrimaryKeyValue(pmavsou.PerformanceMeasureSubcategoryOptionID))
                            .Select(
                                y =>
                                new PerformanceMeasureActualSubcategoryOption(performanceMeasureActual.PerformanceMeasureActualID,
                                                                              y.PerformanceMeasureSubcategoryOptionID.GetValueOrDefault(),
                                                                              y.PerformanceMeasureID,
                                                                              y.PerformanceMeasureSubcategoryID))
                            .ToList();
                    }
                    return(performanceMeasureActual);
                }).ToList();
            }

            var databaseEntities = HttpRequestStorage.DatabaseEntities;

            currentPerformanceMeasureActuals.Merge(performanceMeasureActualsUpdated,
                                                   allPerformanceMeasureActuals,
                                                   (x, y) => x.PerformanceMeasureActualID == y.PerformanceMeasureActualID,
                                                   (x, y) =>
            {
                x.PerformanceMeasureReportingPeriodID = y.PerformanceMeasureReportingPeriodID;
                x.ActualValue = y.ActualValue;
            }, databaseEntities);

            currentPerformanceMeasureActualSubcategoryOptions.Merge(
                performanceMeasureActualsUpdated.SelectMany(x => x.PerformanceMeasureActualSubcategoryOptions).ToList(),
                allPerformanceMeasureActualSubcategoryOptions,
                (x, y) => x.PerformanceMeasureActualID == y.PerformanceMeasureActualID && x.PerformanceMeasureSubcategoryID == y.PerformanceMeasureSubcategoryID && x.PerformanceMeasureID == y.PerformanceMeasureID,
                (x, y) => x.PerformanceMeasureSubcategoryOptionID = y.PerformanceMeasureSubcategoryOptionID, databaseEntities);

            var currentProjectExemptYears = project.GetPerformanceMeasuresExemptReportingYears();

            databaseEntities.ProjectExemptReportingYears.Load();
            var allProjectExemptYears       = databaseEntities.AllProjectExemptReportingYears.Local;
            var projectExemptReportingYears = new List <ProjectExemptReportingYear>();

            if (ProjectExemptReportingYearSimples != null)
            {
                // Completely rebuild the list
                projectExemptReportingYears =
                    ProjectExemptReportingYearSimples.Where(x => x.IsExempt)
                    .Select(x => new ProjectExemptReportingYear(x.ProjectExemptReportingYearID, x.ProjectID, x.CalendarYear, ProjectExemptReportingType.PerformanceMeasures.ProjectExemptReportingTypeID))
                    .ToList();
            }
            currentProjectExemptYears.Merge(projectExemptReportingYears,
                                            allProjectExemptYears,
                                            (x, y) => x.ProjectID == y.ProjectID && x.CalendarYear == y.CalendarYear && x.ProjectExemptReportingTypeID == y.ProjectExemptReportingTypeID, HttpRequestStorage.DatabaseEntities);
            project.PerformanceMeasureActualYearsExemptionExplanation = Explanation;
            if (project.ProjectApprovalStatus == ProjectApprovalStatus.PendingApproval)
            {
                project.ReportedAccomplishmentsComment = Comments;
            }
        }
Exemplo n.º 52
0
        internal static IDaoProvider GetDaoProvider(string dbProviderName)
        {
            IDaoProvider provider = _providers.SingleOrDefault(p => p.Name.Equals(dbProviderName, StringComparison.OrdinalIgnoreCase) || p.SupportsDbProvider(dbProviderName));

            return(provider);
        }
Exemplo n.º 53
0
 private void UpdateDiskDetails(IList<DiskDetails> diskDetails)
 {
     this.Disks = new List<VirtualHardDisk>();
     foreach (var disk in diskDetails)
     {
         VirtualHardDisk hd = new VirtualHardDisk();
         hd.Id = disk.VhdId;
         hd.Name = disk.VhdName;
         this.Disks.Add(hd);
     }
     DiskDetails OSDisk = diskDetails.SingleOrDefault(d => string.Compare(d.VhdType, "OperatingSystem", StringComparison.OrdinalIgnoreCase) == 0);
     if (OSDisk != null)
     {
         this.OSDiskId = OSDisk.VhdId;
         this.OSDiskName = OSDisk.VhdName;
     }
 }
Exemplo n.º 54
0
        private static BlogPost ReturnBlogPost(int year, int month, int day, string title, IList<BlogPost> blogPostList, bool shouldBlogPostRepositoryAlwayReturnPost)
        {
            if (shouldBlogPostRepositoryAlwayReturnPost)
            {
                var blogPost = new BlogPost("Test", "Test", "Test", new ImageReference(1, "/noimage.jpg"), DateTime.Now, new BlogUser());
                blogPost.SetProperty(p => p.Id, 1);

                return blogPost;
            }

            return blogPostList.SingleOrDefault(p => p.PublishedDate.Year == year && p.PublishedDate.Month == month && p.PublishedDate.Day == day && p.Title.Equals(title, StringComparison.CurrentCultureIgnoreCase));
        }
Exemplo n.º 55
0
        public Author Find(int id)
        {
            var author = authors.SingleOrDefault(b => b.Id == id);

            return(author);
        }
Exemplo n.º 56
0
 public static DocumentGroup FindByName(this IList <DocumentGroup> groups, string name)
 {
     return(groups?.SingleOrDefault(g => g.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)));
 }
        /// <summary>
        /// Gets the value by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>System.String.</returns>
        public string GetValueByKey(string key)
        {
            _settings = GetValues();
            var singleOrDefault = _settings.SingleOrDefault(s => string.Equals(s.Name, key, StringComparison.CurrentCultureIgnoreCase));

            string val = null;
            if (singleOrDefault != null)
            {
                val = singleOrDefault.Value;
            }

            return val;
        }
Exemplo n.º 58
0
 public static DocumentGroup FindBySlot(this IList <DocumentGroup> groups, int index)
 {
     return(groups?.SingleOrDefault(g => g.Slot == index));
 }
Exemplo n.º 59
0
 public async Task <bool> DeleteItemAsync(Guid id)
 => await Task.Run(() => Users.Remove(Users.SingleOrDefault(u => u.Id == id)));
        public void Init()
        {
            _accountDataService = new AccountDataService();

            _accountDb = new List <Account>()
            {
                new Account {
                    _AccountId = 1, _CustomerId = 1, _Name = "Wells Fargo",
                    _Balance   = 2000.00m, _Apr = 0.159f, _MinPay = 25.00m, _Payment = 30.00m
                },
                new Account {
                    _AccountId = 2, _CustomerId = 1, _Name = "Chase Bank",
                    _Balance   = 3000.00m, _Apr = 0.189f, _MinPay = 27.00m, _Payment = 30.00m
                },
                new Account {
                    _AccountId = 3, _CustomerId = 1, _Name = "Car Loan",
                    _Balance   = 4000.00m, _Apr = 0.209f, _MinPay = 225.00m, _Payment = 225.00m
                },
                new Account {
                    _AccountId = 4, _CustomerId = 2, _Name = "Bank of America",
                    _Balance   = 1500.00m, _Apr = 0.229f, _MinPay = 25.00m, _Payment = 100.00m
                },
                new Account {
                    _AccountId = 5, _CustomerId = 2, _Name = "Student Loan1",
                    _Balance   = 20000.00m, _Apr = 0.03f, _MinPay = 225.00m, _Payment = 225.00m
                },
                new Account {
                    _AccountId = 6, _CustomerId = 2, _Name = "Student Loan2",
                    _Balance   = 20000.00m, _Apr = 0.06f, _MinPay = 250.00m, _Payment = 250.00m
                },
                new Account {
                    _AccountId = 7, _CustomerId = 3, _Name = "Zales Credit",
                    _Balance   = 2700.00m, _Apr = 0.299f, _MinPay = 75.00m, _Payment = 100.00m
                },
                new Account {
                    _AccountId = 8, _CustomerId = 3, _Name = "Capital One",
                    _Balance   = 1000.00m, _Apr = 0.139f, _MinPay = 15.00m, _Payment = 15.00m
                },
                new Account {
                    _AccountId = 9, _CustomerId = 3, _Name = "Best Buy",
                    _Balance   = 2200.00m, _Apr = 0.169f, _MinPay = 25.00m, _Payment = 100.00m
                },
                new Account {
                    _AccountId = 10, _CustomerId = 3, _Name = "American Express",
                    _Balance   = 3500.00m, _Apr = 0.199f, _MinPay = 25.00m, _Payment = 100.00m
                }
            };

            _accountDataService.SaveToFile(_accountDb);

            _mockAccountService = new Mock <IAccountDataService>();

            _accountJson = _accountDataService.ReadFromFile();

            //_mockAccountService.Object.SavePaymentsToFile(_accountDb);

            _mockAccountService.Setup(a => a.FindAll()).Returns(
                () =>
            {
                var accounts = new List <Account>();

                _accountDb.ToList().ForEach(account =>
                {
                    accounts.Add(new Account()
                    {
                        _AccountId  = account._AccountId,
                        _CustomerId = account._CustomerId,
                        _Name       = account._Name,
                        _Balance    = account._Balance,
                        _Apr        = account._Apr,
                        _MinPay     = account._MinPay,
                        _Payment    = account._Payment
                    });
                });

                return(accounts);
            });

            _mockAccountService.Setup(a => a.AddAccount(It.IsAny <Account>())).Callback(
                (Account account) =>
            {
                if (account == null)
                {
                    throw new InvalidOperationException("Add Account - account was null");
                }
                if (account._AccountId <= 0)
                {
                    account._AccountId = _accountDb.Max(a => a._AccountId) + 1;
                    _accountDb.Add(account);
                }
            });

            _mockAccountService.Setup(a => a.DeleteAccount(It.IsAny <Account>())).Callback(
                (Account account) =>
            {
                var deleteAccount = _accountDb.SingleOrDefault(a => a._AccountId.Equals(account._AccountId));
                _accountDb.Remove(deleteAccount);
            }) /*.Verifiable()??*/;

            _mockAccountService.Setup(a => a.EditAccount(It.IsAny <Account>())).Callback(
                (Account account) =>
            {
                if (account == null)
                {
                    throw new InvalidOperationException("Edit Account - account was null");
                }
                var updateAccount = _accountDb.SingleOrDefault(a => a._AccountId.Equals(account._AccountId));
                if (updateAccount == null)
                {
                    throw new InvalidOperationException("Account was null");
                }
                updateAccount._CustomerId = account._CustomerId;
                updateAccount._Name       = account._Name;
                updateAccount._Balance    = account._Balance;
                updateAccount._Apr        = account._Apr;
                updateAccount._MinPay     = account._MinPay;
                updateAccount._Payment    = account._Payment;
            });

            _mockAccountService.Setup(a => a.FindByName(It.IsAny <string>())).Returns(
                (string name) =>
            {
                return(_accountDb.SingleOrDefault(a => a._Name.Equals(name)));
            });

            _mockAccountService.Setup(a => a.FindByID(It.IsAny <int>())).Returns(
                (int id) =>
            {
                return(_accountDb.SingleOrDefault(a => a._AccountId.Equals(id)));
            });

            _mockAccountService.Setup(a => a.FindAllByCustomerId(It.IsAny <int>())).Returns(
                (int id) =>
            {
                var customerAccounts = new List <Account>();
                customerAccounts     = _accountDb.ToList().Where(account => account._CustomerId.Equals(id)).ToList();
                if (customerAccounts.Count().Equals(0))
                {
                    throw new InvalidOperationException("No accounts with that id");
                }
                return(customerAccounts);
            });
        }