/// <summary>
        /// Set tags to the specified <paramref name="file"/>.
        /// </summary>
        /// <returns>The task to process it.</returns>
        /// <param name="file">File to tag.</param>
        /// <param name="tags">Tags to set.</param>
        /// <param name="clear">If set to <c>true</c> replace existing tags with ne <paramref name="tags"/>.</param>
        public Task TagAsync(FileInfo file, IEnumerable<string> tags, bool clear)
        {
            return Task.Factory.StartNew(() =>
            {
                ImageFile imagefile = ImageFile.FromFile(file.FullName);

                string tagsValue;
                if (clear)
                {
                    tagsValue = tags.Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";");
                }
                else
                {
                    List<string> existingTags = new List<string>();
                    ExifProperty existingTagsValue;
                    if (imagefile.Properties.TryGetValue(ExifTag.WindowsKeywords, out existingTagsValue))
                        existingTags = existingTagsValue.Value.ToString().Split(';').ToList();
                    tagsValue = tags.Union(existingTags).Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";");
                }

                imagefile.Properties.Set(ExifTag.WindowsKeywords, tagsValue);

                imagefile.Save(file.FullName);
            });
        }
        /// <summary>
        /// Create a new tariff restrictions class.
        /// </summary>
        /// <param name="Time">Start/end time of day, for example "13:30 - 19:45", valid from this time of the day.</param>
        /// <param name="Date">Start/end date, for example: 2015-12-24, valid from this day until that day (excluding that day).</param>
        /// <param name="kWh">Minimum/Maximum used energy in kWh, for example 20, valid from this amount of energy is used.</param>
        /// <param name="Power">Minimum/Maximum power in kW, for example 0, valid from this charging speed.</param>
        /// <param name="Duration">Minimum/Maximum duration in seconds, valid for a duration from x seconds.</param>
        /// <param name="DayOfWeek">Minimum/Maximum duration in seconds, valid for a duration from x seconds.</param>
        public TariffRestriction(TimeRange?              Time       = null,
                                 StartEndDateTime?       Date       = null,
                                 DecimalMinMax?          kWh        = null,
                                 DecimalMinMax?          Power      = null,
                                 TimeSpanMinMax?         Duration   = null,
                                 IEnumerable<DayOfWeek>  DayOfWeek  = null)
        {
            #region Initial checks

            if (!Time.   HasValue &&
                !Date.   HasValue &&
                !kWh.    HasValue &&
                Power.   HasValue &&
                Duration.HasValue &&
                DayOfWeek == null)
                throw new ArgumentNullException("All given parameter equals null is invalid!");

            #endregion

            this.Time       = Time;
            this.Date       = Date;
            this.kWh        = kWh;
            this.Power      = Power;
            this.Duration   = Duration;
            this.DayOfWeek  = DayOfWeek != null ? DayOfWeek.Distinct() : new DayOfWeek[0];
        }
Пример #3
0
		public TypeCoupling(string typeName, string namespaceName, string assemblyName, IEnumerable<string> usedMethods, IEnumerable<string> usedProperties, IEnumerable<string> useEvents)
			: base(typeName, namespaceName, assemblyName)
		{
			UsedMethods = usedMethods.Distinct().AsArray();
			UsedProperties = usedProperties.Distinct().AsArray();
			UsedEvents = useEvents.Distinct().AsArray();
		}
        public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            //Debugger.Launch();

            frameworkHandle.SendMessage(TestMessageLevel.Informational, Strings.EXECUTOR_STARTING);

            Settings settings = GetSettings(runContext);

            foreach (string currentAsssembly in sources.Distinct())
            {
                try
                {
                    if (!File.Exists(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(currentAsssembly)),"Machine.Specifications.dll")))
                    {
                        frameworkHandle.SendMessage(TestMessageLevel.Informational, String.Format("Machine.Specifications.dll not found for {0}", currentAsssembly));
                        continue;
                    }

                    frameworkHandle.SendMessage(TestMessageLevel.Informational, String.Format(Strings.EXECUTOR_EXECUTINGIN, currentAsssembly));

                    this.executor.RunAssembly(currentAsssembly, settings, uri, frameworkHandle);
                }
                catch (Exception ex)
                {
                    frameworkHandle.SendMessage(TestMessageLevel.Error, String.Format(Strings.EXECUTOR_ERROR, currentAsssembly, ex.Message));
                }
            }

            frameworkHandle.SendMessage(TestMessageLevel.Informational, String.Format("Complete on {0} assemblies ", sources.Count()));
            
        }
        private void ValidateOperators(IEnumerable<IOperator> operatorList)
        {
            var codes = operatorList.Select(op => op.Code).ToList();
            var duplicateCodes = operatorList.Count() != operatorList.Distinct().Count();

            if (duplicateCodes) {
                var groupedCodes = operatorList.GroupBy(x => x.Code);
                var moreThanOneCodeGroups = groupedCodes.Where(x => x.Count() > 1);

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain duplicate codes:");

                foreach (var group in moreThanOneCodeGroups) {
                    var groupString = string.Format("\\tThe code {0} is present {1} times in operators {2}", group.Key, group.Count(), string.Join(", ", group.Select(x => x.GetType().Name)));
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }

            if (codes.Any(x => string.IsNullOrWhiteSpace(x))) {
                var whitespaceCodes = operatorList.Where(x => string.IsNullOrWhiteSpace(x.Code));

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain empty codes:");

                foreach (var op in whitespaceCodes) {
                    var groupString = string.Format("\\tThe code of {0} is empty", op.GetType().Name);
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }
        }
Пример #6
0
        public static void SaveToCache(TwitterResource resource, IEnumerable<TwitterStatus> list)
        {
            string fileName = GetCacheName(resource);

            var serializer = new SharpSerializer(SerializerSettings);
            Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName);

            if (mutex.WaitOne(1000))
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        serializer.Serialize(list.Distinct().OfType<TwitterStatus>().ToList(), stream);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

            mutex.Dispose();
        }
Пример #7
0
		private static void LogImportedDefaultGroups(IEnumerable<AuthorityGroupDefinition> groups)
		{
			foreach (var g in groups.Distinct())
			{
				Platform.Log(LogLevel.Info, "Imported default authority group definition: {0}", g.Name);
			}
		}
Пример #8
0
        public static IReadOnlyCollection<PoliticalTweet> LoadTweets( IEnumerable<string> handles )
        {
            var service = new TwitterService( ConsumerKey, ConsumerSecret );
            service.AuthenticateWith( AccessToken, AccessTokenSecret );
            var results = new List<PoliticalTweet>();

            foreach ( var handle in handles.Distinct() )
            {
                try
                {
                    var response = service.ListTweetsOnUserTimeline( new ListTweetsOnUserTimelineOptions
                    {
                        ScreenName = handle,
                        Count = 200,
                        IncludeRts = false,
                        ExcludeReplies = true
                    } );
                    results.AddRange( response.Select( t => new PoliticalTweet( handle, t.Text, t.CreatedDate, t.IdStr ) ) );

                    Debug.WriteLine( $"{service.Response.RateLimitStatus.RemainingHits} remaining hits." );
                    if ( service.Response.RateLimitStatus.RemainingHits <= 0 )
                    {
                        var wait = service.Response.RateLimitStatus.ResetTime.ToUniversalTime() - DateTime.UtcNow;
                        Debug.WriteLine( $"Rate limit reached. Sleeping for {wait}." );
                        Thread.Sleep( wait );
                    }
                }
                catch
                {
                    Debug.WriteLine( $"Skipping {handle}" );
                }
            }

            return results;
        }
Пример #9
0
        internal RepoConfig(
            IEnumerable<NuGetPackage> fixedPackages, 
            IEnumerable<string> toolsetPackages, 
            IEnumerable<Regex> nuspecExcludes,
            IEnumerable<Regex> projectJsonExcludes,
            GenerateData? msbuildGenerateData)
        {
            Debug.Assert(toolsetPackages.Distinct().Count() == toolsetPackages.Count());
            MSBuildGenerateData = msbuildGenerateData;
            FixedPackages = fixedPackages.OrderBy(x => x.Name).ToImmutableArray();
            NuSpecExcludes = nuspecExcludes.ToImmutableArray();
            ProjectJsonExcludes = projectJsonExcludes.ToImmutableArray();
            ToolsetPackages = toolsetPackages.OrderBy(x => x).ToImmutableArray();

            var map = new Dictionary<string, List<string>>();
            foreach (var nugetRef in fixedPackages)
            {
                List<string> list;
                if (!map.TryGetValue(nugetRef.Name, out list))
                {
                    list = new List<string>(capacity: 1);
                    map[nugetRef.Name] = list;
                }

                list.Add(nugetRef.Version);
            }
        }
Пример #10
0
        private string[] ValidateFields(string indexName, IEnumerable<string> indexFields)
        {
            var withoutDuplicates = indexFields.Distinct().ToArray();

            var members = _reflectionService.GetFieldsAndProperties(_classInfo.UnderlyingType);

            foreach (var indexField in withoutDuplicates)
            {
                var memberInfo = members.FirstOrDefault(x => x.Name.Equals(indexField));

                var memberType = memberInfo is PropertyInfo
                                     ? ((PropertyInfo) memberInfo).PropertyType
                                     : ((FieldInfo) memberInfo).FieldType;

                if (memberInfo != null && (typeof(IComparable)).IsAssignableFrom(memberType)) 
                    continue;

                var fieldType = (memberInfo == null || memberInfo.DeclaringType == null)
                                    ? "Field doesn't exist"
                                    : memberType.FullName;

                throw new OdbRuntimeException(NDatabaseError.IndexKeysMustImplementComparable.AddParameter(indexName)
                                                            .AddParameter(indexField)
                                                            .AddParameter(fieldType));
            }

            return withoutDuplicates;
        }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerMultiBinding"/> class.
 /// </summary>
 /// <param name="subBindings">The sub bindings.</param>
 /// <param name="readOnly">if set to <c>true</c> [read only].</param>
 public ServerMultiBinding(IEnumerable<IServerBinding> subBindings, bool readOnly = false)
 {
     Condition.Requires(subBindings, "subBindings").IsNotNull();
     _SubBindings = subBindings.Distinct(new UriEqualityComparer<IServerBinding>()).ToList();
     Condition.Requires(_SubBindings, "SubBindings").IsLongerThan(1,"Must have more than one unique server binding.");
     ReadOnly = readOnly;
 }
Пример #12
0
        public ScriptResult(
            object returnValue = null,
            Exception executionException = null,
            Exception compilationException = null, 
            IEnumerable<string> invalidNamespaces = null)
        {
            if (returnValue != null)
            {
                ReturnValue = returnValue;
            }

            if (executionException != null)
            {
                ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(executionException);
            }

            if (compilationException != null)
            {
                CompileExceptionInfo = ExceptionDispatchInfo.Capture(compilationException);
            }

            if (invalidNamespaces != null)
            {
                foreach (var ns in invalidNamespaces.Distinct())
                {
                    _invalidNamespaces.Add(ns);
                }
            }

            IsCompleteSubmission = true;
        }
Пример #13
0
        public static int GetMaxClusters(IEnumerable<int> numbers, int bits, int maxSpacing)
        {
            var distinctNumbers = numbers.Distinct().ToArray();
            int clusterCount = distinctNumbers.Length;
            var numberToCluster = new Dictionary<int, int>();

            for (int i = 0; i < clusterCount; i++)
            {
                numberToCluster.Add(distinctNumbers[i], i);
            }

            var unionFind = new UnionFind(clusterCount);
            for (int spacing = 1; spacing <= maxSpacing; spacing++)
            {
                foreach (var number in distinctNumbers)
                {
                    var modifications = GetModifications(number, bits, spacing, 0).ToArray();
                    foreach (var modification in modifications.Where(numberToCluster.ContainsKey))
                    {
                        var cluster1 = unionFind.Find(numberToCluster[number]);
                        var cluster2 = unionFind.Find(numberToCluster[modification]);
                        if (cluster1 != cluster2)
                        {
                            unionFind.Union(cluster1, cluster2);
                            clusterCount--;
                        }
                    }
                }
            }

            return clusterCount;
        }
Пример #14
0
        public static Type CreateDynamicDecorator(
            Type decoratedType,
            IEnumerable<PropertyInfo> properties,
            Type baseType,
            string decoratedProperty = "DecoratedObject",
            string typeName = null,
            string assemblyName = null,
            string moduleName = null,
            bool createDecoratedProperty = false)
        {
            typeName = typeName ?? "DynamicDecorator_" + Guid.NewGuid().ToString("N");
            var assName = new AssemblyName(decoratedType.FullName + ".DynamicDecorator");

            var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule(decoratedType.Module.Name);

            baseType = baseType ?? typeof (object);

            var tb = moduleBuilder.DefineType(typeName,
                TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass |
                TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, baseType);

            foreach (var prop in properties.Distinct())
                CreateDecoratedProperty(tb, prop, baseType, decoratedProperty, decoratedType);

            return tb.CreateType();
        }
Пример #15
0
        /// <summary>
        /// Adds specific destinations to a claim.
        /// </summary>
        /// <param name="claim">The <see cref="Claim"/> instance.</param>
        /// <param name="destinations">The destinations.</param>
        public static Claim SetDestinations(this Claim claim, IEnumerable<string> destinations)
        {
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }

            if (destinations == null || !destinations.Any())
            {
                claim.Properties.Remove(Properties.Destinations);

                return claim;
            }

            if (destinations.Any(destination => destination.Contains(" ")))
            {
                throw new ArgumentException("Destinations cannot contain spaces.", nameof(destinations));
            }

            //claim.Properties[Properties.Destinations] =
            //    string.Join(" ", destinations.Distinct(StringComparer.Ordinal));
            //TODO chage destination with destinations in rc 2
            claim.Properties[Properties.Destination] =
                string.Join(" ", destinations.Distinct(StringComparer.Ordinal));

            return claim;
        }
Пример #16
0
        public static IEnumerable<TextEntityDescription> ParseText(
            string text, IEnumerable<TwitterEntity> entities)
        {
            if (entities == null) throw new ArgumentNullException("entities");
            var escaped = ParsingExtension.EscapeEntity(text);
            var endIndex = 0;

            // distinct by startindex ignores extended_entities.
            foreach (var entity in entities.Distinct(e => e.StartIndex).OrderBy(e => e.StartIndex))
            {
                if (endIndex < entity.StartIndex)
                {
                    // return raw string
                    yield return new TextEntityDescription(ParsingExtension.ResolveEntity(
                        escaped.SubstringForSurrogatePaire(endIndex, entity.StartIndex - endIndex)));
                }
                // get entitied text
                var body = ParsingExtension.ResolveEntity(escaped.SubstringForSurrogatePaire(
                    entity.StartIndex, entity.EndIndex - entity.StartIndex));
                yield return new TextEntityDescription(body, entity);
                endIndex = entity.EndIndex;
            }
            if (endIndex == 0)
            {
                // entity is empty.
                yield return new TextEntityDescription(text);
            }
            else if (endIndex < escaped.Length)
            {
                // return remain text
                yield return new TextEntityDescription(ParsingExtension.ResolveEntity(
                    escaped.SubstringForSurrogatePaire(endIndex)));
            }
        }
Пример #17
0
 protected IEnumerable<ModelApplicationBase> GetAllLayers(IEnumerable<ModelDifferenceObject> differenceObjects, ModelApplicationBase master) {
     if (GetttingNonAppModels(differenceObjects))
         differenceObjects = differenceObjects.Where(o => o.CombineOrder < CombineOrder);
     var modelApplicationBases = differenceObjects.Distinct().Select(differenceObject => differenceObject.GetModel(master));
     modelApplicationBases = modelApplicationBases.Concat(new List<ModelApplicationBase> { GetModel(master) });
     return modelApplicationBases;
 }
Пример #18
0
 public HexameterGenerator(IEnumerable<string> words)
 {
     _wordToSyllableMap = new Dictionary<string, SyllableList>();
     foreach(var word in words.Distinct())
     {
         _wordToSyllableMap.Add(word,new SyllableList(Syllabler.ToSyllables(word)));
     }
 }
Пример #19
0
		// Public Methods 

        public static Type[] GetAllTypes(IEnumerable<Assembly> assemblies)
        {
            assemblies = assemblies.Distinct().ToArray();
            var result = new Dictionary<string, Type>();
            foreach (var assembly in assemblies)
                GetTypesX(assembly, result);
            return result.Values.ToArray();
        }
Пример #20
0
 private static List<CrawledMovie> GetDistinctCrawledMovies(
     IEnumerable<CrawledShow> shows)
 {
     return shows.Distinct(new CrawledShowComparer())
                 .Select(MapDistinctShowToCrawledMovie)
                 .OrderBy(x => x.CrawledMovieId)
                 .ToList();
 }
 public KnownTypesDataContractResolver(IEnumerable<Type> types)
 {
     this.knownTypes = (
         from type in types.Distinct()
         group type by type.Name into g
         select g.First())
         .ToDictionary(GetName);
 }
Пример #22
0
 public Chainrings(IEnumerable<int> sprockets)
 {
     Sprockets = sprockets
         .Distinct()
         .OrderBy(x => x)
         .Select(x => (Sprocket) x)
         .ToArray();
 }
Пример #23
0
        /// <summary>
        /// Performs any transforms on the web <paramref name="resources" /> passed in and returns the new list.
        /// </summary>
        /// <param name="resources">List of web resources to process.</param>
        /// <param name="resourceType">Web resource types being processed.</param>
        /// <returns>
        /// Transformed list of web resources.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">resources</exception>
        IEnumerable<string> IResourceTransform.ProcessResources(IEnumerable<string> resources, ResourceType resourceType)
        {
            if (resources == null) throw new ArgumentNullException("resources");

            if (!ResourceType.HasFlag(resourceType))
                return resources;

            return resources.Distinct();
        }
Пример #24
0
        public void SetQueues(IEnumerable<Queue> newQueues)
        {
            Queues.Clear();

            foreach (var queue in newQueues.Distinct())
            {
                Queues.Add(queue);
            }
        }
Пример #25
0
        public void AssertContainsAll(IEnumerable<int> expected, IEnumerable<int> actual)
        {
            int n1 = expected.Distinct().Count();
            int n2 = actual.Distinct().Count();

            Assert.AreEqual(n1, n2);
            Assert.AreEqual(n1, expected.Intersect(actual).Count());
            Assert.AreEqual(n2, actual.Intersect(expected).Count());
        }
Пример #26
0
 private XAttribute[] getTypeSpecAttributes(IEnumerable<Type> types)
 {
     var lst = new List<Type>(types.Distinct());
     if(!lst.Contains(typeof(int)))
         lst.Add(typeof(int));
     if (!lst.Contains(typeof(string)))
         lst.Add(typeof(string));
     return lst.Select(tp => _typeSpecs.Where(s => s.CanSpecify(tp)).First()).Select(spec => spec.GetAttribute()).ToArray();
 }
 public CompositeHandlerSource(IEnumerable<IHandlerSource> handlerSources)
 {
     if (handlerSources == null)
     {
         throw new ArgumentNullException("handlerSources");
     }
     _sources = handlerSources.Distinct().ToArray();
     _latch = new object();
 }
Пример #28
0
        /// <inheritdoc />
        public Dictionary<CharacterKey, PlayerLocation> GetLocationsForAll(IEnumerable<CharacterKey> keys)
        {
            // ReSharper disable once PossibleMultipleEnumeration
            Guard.NotNull(() => keys, keys);

            return keys
                .Distinct()
                .ToDictionary(key => key, this.GetLocation);
        }
Пример #29
0
        public static void AddNamespaces(this CodeNamespace theNamespace, IEnumerable<string> namespaceNamesToAdd)
        {
            namespaceNamesToAdd = namespaceNamesToAdd.Distinct();

            foreach(string namespaceName in namespaceNamesToAdd)
            {
                theNamespace.Imports.Add(new CodeNamespaceImport(namespaceName));
            }
        }
Пример #30
0
 public Cassette(string name, IEnumerable<int> sprockets)
 {
     Name = name;
     Sprockets = sprockets
         .Distinct()
         .OrderBy(x => x)
         .Select(x => (Sprocket) x)
         .ToArray();
 }
Пример #31
0
        /// <summary>
        /// Initializes a new instance of the Alphabet class.
        /// </summary>
        /// <param name="characters">The characters of this alphabet.</param>
        /// <exception cref="ArgumentNullException">
        /// The argument is <c>null</c>.
        /// </exception>
        public Alphabet(IEnumerable <char> characters)
        {
            characters = characters?.Distinct().ToArray()
                         ?? throw new ArgumentNullException(
                                   nameof(characters), "Cannot create empty alphabet.");

            if (!characters.Any())
            {
                throw new ArgumentException(
                          "Cannot create empty alphabet.", nameof(characters));
            }

            int index = 0;

            foreach (char ch in characters)
            {
                this.characters.Add(index, ch);
                this.indices.Add(ch, index);
                index++;
            }

            this.Length = index;
        }
        /// <summary>
        /// 根据所有vehicleId查询喷漆等级
        /// </summary>
        /// <param name="vehicleIds"></param>
        /// <returns></returns>
        private List <Tuple <string, string> > GetAllSprayPaintLevelByVehicleIds(IEnumerable <string> vehicleIds)
        {
            vehicleIds = vehicleIds?.Distinct();
            var result = new List <Tuple <string, string> >();

            if (vehicleIds != null && vehicleIds.Any())
            {
                const int size = 60;
                for (var i = 0; i < Math.Ceiling(vehicleIds.Count() * 1.0 / size); i++)
                {
                    var items = GetSprayPaintLevelByVehicleIds(vehicleIds.Skip(i * size).Take(size));
                    if (items != null)
                    {
                        result.AddRange(items);
                    }
                    else
                    {
                        _logger.Info("发生异常终止");
                        break;
                    }
                }
            }
            return(result);
        }
Пример #33
0
        public NotFound RemoveRoleUsers(int idRole, IEnumerable <int> userIdList)
        {
            try
            {
                using (var db = new CoreContext())
                    using (var scope = db.CreateScope(TransactionScopeOption.Required))
                    {
                        if (db.Role.Where(x => x.IdRole == idRole).Count() == 0)
                        {
                            return(NotFound.NotFound);
                        }

                        var userIdList2 = userIdList?.Distinct()?.ToArray();

                        if (userIdList2?.Any() == true)
                        {
                            var query = db.RoleUser.Where(x => x.IdRole == idRole).In(userIdList2, x => x.IdUser);
                            db.RoleUser.RemoveRange(query);
                        }
                        else
                        {
                            db.RoleUser.RemoveRange(db.RoleUser.Where(x => x.IdRole == idRole));
                        }

                        db.SaveChanges();
                        scope.Complete();
                    }

                return(NotFound.Success);
            }
            catch (Exception ex)
            {
                this.RegisterEvent(EventType.Error, "Ошибка при удалении роли у пользователей.", $"Идентификатор роли: {idRole}\r\nИдентификаторы пользователей: {(userIdList?.Any() == true ? "не задано" : string.Join(", ", userIdList))}", ex);
                return(NotFound.Error);
            }
        }
Пример #34
0
        /// <summary>
        /// Create new credentials.
        /// </summary>
        /// <param name="Token">The credentials token for the other party to authenticate in your system.</param>
        /// <param name="URL">The URL to your API versions endpoint.</param>
        /// <param name="Roles">The enumeration of roles a party provides.</param>
        public Credentials(AccessToken Token,
                           URL URL,
                           IEnumerable <CredentialsRole> Roles)
        {
            if (Token.IsNullOrEmpty)
            {
                throw new ArgumentNullException(nameof(Token), "The given token must not be null or empty!");
            }

            if (URL.IsNullOrEmpty)
            {
                throw new ArgumentNullException(nameof(URL), "The given URL must not be null or empty!");
            }

            if (!Roles.SafeAny())
            {
                throw new ArgumentNullException(nameof(Roles), "The given enumeration of roles must not be null or empty!");
            }


            this.Token = Token;
            this.URL   = URL;
            this.Roles = Roles?.Distinct();
        }
Пример #35
0
        public bool CreateTeam(Team team, IEnumerable <string> memberEmails)
        {
            if (
                string.IsNullOrEmpty(team.Name) ||
                team.CreatedBy == 0)
            {
                return(false);
            }

            memberEmails = memberEmails?.Distinct();

            if (memberEmails == null)
            {
                memberEmails = new List <string>();
            }

            var teamId = _teamCommands.CreateTeam(
                team,
                memberEmails);

            team.Id = teamId;

            return(true);
        }
Пример #36
0
            public static void Throws_ArgumentNullException_when_sequence_is_null()
            {
                IEnumerable <int> numbers = null;

                Assert.Throws <ArgumentNullException>(() => numbers.Distinct(n => n % 2));
            }
Пример #37
0
 /// <summary>
 /// Creates a new instance of the <see cref="ParameterCollection"/> type.
 /// </summary>
 /// <param name="parameterNames"> A collection with the used script parameter names (without values). </param>
 public ParameterCollection(IEnumerable <string> parameterNames)
 {
     Parameters = parameterNames?.Distinct()?.ToDictionary(name => name, name => (object)null) ?? new Dictionary <string, object>();
 }
Пример #38
0
 public MinutesPerSlide(IEnumerable <SlideType> slideTypes, IEnumerable <Visit> visits)
 {
     this.slideTypes = slideTypes.Distinct().ToArray();
     this.visits     = visits.OrderBy(visit => visit.Date).ToArray();
 }
Пример #39
0
        public YggCompilation Compile <TState>(IEnumerable <string> namespaces,
                                               IEnumerable <string> referenceAssemblyPaths,
                                               List <ScriptedFunctionDefinition> definitions)
        {
            var compilation      = new YggCompilation();
            var builderClassText = new StringBuilder();
            var usings           = new List <string>(namespaces.Distinct().Select(s => $"using {s};\n"));
            var referencePaths   = new HashSet <string>(referenceAssemblyPaths);

            // Add dynamic using if necessary.
            if (definitions.Any(d => d.ReplaceObjectWithDynamic))
            {
                usings.Add("using System.Dynamic;");
            }

            foreach (var u in usings)
            {
                builderClassText.Append(u);
            }

            builderClassText.Append("public class FunctionBuilder\n{");

            foreach (var definition in definitions)
            {
                var sf = CreateScriptedFunction <TState>(definition.Guid, definition.FunctionProperty,
                                                         definition.FunctionText, definition.ReplaceObjectWithDynamic, compilation.Errors);

                if (sf == null)
                {
                    continue;
                }

                if (!compilation.GuidFunctionMap.TryGetValue(sf.Guid, out var functions))
                {
                    functions = new List <ScriptedFunction>();
                    compilation.GuidFunctionMap[sf.Guid] = functions;
                }

                functions.Add(sf);
                builderClassText.Append(sf.ScriptText);

                foreach (var reference in sf.References)
                {
                    referencePaths.Add(reference);
                }
            }

            builderClassText.Append("\n}");

            List <PortableExecutableReference> references;

            try
            {
                references = referencePaths
                             .Select(p => MetadataReference.CreateFromFile(p))
                             .ToList();
            }
            catch (Exception e)
            {
                compilation.Errors.Add(ParserErrorHelper.CannotLoadReference(e.Message));
                return(compilation);
            }

            var options = ScriptOptions.Default.AddReferences(references);
            var script  = CSharpScript.Create(builderClassText.ToString(), options);
            var comp    = script.GetCompilation();

            byte[] compiledAssembly;
            using (var output = new MemoryStream())
            {
                var emitResult = comp.Emit(output);

                if (!emitResult.Success)
                {
                    var error = new BuildError {
                        Message = "Emit compilation error.", IsCritical = true
                    };
                    foreach (var diag in emitResult.Diagnostics)
                    {
                        error.Diagnostics.Add(diag);
                    }

                    compilation.Errors.Add(error);
                    return(compilation);
                }

                compiledAssembly = output.ToArray();
            }

            var assembly  = Assembly.Load(compiledAssembly);
            var entryType = assembly.GetTypes().First(t => t.Name == "FunctionBuilder");
            var builder   = Activator.CreateInstance(entryType);

            foreach (var sf in compilation.GuidFunctionMap.Values.SelectMany(g => g))
            {
                sf.Builder       = builder;
                sf.BuilderMethod = entryType.GetMethod(sf.BuilderMethodName);
            }

            return(compilation);
        }
Пример #40
0
        public ArticleDataLoader(IEnumerable <RuleReq> reqs)
        {
            foreach (var req in reqs.Distinct())
            {
                var loader = Loaders[req];

                JObject request;
                if (!_requests.TryGetValue(loader.Type, out request))
                {
                    if (loader.Type == LoaderType.FirstRev || loader.Type == LoaderType.LastRev)
                    {
                        request = JObject.FromObject(new
                        {
                            _title    = "titles",
                            action    = "query",
                            redirects = true,
                            rvdir     = loader.Type == LoaderType.FirstRev ? "newer" : "older",
                        });
                    }
                    else if (loader.Type == LoaderType.Html)
                    {
                        request = JObject.FromObject(new
                        {
                            _title          = "page",
                            action          = "parse",
                            prop            = new[] { "text" },
                            wrapoutputclass = "",
                        });
                    }
                    _requests.Add(loader.Type, request);
                }

                var pars = loader.Params as JObject;
                if (pars == null)
                {
                    if (loader.Params != null)
                    {
                        pars = JObject.FromObject(loader.Params);
                    }
                    else
                    {
                        pars = new JObject();
                    }
                }

                foreach (var prop in pars.Properties())
                {
                    if (prop.Name.StartsWith("_"))
                    {
                        continue;
                    }

                    JToken value;
                    if (prop.Value is JArray)
                    {
                        JArray arr;
                        if (request[prop.Name] == null)
                        {
                            arr = new JArray();
                        }
                        else
                        {
                            arr = request.Value <JArray>(prop.Name);
                        }

                        arr.Merge(prop.Value, new JsonMergeSettings {
                            MergeArrayHandling = MergeArrayHandling.Union
                        });
                        value = arr;
                    }
                    else
                    {
                        var existing = request[prop.Name];
                        if (existing != null && !existing.Equals(prop.Value))
                        {
                            throw new Exception(string.Format("'{0}' is already defined for {1}, existing '{2}' !== new '{3}'", prop.Name, loader.Type, existing, prop.Value));
                        }
                        value = prop.Value;
                    }

                    request[prop.Name] = value;
                }

                var key = req.ToString();
                key = char.ToLower(key[0]) + key.Substring(1);
                _callbacks.Add((results, result) => result[key] = JToken.FromObject(loader.Callback(results[loader.Type])));
            }

            foreach (var request in _requests.Values)
            {
                foreach (var prop in request.Properties())
                {
                    var arr = prop.Value as JArray;
                    if (arr != null)
                    {
                        prop.Value = string.Join("|", arr.Values <string>());
                    }
                }
            }
        }
Пример #41
0
 /// <summary>
 /// Create new command result.
 /// </summary>
 /// <param name="Result">Human-readable description of the reason (if one can be provided), multiple languages can be provided.</param>
 /// <param name="Message">Result of the command request as sent by the charge point to the CPO.</param>
 public CommandResult(CommandResultTypes Result,
                      IEnumerable <DisplayText> Message)
 {
     this.Result  = Result;
     this.Message = Message?.Distinct() ?? new DisplayText[0];
 }
Пример #42
0
 public IEnumerable <TypescriptContract> GetTypeScriptReferences(IEnumerable <Type> types)
 {
     return(types.Distinct().Select(GetTypeScriptReference).Distinct().Where(x => x != null));
 }
Пример #43
0
        public IEnumerable <CocktailMatch> FindCocktails(IEnumerable <Ingredients> ingredients = null,
                                                         IEnumerable <Ingredients> exgredients = null,
                                                         IEnumerable <Vessels> vessels         = null)
        {
            ingredients = ingredients?.Distinct()?.ToList();
            var nonOptionalIngredients = "CI.IsOptional = 0 AND CI.Ingredient not in @nonFullnessIngredients";

            using (var db = new SqlConnection(connectionString))
            {
                var cocktailSql = $@"
                    WITH
                    IncludedIngredientRoot AS (
                        SELECT *
                        FROM Ingredient WHERE Id IN @ingredients
                    ),
                    IncludedIngredientUp AS (
                        SELECT *, Id AS QueryIngredient
                        FROM IncludedIngredientRoot
                        UNION ALL
                        SELECT P.*, C.QueryIngredient
                        FROM IncludedIngredientUp C
                        JOIN IngredientRelationship IR ON IR.Child = C.Id
                        JOIN Ingredient P ON P.Id = IR.Parent
                    ),
                    IncludedIngredientDown AS (
                        SELECT *, Id AS QueryIngredient
                        FROM IncludedIngredientRoot
                        UNION ALL
                        SELECT C.*, P.QueryIngredient
                        FROM IncludedIngredientDown P
                        JOIN IngredientRelationship IR ON IR.Parent = P.Id
                        JOIN Ingredient C ON C.Id = IR.Child
                    ),
                    IncludedIngredient AS (
                        SELECT * FROM IncludedIngredientUp
                        UNION
                        SELECT * FROM IncludedIngredientDown
                    ),
                    ExcludedIngredient AS (
                        SELECT *
                        FROM Ingredient WHERE Id IN @exgredients
                        UNION ALL
                        SELECT C.*
                        FROM ExcludedIngredient P
                        JOIN IngredientRelationship IR ON IR.Parent = P.Id
                        JOIN Ingredient C ON C.Id = IR.Child
                    ),
                    NonExcludedCocktail AS (
                        SELECT C.*
                        FROM Cocktail C
                        LEFT JOIN CocktailIngredient CI ON CI.Cocktail = C.Id
                        AND CI.Ingredient IN (SELECT Id FROM ExcludedIngredient)
                        WHERE CI.Id IS NULL
                    ),
                    MatchingCocktail AS (
                        SELECT C.Id, C.Name, C.Color, C.Vessel, C.VesselName, C.PrepMethod, C.PrepMethodName,
                        COUNT(*) AS IngredientCount,
                        (CAST(C.FullnessCount AS float) / COUNT(*)) AS Fullness,
                        (CAST(C.CompletenessCount AS float) / NULLIF(@ingredientsCount, 0)) AS Completeness
                        FROM (
                            SELECT C.Id, C.Name, C.Color,
                            C.Vessel, V.Name AS VesselName,
                            C.PrepMethod, P.Name AS PrepMethodName,
                            COUNT(DISTINCT (CASE WHEN {nonOptionalIngredients} THEN II.Id END)) AS FullnessCount,
                            COUNT(DISTINCT II.QueryIngredient) AS CompletenessCount
                            FROM NonExcludedCocktail C
                            LEFT JOIN CocktailIngredient CI ON CI.Cocktail = C.Id
                            LEFT JOIN IncludedIngredient II ON II.Id = CI.Ingredient
                            LEFT JOIN Vessel V ON V.Id = C.Vessel
                            LEFT JOIN PrepMethod P ON P.Id = C.PrepMethod
                            WHERE (@noVessels = 1 OR C.Vessel in @vessels)
                            AND (NOT EXISTS (SELECT TOP 1 * FROM IncludedIngredient)
                            OR II.Id IS NOT NULL)
                            GROUP BY C.Id, C.Name, C.Color, C.Vessel, V.Name, C.PrepMethod, P.Name
                        ) AS C
                        LEFT JOIN CocktailIngredient CI ON CI.Cocktail = C.Id
                        WHERE {nonOptionalIngredients}
                        GROUP BY C.Id, C.Name, C.Color,
                        C.Vessel, C.VesselName, C.PrepMethod, C.PrepMethodName,
                        C.FullnessCount, C.CompletenessCount
                    )
                    SELECT * FROM MatchingCocktail
                    ORDER BY
                        IIF(Fullness >= Completeness, Fullness, Completeness) DESC,
                        IIF(Fullness < Completeness, Fullness, Completeness) DESC,
                        IngredientCount ASC,
                        Id ASC
                ";

                var cocktails = db.Query <CocktailMatch>(cocktailSql,
                                                         new {
                    ingredientsCount = ingredients?.Count() ?? 0,
                    ingredients,
                    exgredients,
                    noVessels = vessels == null,
                    vessels,
                    nonFullnessIngredients = new List <i> {
                        i.Water, i.Sugar,
                        i.Bitters, i.Angostura, i.OrangeBitters, i.Peychauds
                    }
                });

                foreach (var cocktail in cocktails)
                {
                    cocktail.Recipe = CocktailIngredients(db, cocktail.Id);
                }
                return(cocktails);
            }
        }
Пример #44
0
 internal SchemaValidationResults(IEnumerable <SchemaValidationError> errors = null)
 {
     Errors = errors?.Distinct() ?? Enumerable.Empty <SchemaValidationError>();
 }
 /// <summary>
 /// Creates a new instance of the <see cref="ModelCollection"/> type.
 /// </summary>
 /// <param name="modelPaths"> A collection with the used model paths. </param>
 public ModelCollection(IEnumerable <string> modelPaths)
 {
     Models = modelPaths?.Distinct()?.ToDictionary(path => Path.GetFileNameWithoutExtension(path), path => path) ?? new Dictionary <string, string>();
 }
Пример #46
0
 public static IEnumerable <PracticeFrameworkViewModel> From(IEnumerable <tblTest> lst)
 {
     return(lst?.Distinct().Select(From).ToList());
 }
Пример #47
0
 public PaperAggregateCatalog(IEnumerable <Type> paperTypes)
 {
     paperTypes?.Distinct().ForEach(Add);
 }
Пример #48
0
 public void AddRange(IEnumerable <Type> paperTypes)
 {
     paperTypes?.Distinct().ForEach(Add);
 }
Пример #49
0
 public static IEnumerable <T> Distinct <T>(this IEnumerable <T> source, Func <T, T, bool> comparer)
 {
     return(source.Distinct(new LambdaEqualityComparer <T>(comparer)));
 }
Пример #50
0
        public async Task <IReadOnlyCollection <T> > GetByIdsAsync(IEnumerable <string> ids, bool useCache = false, TimeSpan?expiresIn = null)
        {
            var idList = ids?.Distinct().Where(i => !String.IsNullOrEmpty(i)).ToList();

            if (idList == null || idList.Count == 0)
            {
                return(EmptyList);
            }

            if (!HasIdentity)
            {
                throw new NotSupportedException("Model type must implement IIdentity.");
            }

            var hits = new List <T>();

            if (IsCacheEnabled && useCache)
            {
                var cacheHits = await Cache.GetAllAsync <T>(idList).AnyContext();

                hits.AddRange(cacheHits.Where(kvp => kvp.Value.HasValue).Select(kvp => kvp.Value.Value));
            }

            var itemsToFind = idList.Except(hits.OfType <IIdentity>().Select(i => i.Id)).ToList();

            if (itemsToFind.Count == 0)
            {
                return(hits.AsReadOnly());
            }

            var multiGet = new MultiGetDescriptor();

            if (!HasParent)
            {
                itemsToFind.ForEach(id => multiGet.Get <T>(f => f.Id(id).Index(GetIndexById(id)).Type(ElasticType.Name)));

                var multiGetResults = await _client.MultiGetAsync(multiGet).AnyContext();

                _logger.Trace(() => multiGetResults.GetRequest());

                foreach (var doc in multiGetResults.Documents)
                {
                    if (!doc.Found)
                    {
                        continue;
                    }

                    hits.Add(((IMultiGetHit <T>)doc).ToFindHit().Document);
                    itemsToFind.Remove(doc.Id);
                }
            }

            // fallback to doing a find
            if (itemsToFind.Count > 0 && (HasParent || HasMultipleIndexes))
            {
                hits.AddRange((await FindAsync(NewQuery().WithIds(itemsToFind)).AnyContext()).Hits.Where(h => h.Document != null).Select(h => h.Document));
            }

            if (IsCacheEnabled && useCache)
            {
                foreach (var item in hits.OfType <IIdentity>())
                {
                    await Cache.SetAsync(item.Id, item, expiresIn.HasValue?SystemClock.UtcNow.Add(expiresIn.Value) : SystemClock.UtcNow.AddSeconds(ElasticType.DefaultCacheExpirationSeconds)).AnyContext();
                }
            }

            return(hits.AsReadOnly());
        }
Пример #51
0
 public void SetMembersOrder(IEnumerable <string> value) => MembersOrder = value?.Distinct().ToArray() ?? throw new ArgumentNullException(nameof(value));
Пример #52
0
 /// <summary>
 /// Create a new references to location details.
 /// </summary>
 /// <param name="LocationId">Unique identifier for the location..</param>
 /// <param name="EVSEUIds">Optional enumeration of EVSE identifiers within the CPO’s platform.</param>
 public LocationReference(Location_Id LocationId,
                          IEnumerable <EVSE_UId> EVSEUIds = null)
 {
     this.LocationId = LocationId;
     this.EVSEUIds   = EVSEUIds?.Distinct().OrderBy(evseUId => evseUId).ToArray() ?? new EVSE_UId[0];
 }
Пример #53
0
        /// <summary>
        /// Send email(s) over SendGrid’s v3 Web API.
        /// </summary>
        /// <param name="personalizations">The personalizations.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="contents">The contents.</param>
        /// <param name="from">From.</param>
        /// <param name="replyTo">The reply-to addresses.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="templateId">The template identifier.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="customArgs">The custom arguments.</param>
        /// <param name="sendAt">The send at.</param>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="unsubscribeOptions">The unsubscribe options.</param>
        /// <param name="ipPoolName">Name of the ip pool.</param>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="trackingSettings">The tracking settings.</param>
        /// <param name="priority">The priority.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>
        /// The message id.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients.</exception>
        /// <exception cref="Exception">Email exceeds the size limit.</exception>
        public async Task <string> SendAsync(
            IEnumerable <MailPersonalization> personalizations,
            string subject,
            IEnumerable <MailContent> contents,
            MailAddress from,
            IEnumerable <MailAddress> replyTo    = null,
            IEnumerable <Attachment> attachments = null,
            string templateId = null,
            IEnumerable <KeyValuePair <string, string> > headers = null,
            IEnumerable <string> categories = null,
            IEnumerable <KeyValuePair <string, string> > customArgs = null,
            DateTime?sendAt = null,
            string batchId  = null,
            UnsubscribeOptions unsubscribeOptions = null,
            string ipPoolName                   = null,
            MailSettings mailSettings           = null,
            TrackingSettings trackingSettings   = null,
            MailPriority priority               = MailPriority.Normal,
            CancellationToken cancellationToken = default)
        {
            if (_client?.BaseClient?.DefaultRequestHeaders?.Authorization?.Scheme?.Equals("Basic", StringComparison.OrdinalIgnoreCase) ?? false)
            {
                const string errorMessage  = "SendGrid does not support Basic authentication when sending transactional emails.";
                const string diagnosticLog = "This request was not dispatched to SendGrid because the exception returned by their API in this scenario is not clear: 'Permission denied, wrong credentials'.";
                throw new SendGridException(errorMessage, null, diagnosticLog);
            }

            if (personalizations == null || !personalizations.Any())
            {
                throw new ArgumentNullException(nameof(personalizations));
            }

            // This comparer is used to perform case-insensitive comparisons of email addresses
            var emailAddressComparer = new LambdaComparer <MailAddress>((address1, address2) => address1.Email.Equals(address2.Email, StringComparison.OrdinalIgnoreCase));

            // It's important to make a copy of the personalizations to ensure we don't modify the original array
            var personalizationsCopy = personalizations.Where(p => p != null).ToArray();

            foreach (var personalization in personalizationsCopy)
            {
                // Make sure the arrays are not null otherwise Linq's 'Except' method will throw a ArgumentNull exception (See GH-286).
                if (personalization.To == null)
                {
                    personalization.To = Array.Empty <MailAddress>();
                }
                if (personalization.Cc == null)
                {
                    personalization.Cc = Array.Empty <MailAddress>();
                }
                if (personalization.Bcc == null)
                {
                    personalization.Bcc = Array.Empty <MailAddress>();
                }

                // Avoid duplicate addresses. This is important because SendGrid does not throw any
                // exception when a recipient is duplicated (which gives you the impression the email
                // was sent) but it does not actually send the email
                personalization.To = personalization.To
                                     .Distinct(emailAddressComparer)
                                     .ToArray();
                personalization.Cc = personalization.Cc
                                     .Distinct(emailAddressComparer)
                                     .Except(personalization.To, emailAddressComparer)
                                     .ToArray();
                personalization.Bcc = personalization.Bcc
                                      .Distinct(emailAddressComparer)
                                      .Except(personalization.To, emailAddressComparer)
                                      .Except(personalization.Cc, emailAddressComparer)
                                      .ToArray();

                // SendGrid doesn't like empty arrays
                if (!personalization.To.Any())
                {
                    personalization.To = null;
                }
                if (!personalization.Cc.Any())
                {
                    personalization.Cc = null;
                }
                if (!personalization.Bcc.Any())
                {
                    personalization.Bcc = null;
                }

                // Surround recipient names with double-quotes if necessary
                personalization.To  = EnsureRecipientsNamesAreQuoted(personalization.To);
                personalization.Cc  = EnsureRecipientsNamesAreQuoted(personalization.Cc);
                personalization.Bcc = EnsureRecipientsNamesAreQuoted(personalization.Bcc);

                // Indicate if a dynamic template is being used. This is used by MailPersonalizationConverter to generate the appropriate JSON
                personalization.IsUsedWithDynamicTemplate = Template.IsDynamic(templateId);
            }

            // The total number of recipients must be less than 1000. This includes all recipients defined within the to, cc, and bcc parameters, across each object that you include in the personalizations array.
            var numberOfRecipients = personalizationsCopy.Sum(p => p.To?.Count(r => r != null) ?? 0);

            numberOfRecipients += personalizationsCopy.Sum(p => p.Cc?.Count(r => r != null) ?? 0);
            numberOfRecipients += personalizationsCopy.Sum(p => p.Bcc?.Count(r => r != null) ?? 0);
            if (numberOfRecipients >= 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(numberOfRecipients), numberOfRecipients, "The total number of recipients must be less than 1000");
            }

            // Get the priority headers
            if (!_priorityHeaders.TryGetValue(priority, out KeyValuePair <string, string>[] priorityHeaders))
            {
                throw new Exception($"{priority} is an unknown priority");
            }

            // Combine headers with priority headers making sure not to duplicate priority headers
            var combinedHeaders = (headers ?? Array.Empty <KeyValuePair <string, string> >())
                                  .Where(kvp => !priorityHeaders.Any(p => p.Key.Equals(kvp.Key, StringComparison.OrdinalIgnoreCase)))
                                  .Concat(priorityHeaders);

            // Remove duplicates from the list of 'reply-to' addresses
            var cleanReplyTo = replyTo?.Distinct(emailAddressComparer) ?? Enumerable.Empty <MailAddress>();

            // SendGrid allows no more than 1000 'reply-to' addresses
            var numberOfReplyToAddresses = cleanReplyTo.Count();

            if (numberOfReplyToAddresses > 1000)
            {
                throw new ArgumentOutOfRangeException(nameof(numberOfReplyToAddresses), numberOfReplyToAddresses, "The number of distinct reply-to addresses can't exceed 1000");
            }

            // Serialize the mail message
            var data = new StrongGridJsonObject();

            data.AddProperty("from", from);
            data.AddProperty("reply_to_list", cleanReplyTo);
            data.AddProperty("subject", subject);
            data.AddProperty("content", contents);
            data.AddProperty("attachments", attachments);
            data.AddProperty("template_id", templateId);
            data.AddProperty("categories", categories);
            data.AddProperty("send_at", sendAt?.ToUnixTime());
            data.AddProperty("batch_id", batchId);
            data.AddProperty("asm", unsubscribeOptions);
            data.AddProperty("ip_pool_name", ipPoolName);
            data.AddProperty("mail_settings", mailSettings);
            data.AddProperty("tracking_settings", trackingSettings);
            data.AddProperty("personalizations", personalizationsCopy);
            data.AddProperty("headers", ConvertEnumerationToJson(combinedHeaders));
            data.AddProperty("custom_args", ConvertEnumerationToJson(customArgs));

            // SendGrid does not allow emails that exceed 30MB
            var serializedContent = JsonSerializer.Serialize(data, typeof(StrongGridJsonObject), JsonFormatter.SerializationContext);

            if (serializedContent.Length > MAX_EMAIL_SIZE)
            {
                throw new Exception("Email exceeds the size limit");
            }

            // Send the request
            var response = await _client
                           .PostAsync($"{_endpoint}/send")
                           .WithJsonBody(data)
                           .WithCancellationToken(cancellationToken)
                           .AsResponse()
                           .ConfigureAwait(false);

            // Get the messageId from the response
            return(response.Message.Headers.GetValue("X-Message-Id"));
        }
Пример #54
0
        /// <summary>
        /// Rebuilds and submits to index all indexables created from Interactions collection using the
        /// <see cref="ICollectionDataProvider"/> as a source.
        /// and submits them to the index using <see cref="IAnalyticsSearchService"/>
        /// <para>
        /// This includes building of 'visit', 'visitPage' and 'visitPageEvent' indexable types
        /// </para>
        /// </summary>
        /// <param name="contactIds">
        /// Specify contact ID's you want to rebuild interaction indexables for.
        /// </param>
        public virtual void RebuildVisitIndexableTypes(IEnumerable <Guid> contactIds)
        {
            var all = contactIds == null;
            var ids = contactIds as ICollection <Guid> ?? contactIds?.Distinct().ToList();

            this.SafeExecution($"rebuilding [{this.visitUpdater.IndexableType}, {this.visitPageUpdater.IndexableType}, {this.visitPageEventUpdater.IndexableType}] indexables {(all ? "for all visits in collection database" : $"for {ids.Count} contacts")}", () =>
Пример #55
0
 /// <summary>
 /// 自定义Distinct扩展方法
 /// </summary>
 /// <typeparam name="T">要去重的对象类</typeparam>
 /// <typeparam name="C">自定义去重的字段类型</typeparam>
 /// <param name="source">要去重的对象</param>
 /// <param name="getfield">获取自定义去重字段的委托</param>
 /// <returns></returns>
 public static IEnumerable <T> MyDistinct <T, C>(this IEnumerable <T> source, Func <T, C> getfield)
 {
     return(source.Distinct(new CommonEqualityComparer <T, C>(getfield)));
 }
        private void VerifyInstanceInformation(
            CloudTable table,
            IEnumerable <DynamicTableEntity> records,
            int partIdx,
            bool hasDeletionEventWithIdOnly)
        {
            // Verify that the number of instances is what we expect
            int expectedInstanceCount = InstancesForPartition(partIdx);
            EqualityComparerInstanceProperty instanceComparer = new EqualityComparerInstanceProperty();
            IEnumerable <DynamicTableEntity> distinctRecords  = records.Distinct(instanceComparer);
            int numInstances = distinctRecords.Count();

            if (expectedInstanceCount != numInstances)
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Unexpected instance count for table {0} partition {1}. Expected instance count: {2}, Actual instance count: {3}.",
                    table.Name,
                    partIdx,
                    expectedInstanceCount,
                    numInstances);
                Verify.Fail("Unexpected instance count");
            }

            // Verify that the instance values are as expected
            long maxInstanceValue = records.Max(
                r => { return((long)r.Properties[AzureTableUploaderTest.DcaInstanceProperty].Int64Value); });

            if (maxInstanceValue != (numInstances - 1))
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Unexpected maximum instance value for table {0} partition {1}. Expected max: {2}, Actual max: {3}.",
                    table.Name,
                    partIdx,
                    (numInstances - 1),
                    maxInstanceValue);
                Verify.Fail("Unexpected maximum entity data value in partition");
            }
            long minInstanceValue = records.Min(
                r => { return((long)r.Properties[AzureTableUploaderTest.DcaInstanceProperty].Int64Value); });

            if (minInstanceValue != 0)
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Unexpected minimum instance value for table {0} partition {1}. Expected min: {2}, Actual min: {3}.",
                    table.Name,
                    partIdx,
                    0,
                    minInstanceValue);
                Verify.Fail("Unexpected maximum entity data value in partition");
            }

            // Verify that each instance has the expected number of events
            for (long i = 0; i <= maxInstanceValue; i++)
            {
                int eventsForInstance = records
                                        .Where(r => { return(i == (long)r.Properties[AzureTableUploaderTest.DcaInstanceProperty].Int64Value); })
                                        .Count();
                int expectedEventsForInstance = ((i != maxInstanceValue) || (false == hasDeletionEventWithIdOnly)) ? EventsPerInstance : (EventsPerInstance - 1);
                if (eventsForInstance != expectedEventsForInstance)
                {
                    Utility.TraceSource.WriteError(
                        AzureTableUploaderTest.TraceType,
                        "Unexpected event count for instance {0} in table {1} partition {2}. Expected count: {3}, Actual count: {4}.",
                        i,
                        table.Name,
                        partIdx,
                        expectedEventsForInstance,
                        eventsForInstance);
                    Verify.Fail("Unexpected event count for instance");
                }
            }
        }
Пример #57
0
 public static IEnumerable <T> Distinct <T, V>(this IEnumerable <T> source, Func <T, V> keySelector, IEqualityComparer <V> comparer)
 {
     return(source.Distinct(new CommonEqualityComparer <T, V>(keySelector, comparer)));
 }
        private void VerifyPartitionEntities(
            CloudTable table,
            IEnumerable <DynamicTableEntity> records,
            int partIdx,
            int expectedEntityCount,
            EqualityComparerDataProperty dataComparer,
            int expectedEntitiesWithDuplicateData,
            bool recordsContainInstanceInfo)
        {
            string recordDescription = recordsContainInstanceInfo ? "records with instance information" : "records without instance information";

            // Verify the entity count
            int numRecords = records.Count();

            if (numRecords != expectedEntityCount)
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Table {0} partition {1} does not have the expected number of {2}. Expected records: {3}, actual records: {4}.",
                    table.Name,
                    partIdx,
                    recordDescription,
                    expectedEntityCount,
                    numRecords);
                Verify.Fail("Unexpected count of records");
            }

            // Verify that the records do not have duplicate data
            IEnumerable <DynamicTableEntity> distinctRecords =
                records.Distinct(dataComparer);
            int numDistinctRecords = distinctRecords.Count();

            if ((numRecords - numDistinctRecords) != expectedEntitiesWithDuplicateData)
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "We found duplicate data in {0} {1}, but we expected duplicate data in {2} records. Table {3}, partition {4}.",
                    (numRecords - numDistinctRecords),
                    recordDescription,
                    expectedEntitiesWithDuplicateData,
                    table.Name,
                    partIdx);
                Verify.Fail("Unexpected partition records with duplicate data");
            }

            // Verify that the data values are as expected
            int maxDataValue = records.Max(
                r => { return((int)r.Properties[AzureTableUploaderTest.DataProperty].Int32Value); });

            if (maxDataValue != (numDistinctRecords - 1))
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Unexpected maximum data value for {0} in table {1} partition {2}. Expected max: {3}, Actual max: {4}.",
                    recordDescription,
                    table.Name,
                    partIdx,
                    (numRecords - 1),
                    maxDataValue);
                Verify.Fail("Unexpected maximum entity data value in partition");
            }
            int minDataValue = records.Min(
                r => { return((int)r.Properties[AzureTableUploaderTest.DataProperty].Int32Value); });

            if (minDataValue != 0)
            {
                Utility.TraceSource.WriteError(
                    AzureTableUploaderTest.TraceType,
                    "Unexpected minimum data value for {0} in table {1} partition {2}. Expected min: {3}, Actual min: {4}.",
                    recordDescription,
                    table.Name,
                    partIdx,
                    0,
                    minDataValue);
                Verify.Fail("Unexpected maximum entity data value in partition");
            }
        }
Пример #59
0
 /// <summary>
 /// Determines if a list of <typeparam name="T"></typeparam> is a distinct list. An empty list is considered distinct.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static bool IsDistinct <T>(this IEnumerable <T> s)
 {
     return(s?.Distinct()?.Count() == s?.Count());
 }
Пример #60
0
 public StringGenerator(int seed, IEnumerable <char> usedChars, int maxLength)
     : base(seed)
 {
     UsedChars = usedChars?.Distinct().ToArray() ?? throw new NullReferenceException();
     MaxLength = maxLength >= 0 ? maxLength : throw new ArgumentOutOfRangeException();
 }