System.Collections.Generic.IEnumerable.Single()

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Single() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1646 Examples 7

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveFeatures_IdsEnumerableVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Feature<Point>("point1", new Point());
            var point2 = new Feature<Point>("point2", new Point());
            var features = new List<Feature<Point>> { point1, point2 };

            await dataSource.AddAsync(features);
            await dataSource.RemoveAsync(new List<string> { point1.Id });

            replacedert.DoesNotContain(point1, dataSource.Features);
            replacedert.Contains(point2, dataSource.Features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveShapes_EnumerableVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Shape<Point>("point1", new Point());
            var point2 = new Shape<Point>("point2", new Point());
            var shapes = new List<Shape<Point>> { point1, point2 };

            await dataSource.AddAsync(shapes);
            await dataSource.RemoveAsync(new List<Shape> { point1 });

            replacedert.DoesNotContain(point1, dataSource.Shapes);
            replacedert.Contains(point2, dataSource.Shapes);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alexx999

static void Main(string[] args)
        {
            if (args.Length != 3 && args.Length != 4)
            {
                Console.WriteLine("Wrong argument count.\nUsage:\ndumper.exe <debugged process id or name> <memory_start_addr> <memory_length> (-unprotect)");
                return;
            }

            if (!TryParse(args[1], out var address))
            {
                Console.WriteLine($"Bad address value {args[1]}");
                return;
            }

            if (!TryParse(args[2], out var length))
            {
                Console.WriteLine($"Bad length value {args[2]}");
                return;
            }

            var unprotect = args.Length > 3 && args[3] == "-unprotect";

            if (!int.TryParse(args[0], out var processId))
            {
                var processName = args[0];
                var process = Process.GetProcessesByName(processName);
                if (process.Length == 0)
                {
                    Console.WriteLine($"Process {processName} not found");
                    return;
                }
                if (process.Length > 1)
                {
                    Console.WriteLine($"Found more than one instance of process with name {processName}");
                    return;
                }
                processId = process.Single().Id;
            }

            var rights = ProcessAccessFlags.VirtualMemoryRead;
            if (unprotect)
            {
                rights |= ProcessAccessFlags.SuspendResume | ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryOperation;
            }

            using (var process = OpenProcess(rights, false, processId))
            {
                if (process.IsInvalid)
                {
                    Console.WriteLine($"Opening process {processId} failed with error {Marshal.GetLastWin32Error()}");
                    return;
                }

                var outFileName = $"{args[0]}-{args[1]}-{args[2]}";

                outFileName = GetNextFreeName(outFileName, ".dmp");

                Console.WriteLine($"Saving contents of process {processId} to {outFileName}");

                List<MemBlock> unprotected = null;

                if (unprotect)
                {
                    NtSuspendProcess(process.DangerousGetHandle());

                    try
                    {
                        Console.WriteLine("Unprotecting");
                        unprotected = Unprotect(process, new IntPtr(address), new IntPtr(length));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Unprotecting failed with exception {e}");
                        return;
                    }
                }

                try
                {
                    Dump(process, outFileName, new IntPtr(address), new IntPtr(length), unprotect);
                    Console.WriteLine("Done");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Writing file failed with exception {e}");
                }


                if (unprotect)
                {
                    Protect(process, unprotected);
                    NtResumeProcess(process.DangerousGetHandle());
                }
            }
        }

19 View Source File : FetchAvailableScenesUseCaseTests.cs
License : Apache License 2.0
Project Creator : Anapher

[Fact]
        public async Task Handle_OneProvider_FetchResultFromProvidersAndCache()
        {
            // arrange
            var useCase = Create();
            var sceneStack = new List<IScene> {new Mock<IScene>().Object};

            _sceneProvider.Setup(x => x.GetAvailableScenes(ConferenceId, RoomId, sceneStack)).ReturnsAsync(sceneStack);

            // act
            var result = await useCase.Handle(new FetchAvailableScenesRequest(ConferenceId, RoomId, sceneStack),
                CancellationToken.None);

            // replacedert
            replacedert.Single(result, sceneStack.Single());
        }

19 View Source File : OpenApiSchemaExtensions.cs
License : MIT License
Project Creator : aliencube

[Obsolete("This method is now obsolete", error: true)]
        public static OpenApiSchema ToOpenApiSchema(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null)
        {
            return ToOpenApiSchemas(type, namingStrategy, attribute, true).Single().Value;
        }

19 View Source File : ExtensionMethods.cs
License : GNU General Public License v3.0
Project Creator : Albo1125

public static T PickRandom<T>(this IEnumerable<T> source)
        {
            return source.PickRandom(1).Single();
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_NotRemoveFeaturesButOnlyShapes_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var shape = new Shape<Point>("point1", new Point());
            var feature = new Feature<Point>("point2", new Point());

            Shape[] shapes = new[] { shape };
            Feature[] features = null;

            await dataSource.AddAsync(shape);
            await dataSource.AddAsync(feature);
            await dataSource.RemoveAsync(shapes, features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == shape.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : EntityListDataAdapter.cs
License : MIT License
Project Creator : Adoxio

protected void AddSelectableFilterToFetchEnreplacedy(FetchEnreplacedy fetchEnreplacedy, EnreplacedyListSettings settings, string filter)
		{
			var user = Dependencies.GetPortalUser();

			foreach (var condition in GetConditions(fetchEnreplacedy).Where(condition => condition.UiType == "contact"))
			{
				condition.Value = user == null ? Guid.Empty : user.Id;
			}

			var userAccount = GetPortalUserAccount(user);

			foreach (var condition in GetConditions(fetchEnreplacedy).Where(condition => condition.UiType == "account"))
			{
				condition.Value = userAccount == null ? Guid.Empty : userAccount.Id;
			}

			// Build dictionary of available selectable filters.
			var filters = new Dictionary<string, Action>(StringComparer.InvariantCultureIgnoreCase);

			if (!string.IsNullOrWhiteSpace(settings.FilterPortalUserFieldName))
			{
				filters["user"] = () => AddEnreplacedyReferenceFilterToFetchEnreplacedy(fetchEnreplacedy, settings.FilterPortalUserFieldName, user);
			}

			if (!string.IsNullOrWhiteSpace(settings.FilterAccountFieldName))
			{
				filters["account"] = () => AddEnreplacedyReferenceFilterToFetchEnreplacedy(fetchEnreplacedy, settings.FilterAccountFieldName, userAccount);
			}

			// If there are no filters, apply nothing.
			if (filters.Count < 1)
			{
				return;
			}

			// If there is only one filter defined, apply it automatically.
			if (filters.Count == 1)
			{
				filters.Single().Value();

				return;
			}

			Action applyFilter;

			// Try look up the specified filter in the filter dictionary. Apply it if found.
			if (filter != null && filters.TryGetValue(filter, out applyFilter))
			{
				applyFilter();

				return;
			}

			// If the specified filter is not found, try apply the user filter.
			if (filters.TryGetValue("user", out applyFilter))
			{
				applyFilter();

				return;
			}

			// If the user filter is not found, try apply the account filter.
			if (filters.TryGetValue("account", out applyFilter))
			{
				applyFilter();

				return;
			}
		}

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveFeatures_IdsVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Feature<Point>("point1", new Point());
            var point2 = new Feature<Point>("point2", new Point());
            var features = new List<Feature<Point>> { point1, point2 };

            await dataSource.AddAsync(features);
            await dataSource.RemoveAsync(point1.Id);

            replacedert.DoesNotContain(point1, dataSource.Features);
            replacedert.Contains(point2, dataSource.Features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : CaseEntitlement.cs
License : MIT License
Project Creator : Adoxio

protected virtual void ProcessSupportPlans(List<Enreplacedy> plans)
		{
			Controls.Clear();
			var context = PortalCrmConfigurationManager.CreateServiceContext(PortalName);
			NumberOfPlans = plans.Count();
			if (NumberOfPlans > 1)
			{
				SupportPlanID = Guid.Empty;
				// Multiple plans found so prompt for single plan selection
				var snippetHelpDeskEnreplacedlementSelectPlan = new Literal { ID = "SelectPlan", Text = DefaultSnippetHelpDeskEnreplacedlementSelectPlan };
				var snippet = context.CreateQuery("adx_contentsnippet").FirstOrDefault(c => c.GetAttributeValue<string>("adx_name") == "Help Desk Enreplacedlement Select Plan");
				if (snippet != null)
				{
					snippetHelpDeskEnreplacedlementSelectPlan.Text = !string.IsNullOrWhiteSpace(snippet.GetAttributeValue<string>("adx_value")) ? snippet.GetAttributeValue<string>("adx_value") : DefaultSnippetHelpDeskEnreplacedlementSelectPlan;
				}
				var panelHelpDeskEnreplacedlementSelectPlan = new Panel { ID = "EnreplacedlementSelectPlanPanel" };
				panelHelpDeskEnreplacedlementSelectPlan.Controls.Add(snippetHelpDeskEnreplacedlementSelectPlan);
				var p = new HtmlGenericControl("p");
				var supportPlans = plans.OrderBy(o => o.GetAttributeValue<string>("adx_name")).Select(o => new { DataValueField = o.GetAttributeValue<Guid>("adx_supportplanid").ToString(), DataTextField = string.Format("{0}: Prepaid Incidents Remaining {1}", o.GetAttributeValue<string>("adx_name"), o.GetAttributeValue<int>("adx_allotmentsremaining")) });
				var planList = new RadioButtonList
				{
					ID = "PlanDropDown",
					DataSource = supportPlans,
					DataTextField = "DataTextField",
					DataValueField = "DataValueField",
					AppendDataBoundItems = true,
					AutoPostBack = true,
					ValidationGroup = ValidationGroup,
					CssClreplaced = "cell checkbox-cell",
					RepeatLayout = RepeatLayout.Flow
				};
				planList.DataBind();
				planList.SelectedIndexChanged += PlanRadioButtonList_SelectedIndexChanged;
				p.Controls.Add(planList);
				var requiredValidator = new RequiredFieldValidator
				{
					ID = "PlanDropDownRequiredFieldValidator",
					ControlToValidate = planList.ID,
					Display = ValidatorDisplay.Static,
					ErrorMessage = ResourceManager.GetString("Select_Support_Plan_Error_Message"),
					ValidationGroup = ValidationGroup,
					InitialValue = string.Empty,
					CssClreplaced = "help-block error",
				};
				p.Controls.Add(requiredValidator);
				panelHelpDeskEnreplacedlementSelectPlan.Controls.Add(p);
				AddContextualButtons(panelHelpDeskEnreplacedlementSelectPlan);
				Controls.Add(panelHelpDeskEnreplacedlementSelectPlan);
			}
			else if (NumberOfPlans == 1)
			{
				var plan = plans.Single();
				ProcessSingleSupportPlan(plan);
			}
			else
			{
				// No plan found so display no plan message
				SupportPlanID = Guid.Empty;
				var snippetHelpDeskEnreplacedlementNoPlan = new Literal { ID = "NoPlan", Text = DefaultSnippetHelpDeskEnreplacedlementNoPlan };
				var snippet = context.CreateQuery("adx_contentsnippet").FirstOrDefault(c => c.GetAttributeValue<string>("adx_name") == "Help Desk Enreplacedlement No Plan");
				if (snippet != null)
				{
					snippetHelpDeskEnreplacedlementNoPlan.Text = !string.IsNullOrWhiteSpace(snippet.GetAttributeValue<string>("adx_value")) ? snippet.GetAttributeValue<string>("adx_value") : DefaultSnippetHelpDeskEnreplacedlementNoPlan;
				}
				var panelHelpDeskEnreplacedlementNoPlan = new Panel { ID = "EnreplacedlementNoPanel" };
				panelHelpDeskEnreplacedlementNoPlan.Controls.Add(snippetHelpDeskEnreplacedlementNoPlan);
				AddContextualButtons(panelHelpDeskEnreplacedlementNoPlan);
				Controls.Add(panelHelpDeskEnreplacedlementNoPlan);
			}
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : AmolLearning

public static void ClickOnRowContainingText(this IList<IWebElement> elementList, string requiredText)
        {
            elementList.Where(x => x.Text.Contains(requiredText)).Single().Click();

        }

19 View Source File : ReleaseRepository.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task<ReleaseEnreplacedy> GetSucceededReleaseFromDb(string org, string app, string tagName)
        {
            List<string> buildResult = new List<string>();
            buildResult.Add(BuildResult.Succeeded.ToEnumMemberAttributeValue());

            IEnumerable<ReleaseEnreplacedy> releases = await Get(org, app, tagName, null, buildResult);
            return releases.Single();
        }

19 View Source File : ReflectionObject.cs
License : MIT License
Project Creator : akaskela

public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
        {
            ReflectionObject d = new ReflectionObject();

            ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory;

            if (creator != null)
            {
                d.Creator = delegateFactory.CreateParameterizedConstructor(creator);
            }
            else
            {
                if (ReflectionUtils.HasDefaultConstructor(t, false))
                {
                    Func<object> ctor = delegateFactory.CreateDefaultConstructor<object>(t);

                    d.Creator = args => ctor();
                }
            }

            foreach (string memberName in memberNames)
            {
                MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public);
                if (members.Length != 1)
                {
                    throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName));
                }

                MemberInfo member = members.Single();

                ReflectionMember reflectionMember = new ReflectionMember();

                switch (member.MemberType())
                {
                    case MemberTypes.Field:
                    case MemberTypes.Property:
                        if (ReflectionUtils.CanReadMemberValue(member, false))
                        {
                            reflectionMember.Getter = delegateFactory.CreateGet<object>(member);
                        }

                        if (ReflectionUtils.CanSetMemberValue(member, false, false))
                        {
                            reflectionMember.Setter = delegateFactory.CreateSet<object>(member);
                        }
                        break;
                    case MemberTypes.Method:
                        MethodInfo method = (MethodInfo)member;
                        if (method.IsPublic)
                        {
                            ParameterInfo[] parameters = method.GetParameters();
                            if (parameters.Length == 0 && method.ReturnType != typeof(void))
                            {
                                MethodCall<object, object> call = delegateFactory.CreateMethodCall<object>(method);
                                reflectionMember.Getter = target => call(target);
                            }
                            else if (parameters.Length == 1 && method.ReturnType == typeof(void))
                            {
                                MethodCall<object, object> call = delegateFactory.CreateMethodCall<object>(method);
                                reflectionMember.Setter = (target, arg) => call(target, arg);
                            }
                        }
                        break;
                    default:
                        throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name));
                }

                if (ReflectionUtils.CanReadMemberValue(member, false))
                {
                    reflectionMember.Getter = delegateFactory.CreateGet<object>(member);
                }

                if (ReflectionUtils.CanSetMemberValue(member, false, false))
                {
                    reflectionMember.Setter = delegateFactory.CreateSet<object>(member);
                }

                reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member);

                d.Members[memberName] = reflectionMember;
            }

            return d;
        }

19 View Source File : MediatorNotificationCollector.cs
License : Apache License 2.0
Project Creator : Anapher

public void replacedertSingleNotificationIssued<T>(Func<T, bool> filter, Action<T>? replacedertNotificationFunc = null)
            where T : INotification
        {
            var notification = _notifications.OfType<T>().Where(filter).Single();
            _notifications.Remove(notification);

            replacedertNotificationFunc?.Invoke(notification);
        }

19 View Source File : SuppressionFileIOTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

[Fact]
		public void CheckSuppressionMessageConversion_FromXml()
		{
			var xElement = GetXElementsToCheck().Take(1).Single();
			var target = xElement.Element("target").Value;
			var syntaxNode = xElement.Element("syntaxNode").Value;

			var messageToCheck = SuppressMessage.MessageFromElement(xElement);

			messageToCheck.Should().NotBeNull();
			messageToCheck.Value.Id.Should().Be(xElement.Attribute("id").Value);
			messageToCheck.Value.Target.Should().Be(target);
			messageToCheck.Value.SyntaxNode.Should().Be(syntaxNode);
		}

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveShapes_IdsEnumerableVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Shape<Point>("point1", new Point());
            var point2 = new Shape<Point>("point2", new Point());
            var shapes = new List<Shape<Point>> { point1, point2 };

            await dataSource.AddAsync(shapes);
            await dataSource.RemoveAsync(new List<string> { point1.Id });

            replacedert.DoesNotContain(point1, dataSource.Shapes);
            replacedert.Contains(point2, dataSource.Shapes);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereIn<TEnreplacedy, TValue>
          (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, TValue>> selector,
            IEnumerable<TValue> values
          )
        {
            /*
             * 实现效果:
             * var names = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='A' OR Name='B' OR Name='C'
             * 实际上,可以直接这样:
             * var query = DbContext.User.Where(m => names.Contains(m.Name));
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            IEnumerable<Expression> equals = values.Select(value => (Expression)Expression.Equal(selector.Body, Expression.Constant(value, typeof(TValue))));
            Expression body = equals.Aggregate((acreplacedulate, equal) => Expression.Or(acreplacedulate, equal));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveShapes_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Shape<Point>("point1", new Point());
            var point2 = new Shape<Point>("point2", new Point());
            var shapes = new List<Shape<Point>> { point1, point2 };

            await dataSource.AddAsync(shapes);
            await dataSource.RemoveAsync(point1);

            replacedert.DoesNotContain(point1, dataSource.Shapes);
            replacedert.Contains(point2, dataSource.Shapes);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

public TInstance With<TInstance, TValue>(TInstance source, Expression<Func<TInstance, TValue>> expression, TValue value)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var processContext = new ProcessContext<TInstance>()
            {
                Source = source,
                Target = value as object,
                SourceParameterExpression = expression.Parameters.Single(),
                InstanceExpression = expression.Body
            };

            var actualValue = (TValue)ResolveInstance(processContext);
            if (object.Equals(actualValue, value))
            {
                return source;
            }

            while (processContext.InstanceExpression != processContext.SourceParameterExpression)
            {
                if (TryProcessMemberExpression(processContext)) continue;

                throw new NotSupportedException($"Unable to process expression. Expression: '{processContext.InstanceExpression}'.");
            }

            var target = (TInstance)processContext.Target;

            processContext.AffectedProperties.Reverse();
            OnEmit?.Invoke(source, target, value, processContext.AffectedProperties.ToArray());

            return target;
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveShapes_IdsVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Shape<Point>("point1", new Point());
            var point2 = new Shape<Point>("point2", new Point());
            var shapes = new List<Shape<Point>> { point1, point2 };

            await dataSource.AddAsync(shapes);
            await dataSource.RemoveAsync(point1.Id);

            replacedert.DoesNotContain(point1, dataSource.Shapes);
            replacedert.Contains(point2, dataSource.Shapes);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : HateoasResultProvider.cs
License : Apache License 2.0
Project Creator : alexz76

public bool HasAnyPolicy(IActionResult actionResult, out ObjectResult objectResult)
		{
			if (actionResult is ObjectResult result)
			{
				objectResult = actionResult as ObjectResult;
				string resultType = objectResult.Value.GetType().FullName;

				if (result.Value is IEnumerable<object> collection)
				{
					resultType = collection
						.Select(v => v.GetType().FullName)
						.Distinct()
						.Single();
				}

				return InMemoryPolicyRepository.InMemoryPolicies
					.Any(p => p.Type.FullName.Equals(resultType));
			}

			objectResult = default;
			return false;
		}

19 View Source File : OpenApiSchemaExtensions.cs
License : MIT License
Project Creator : aliencube

[Obsolete("This method is now obsolete", error: true)]
        public static Dictionary<string, OpenApiSchema> ToOpenApiSchemas(this Type type, NamingStrategy namingStrategy, OpenApiSchemaVisibilityAttribute attribute = null, bool returnSingleSchema = false, int depth = 0)
        {
            type.ThrowIfNullOrDefault();

            var schema = (OpenApiSchema)null;
            var schemeName = type.GetOpenApiTypeName(namingStrategy);

            if (depth == 8)
            {
                schema = new OpenApiSchema()
                {
                    Type = type.ToDataType(),
                    Format = type.ToDataFormat()
                };

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            depth++;

            if (type.IsJObjectType())
            {
                schema = typeof(object).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiNullable(out var unwrappedValueType))
            {
                schema = unwrappedValueType.ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;
                schema.Nullable = true;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            schema = new OpenApiSchema()
            {
                Type = type.ToDataType(),
                Format = type.ToDataFormat()
            };

            if (!attribute.IsNullOrDefault())
            {
                var visibility = new OpenApiString(attribute.Visibility.ToDisplayName());

                schema.Extensions.Add("x-ms-visibility", visibility);
            }

            if (type.IsUnflaggedEnumType())
            {
                var converterAttribute = type.GetCustomAttribute<JsonConverterAttribute>();
                if (!converterAttribute.IsNullOrDefault()
                    && typeof(StringEnumConverter).IsreplacedignableFrom(converterAttribute.ConverterType))
                {
                    var enums = type.ToOpenApiStringCollection(namingStrategy);

                    schema.Type = "string";
                    schema.Format = null;
                    schema.Enum = enums;
                    schema.Default = enums.First();
                }
                else
                {
                    var enums = type.ToOpenApiIntegerCollection();

                    schema.Enum = enums;
                    schema.Default = enums.First();
                }
            }

            if (type.IsSimpleType())
            {
                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiDictionary())
            {
                schema.AdditionalProperties = type.GetGenericArguments()[1].ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            if (type.IsOpenApiArray())
            {
                schema.Type = "array";
                schema.Items = (type.GetElementType() ?? type.GetGenericArguments()[0]).ToOpenApiSchemas(namingStrategy, null, true, depth).Single().Value;

                return new Dictionary<string, OpenApiSchema>() { { schemeName, schema } };
            }

            var allProperties = type.IsInterface
                                    ? new[] { type }.Concat(type.GetInterfaces()).SelectMany(i => i.GetProperties())
                                    : type.GetProperties();
            var properties = allProperties.Where(p => !p.ExistsCustomAttribute<JsonIgnoreAttribute>());

            var retVal = new Dictionary<string, OpenApiSchema>();
            foreach (var property in properties)
            {
                var visiblity = property.GetCustomAttribute<OpenApiSchemaVisibilityAttribute>(inherit: false);
                var propertyName = property.GetJsonPropertyName(namingStrategy);

                var ts = property.DeclaringType.GetGenericArguments();
                if (!ts.Any())
                {
                    if (property.PropertyType.IsUnflaggedEnumType() && !returnSingleSchema)
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                        retVal.AddRange(recur1);

                        var enumReference = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema() { Reference = enumReference };
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }
                    else if (property.PropertyType.IsSimpleType() || Nullable.GetUnderlyingType(property.PropertyType) != null || returnSingleSchema)
                    {
                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                    }
                    else if (property.PropertyType.IsOpenApiDictionary())
                    {
                        var elementType = property.PropertyType.GetGenericArguments()[1];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                        }
                        else
                        {
                            var recur1 = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                            retVal.AddRange(recur1);

                            var elementReference = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id = elementType.GetOpenApiReferenceId(false, false)
                            };

                            var dictionarySchema = new OpenApiSchema()
                            {
                                Type = "object",
                                AdditionalProperties = new OpenApiSchema() { Reference = elementReference }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;
                        }
                    }
                    else if (property.PropertyType.IsOpenApiArray())
                    {
                        var elementType = property.PropertyType.GetElementType() ?? property.PropertyType.GetGenericArguments()[0];
                        if (elementType.IsSimpleType() || elementType.IsOpenApiDictionary() || elementType.IsOpenApiArray())
                        {
                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;
                        }
                        else
                        {
                            var elementReference = elementType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                            retVal.AddRange(elementReference);

                            var reference1 = new OpenApiReference()
                            {
                                Type = ReferenceType.Schema,
                                Id = elementType.GetOpenApiReferenceId(false, false)
                            };
                            var arraySchema = new OpenApiSchema()
                            {
                                Type = "array",
                                Items = new OpenApiSchema()
                                {
                                    Reference = reference1
                                }
                            };

                            schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;
                        }

                    }
                    else
                    {
                        var recur1 = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, false, depth);
                        retVal.AddRange(recur1);

                        var reference1 = new OpenApiReference()
                        {
                            Type = ReferenceType.Schema,
                            Id = property.PropertyType.GetOpenApiReferenceId(false, false)
                        };

                        var schema1 = new OpenApiSchema() { Reference = reference1 };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = schema1;
                    }

                    continue;
                }

                var reference = new OpenApiReference()
                {
                    Type = ReferenceType.Schema,
                    Id = property.PropertyType.GetOpenApiRootReferenceId()
                };

                var referenceSchema = new OpenApiSchema() { Reference = reference };

                if (!ts.Contains(property.PropertyType))
                {
                    if (property.PropertyType.IsOpenApiDictionary())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(true, false);
                        var dictionarySchema = new OpenApiSchema()
                        {
                            Type = "object",
                            AdditionalProperties = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = dictionarySchema;

                        continue;
                    }

                    if (property.PropertyType.IsOpenApiArray())
                    {
                        reference.Id = property.PropertyType.GetOpenApiReferenceId(false, true);
                        var arraySchema = new OpenApiSchema()
                        {
                            Type = "array",
                            Items = referenceSchema
                        };

                        schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = arraySchema;

                        continue;
                    }

                    schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = property.PropertyType.ToOpenApiSchemas(namingStrategy, visiblity, true, depth).Single().Value;

                    continue;
                }

                schema.Properties[namingStrategy.GetPropertyName(propertyName, false)] = referenceSchema;
            }

            retVal[schemeName] = schema;

            return retVal;
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private PropertyInfo FindProperty(Type type, ParameterInfo parameter, PropertyInfo[] properties)
        {
            if (ActivationConfiguration.Settings.TryGetValue(type, out var setting))
            {
                if (setting.Parameters.TryGetValue(parameter, out var property))
                {
                    return property;
                }
            }

            properties = properties.Where(x => string.Equals(x.Name, parameter.Name, StringComparison.OrdinalIgnoreCase)).ToArray();

            if (properties.Count() != 1)
            {
                throw new Exception($"Unable to find appropriate property to use as a constructor parameter '{parameter.Name}'. Type '{type.Name}'. Consider to use {nameof(ActivationConfiguration)} parameter.");
            }

            return properties.Single();
        }

19 View Source File : ErrorCodeTests.cs
License : MIT License
Project Creator : aliyun

[Fact]
        public void TestUsingAsHashableKey()
        {
            var errorCodeKeyedDictionary = new Dictionary<ErrorCode, Object>();
            var stringKeyedDictionary = new Dictionary<String, Object>();
            var objectKeyedDictionary = new Dictionary<Object, Object>();

            errorCodeKeyedDictionary[ErrorCode.SdkInternalError] = "from code";
            errorCodeKeyedDictionary["SdkInternalError"] = "from string";

            stringKeyedDictionary[ErrorCode.SdkInternalError] = "from code";
            stringKeyedDictionary["SdkInternalError"] = "from string";

            objectKeyedDictionary[ErrorCode.SdkInternalError] = "from code";
            objectKeyedDictionary["SdkInternalError"] = "from string";

            replacedert.Equal("from string", errorCodeKeyedDictionary.Single().Value);
            replacedert.Equal("from string", stringKeyedDictionary.Single().Value);
            replacedert.Equal("from string", objectKeyedDictionary.Single().Value);
        }

19 View Source File : EmbeddedResourceHttpHandler.cs
License : MIT License
Project Creator : Adoxio

public void ProcessRequest(HttpContext context)
		{
			var paths = GetPaths(context);

			if (paths.Count() == 1)
			{
				Render(context, paths.Single());
			}
			else
			{
				Render(context, paths);
			}
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : AmolLearning

public static void SelecreplacedemByValuefromDrpDwn(this IList<IWebElement> elementList, string ItemValue)

        {
            elementList.Where(x => x.Text == ItemValue).Single().Click();

        }

19 View Source File : CsharpFromJsonExampleFactory.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static void NameFromProperty(TypeDescription root, string rootObjectName)
        {
            if (!string.IsNullOrWhiteSpace(rootObjectName))
            {
                root.replacedignedName = SafeIdentifier(rootObjectName);
            }

            var allTreeNodes = root.AllTypeDescriptions().ToList();

            var allChids =
                allTreeNodes.Where(p => p.Parent != null)
                    .Select(
                        p =>
                            new
                            {
                                SafeParentName = SafeIdentifier(p.ParentName, true),
                                ParentIsArray = p.Parent != null && p.Parent.IsArray,
                                Type = p,
                            })
                    .GroupBy(d => d.SafeParentName)
                    .ToList();

            foreach (var namedCollection in allChids)
            {
                var items = namedCollection.ToList();
                if (items.Count == 1)
                {
                    namedCollection.Single().Type.replacedignedName = namedCollection.Key;
                }
                else
                {
                    var index = 0;
                    foreach (var item in items)
                    {
                        item.Type.replacedignedName = $"{namedCollection.Key}{index++ :000}";
                    }
                }
            }
        }

19 View Source File : DbContextOptionsSpecimenBuilder.cs
License : MIT License
Project Creator : aivascu

public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!this.OptionsSpecification.IsSatisfiedBy(request))
            {
                return new NoSpecimen();
            }

            if (!(request is Type type))
            {
                return new NoSpecimen();
            }

            var contextType = type.GetGenericArguments().Single();

            var optionsBuilderObj = context.Resolve(typeof(IOptionsBuilder));

            if (optionsBuilderObj is NoSpecimen
                || optionsBuilderObj is OmitSpecimen
                || optionsBuilderObj is null)
            {
                return optionsBuilderObj;
            }

            if (!(optionsBuilderObj is IOptionsBuilder optionsBuilder))
            {
                return new NoSpecimen();
            }

            return optionsBuilder.Build(contextType);
        }

19 View Source File : TodoItemTest.cs
License : MIT License
Project Creator : amoraitis

[Fact]
        public void TodoItem_UserIdIsRequired()
        {
            var validationResults = new List<ValidationResult>();
            var todoItemId = Guid.NewGuid();
            var todoItem = new TodoItem()
            {
                Id = todoItemId,
                replacedle = "Cleaning",
                Content = "Clean the kitchen.",
                Added = new Instant(),
                DueTo = new Instant(),
#pragma warning disable CS0618 // 'TodoItem.AddedDateTime' is obsolete: 'Property only used for EF-serialization purposes'
                AddedDateTime = DateTime.Now,
#pragma warning restore CS0618 // 'TodoItem.AddedDateTime' is obsolete: 'Property only used for EF-serialization purposes'
#pragma warning disable CS0618 // 'TodoItem.DuetoDateTime' is obsolete: 'Property only used for EF-serialization purposes'
                DuetoDateTime = DateTime.Now,
#pragma warning restore CS0618 // 'TodoItem.DuetoDateTime' is obsolete: 'Property only used for EF-serialization purposes'
                Done = false,
                Tags = new[] { "test" },
                UserId = null, // Required
                File = new FileInfo()
                {
                    Path = "C:/temp",
                    Size = 100,
                    TodoId = todoItemId
                }
            };

            var isValid = Validator.TryValidateObject(todoItem, new ValidationContext(todoItem), validationResults);

            replacedert.False(isValid);
            replacedert.NotEmpty(validationResults);
            replacedert.Single(validationResults);
            replacedert.Equal($"The {nameof(TodoItem.UserId)} field is required.", validationResults.Single().ErrorMessage);
        }

19 View Source File : SuppressionFileIOTests.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

[Fact]
		public void CheckSuppressionMessageConversion_ToXml()
		{
			var expectedXElement = GetXElementsToCheck().Take(1).Single();
			var message = new SuppressMessage(id: "PX1001",
											  target: @"PX.Objects.CS.Email.ExchangeBaseLogicSyncCommand<GraphType, TPrimary, ExchangeType>.Uploader",
											  syntaxNode: @"new UploadFileMaintenance()");

			var xElement = message.ToXml();

			xElement.Should().NotBeNull();
			xElement.Should().Be(expectedXElement);	
		}

19 View Source File : MediatorNotificationCollector.cs
License : Apache License 2.0
Project Creator : Anapher

public void replacedertSingleNotificationIssued<T>(Action<T>? replacedertNotificationFunc = null) where T : INotification
        {
            var notification = _notifications.OfType<T>().Single();
            _notifications.Remove(notification);

            replacedertNotificationFunc?.Invoke(notification);
        }

19 View Source File : BasicAuthFilter.cs
License : MIT License
Project Creator : alanedwardes

private (string Username, string Preplacedword) GetCredentials(IHeaderDictionary headers)
        {
            if (!headers.ContainsKey(AuthorizationHeader))
            {
                throw new InvalidOperationException("No Authorization header found.");
            }

            string[] authValues = headers[AuthorizationHeader].ToArray();
            if (authValues.Length != 1)
            {
                throw new InvalidOperationException("More than one Authorization header found.");
            }

            string auth = authValues.Single();
            if (!auth.StartsWith(BasicPrefix))
            {
                throw new InvalidOperationException("Authorization header is not Basic.");
            }

            auth = auth.Substring(BasicPrefix.Length).Trim();

            byte[] decoded = Convert.FromBase64String(auth);
            Encoding iso = Encoding.GetEncoding("ISO-8859-1");

            string[] authPair = iso.GetString(decoded).Split(':');

            return (authPair[0], authPair[1]);
        }

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : ap0llo

public static MdSpan Join(this IEnumerable<MdSpan> spans, MdSpan? separator)
        {
            // no spans to join => return empty span
            if (!spans.Any())
            {
                return MdEmptySpan.Instance;
            }
            // a single span to join => just return the single span
            else if (!spans.Skip(1).Any())
            {
                return spans.Single();
            }
            // multiple span but no separator => create composite span with all the specified spans
            else if (separator == null)
            {
                return new MdCompositeSpan(spans);
            }
            // multiple spans and separator specified
            // => create composite span and add separator between individual spans
            else
            {
                var composite = new MdCompositeSpan();

                foreach (var span in spans)
                {
                    if (composite.Spans.Count > 0)
                    {
                        composite.Add(separator.DeepCopy());
                    }
                    composite.Add(span);
                }

                return composite;
            }
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static T ToEnum<T>(this string str)
        {
            var enumType = typeof(T);
            foreach (var name in Enum.GetNames(enumType))
            {
                var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
                if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name);
            }
            //throw exception or whatever handling you want or
            return default(T);
        }

19 View Source File : FullScreenControl.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_AddEvents_Async()
        {
            var control = new FullScreenControl(eventFlags: FullScreenEventActivationFlags.All()) {
                JsRuntime = _jsRuntimeMock.Object,
                Logger = _loggerMock.Object
            };

            await control.AddEventsAsync();

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.FullScreenControl.AddEvents.ToFullScreenControlNamespace(), It.Is<object[]>(parameters =>
               (parameters[0] as Guid?).GetValueOrDefault() == control.Id
               && parameters[1] is IEnumerable<string>
               && (parameters[1] as IEnumerable<string>).Single() == FullScreenEventType.FullScreenChanged.ToString()
               && parameters[2] is DotNetObjectReference<FullScreenEventInvokeHelper>
            )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrCollectionAnyEqual<TEnreplacedy, TValue, TMemberValue>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, IEnumerable<TValue>>> selector,
            Expression<Func<TValue, TMemberValue>> memberSelector,
            IEnumerable<TMemberValue> values
            )
        {
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression selectorParameter = selector.Parameters.Single();
            ParameterExpression memberParameter = memberSelector.Parameters.Single();
            var methodInfo = GetEnumerableMethod("Any", 2).MakeGenericMethod(typeof(TValue));
            var anyExpressions = values.Select(value =>
                    (Expression)Expression.Call(null,
                                                methodInfo,
                                                selector.Body,
                                                Expression.Lambda<Func<TValue, bool>>(Expression.Equal(memberSelector.Body,
                                                                                                       Expression.Constant(value, typeof(TMemberValue))),
                                                                                                       memberParameter
                                                                                                       )
                                                )
                );
            Expression body = anyExpressions.Aggregate((acreplacedulate, any) => Expression.Or(acreplacedulate, any));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, selectorParameter));
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_NotRemoveShapesButOnlyFeatures_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var shape = new Shape<Point>("point1", new Point());
            var feature = new Feature<Point>("point2", new Point());

            IEnumerable<Shape> shapes = null;
            Feature[] features = new[] { feature };

            await dataSource.AddAsync(shape);
            await dataSource.AddAsync(feature);
            await dataSource.RemoveAsync(shapes, features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddShapes.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == feature.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : adamfisher

public static Stream GetEmbeddedResourceStream(this replacedembly replacedembly, string resourceFileName)
        {
            var resourceNames = replacedembly.GetManifestResourceNames();

            var resourcePaths = resourceNames
                .Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
                .ToArray();

            if (!resourcePaths.Any())
            {
                throw new Exception($"Resource ending with {resourceFileName} not found.");
            }

            if (resourcePaths.Count() > 1)
            {
                throw new Exception($"Multiple resources ending with {resourceFileName} found: {Environment.NewLine}{string.Join(Environment.NewLine, resourcePaths)}");
            }

            return replacedembly.GetManifestResourceStream(resourcePaths.Single());
        }

19 View Source File : GeolocationControl.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_AddEvents_Async()
        {
            var control = new GeolocationControl(eventFlags: GeolocationEventActivationFlags.None().Enable(GeolocationEventType.GeolocationError)) {
                JsRuntime = _mapJsRuntimeMock.Object
            };

            await control.AddEventsAsync();

            _mapJsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.GeolocationControl.AddEvents.ToGeolocationControlNamespace(), It.Is<object[]>(parameters =>
               (parameters[0] as Guid?).GetValueOrDefault() == control.Id
               && parameters[1] is IEnumerable<string>
               && (parameters[1] as IEnumerable<string>).Single() == GeolocationEventType.GeolocationError.ToString()
               && parameters[2] is DotNetObjectReference<GeolocationEventInvokeHelper>
            )), Times.Once);
            _mapJsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : QueryableExtensions.cs
License : MIT License
Project Creator : albyho

public static IQueryable<TEnreplacedy> WhereOrStringContains<TEnreplacedy, String>
            (
            this IQueryable<TEnreplacedy> query,
            Expression<Func<TEnreplacedy, String>> selector,
            IEnumerable<String> values
            )
        {
            /*
             * 实现效果:
             * var tags = new[] { "A", "B", "C" };
             * SELECT * FROM [User] Where Name='Test' AND (Tags LIKE '%A%' Or Tags LIKE  '%B%')
             */

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!values.Any()) return query;

            ParameterExpression p = selector.Parameters.Single();
            var containsExpressions = values.Select(value => (Expression)Expression.Call(selector.Body, typeof(String).GetMethod("Contains", new[] { typeof(String) }), Expression.Constant(value)));
            Expression body = containsExpressions.Aggregate((acreplacedulate, containsExpression) => Expression.Or(acreplacedulate, containsExpression));

            return query.Where(Expression.Lambda<Func<TEnreplacedy, bool>>(body, p));
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveFeatures_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Feature<Point>("point1", new Point());
            var point2 = new Feature<Point>("point2", new Point());
            var features = new List<Feature<Point>> { point1, point2 };

            await dataSource.AddAsync(features);
            await dataSource.RemoveAsync(point1);

            replacedert.DoesNotContain(point1, dataSource.Features);
            replacedert.Contains(point2, dataSource.Features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private IEnumerable GenerateListOf(Type type, int recursionLevel)
        {
            var typeGenericTypeArguments = type.GenericTypeArguments;

            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(typeGenericTypeArguments);

            // Instantiates a collection of ...
            var list = Activator.CreateInstance(constructedListType) as IList;

            // Add 5 elements of this type
            for (var i = 0; i < MaxCountToFuzzInLists; i++)
            {
                list.Add(GenerateInstanceOf(typeGenericTypeArguments.Single(), recursionLevel));
            }

            return list;
        }

19 View Source File : GriddedDataSource.cs
License : MIT License
Project Creator : arnaudleclerc

[Fact]
        public async void Should_RemoveFeatures_EnumerableVersion_Async()
        {
            var dataSource = new GriddedDataSource() { JSRuntime = _jsRuntimeMock.Object };
            var point1 = new Feature<Point>("point1", new Point());
            var point2 = new Feature<Point>("point2", new Point());
            var features = new List<Feature<Point>> { point1, point2 };

            await dataSource.AddAsync(features);
            await dataSource.RemoveAsync(point1);

            replacedert.DoesNotContain(point1, dataSource.Features);
            replacedert.Contains(point2, dataSource.Features);

            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.AddFeatures.ToSourceNamespace(), It.IsAny<object[]>()), Times.Once);
            _jsRuntimeMock.Verify(runtime => runtime.InvokeVoidAsync(Constants.JsConstants.Methods.Source.Remove.ToSourceNamespace(), It.Is<object[]>(
                parameters => parameters[0] as string == dataSource.Id
                && (parameters[1] as IEnumerable<string>).Single() == point1.Id
                )), Times.Once);
            _jsRuntimeMock.VerifyNoOtherCalls();
        }

19 View Source File : HateoasResultProvider.cs
License : Apache License 2.0
Project Creator : alexz76

private IEnumerable<InMemoryPolicyRepository.Policy> GetFilteredPolicies(ObjectResult result)
		{
			string resultType = result.Value.GetType().FullName;

			if (result.Value is IEnumerable<object> collection)
			{
				resultType = collection
					.Select(v => v.GetType().FullName)
					.Distinct()
					.Single();
			}

			return InMemoryPolicyRepository.InMemoryPolicies
				.Where(p => p.Type.FullName.Equals(resultType))
				.AsEnumerable();
		}

19 View Source File : CrmProfileProvider.cs
License : MIT License
Project Creator : Adoxio

private Expression<Func<Enreplacedy, bool>> CreateOrModifyWherePredicate(Expression<Func<Enreplacedy, bool>> wherePredicate, ProfileAuthenticationOption authenticationOption)
		{
			var isAnonymous = authenticationOption == ProfileAuthenticationOption.Anonymous;

			if (wherePredicate == null)
			{
				return enreplacedy => enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous;
			}
			
			// Set the wherePredicate so that the clause is equivilant to:
			// enreplacedy => wherePreicate.Body && enreplacedy.GetAttributeValue<bool?>(_attributeMapIsAnonymous).GetValueOrDefault() == isAnonymous

			var enreplacedyParameter = wherePredicate.Parameters.Single();

			Expression getPropertyValue = Expression.Call(enreplacedyParameter, "GetPropertyValue", new[] { typeof(bool?) }, Expression.Constant(_attributeMapIsAnonymous));

			var left = Expression.Call(getPropertyValue, typeof(bool?).GetMethod("GetValueOrDefault", Type.EmptyTypes));

			var anonymousPredicateBody = Expression.Equal(left, Expression.Constant(isAnonymous));

			return Expression.Lambda<Func<Enreplacedy, bool>>(Expression.AndAlso(wherePredicate.Body, anonymousPredicateBody), enreplacedyParameter);
		}

19 View Source File : CheckCreateFile.cs
License : MIT License
Project Creator : 3RD-Dimension

public static void CheckAndUpdateXMLFile(int CurrentKeyFileVersion)
        {
            MainWindow.Logger.Info($"Updating HotkeyXML File. Current File Version {CurrentKeyFileVersion}, Update to File Version {HotKeyFileVer}");
            // Define new Hotkey fields - This changes every program update if needed   
            var UpdateHotkey = XDoreplacedent.Load(HotKeyFile);

            // NOTES | Sample Code for Add, Add at position, Rename:
            // Add to end of file: xDoc.Root.Add(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Add to specific Location: xDoc.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Rename Hotkey Data
            //var hotKeyRename1 = xDoc.Descendants("bind").Where(arg => arg.Attribute("key_description").Value == "Feed Rate Increase").Single();
            //hotKeyRename1.Attribute("key_description").Value = "Feed Rate Increase X";

            // START FILE MANIPULATION
            // Insert at specific Location - Reverse Order - Bottom will be inserted at the top
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Z"), new XAttribute("keyfunction", "JDistDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Z"), new XAttribute("keyfunction", "JDistIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Y"), new XAttribute("keyfunction", "JDistDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Y"), new XAttribute("keyfunction", "JDistIncY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease X"), new XAttribute("keyfunction", "JDistDecX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase X"), new XAttribute("keyfunction", "JDistIncX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Z"), new XAttribute("keyfunction", "JRateDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Z"), new XAttribute("keyfunction", "JRateIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Y"), new XAttribute("keyfunction", "JRateDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Y"), new XAttribute("keyfunction", "JRateIncY"), new XAttribute("keycode", "")));

            // Change Hotkey Desciptions and Keyfunction Name
            var hotKeyRename1 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateInc").Single();
            var hotKeyRename2 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateDec").Single();
            hotKeyRename1.Attribute("key_description").Value = "Jog Rate Increase X";
            hotKeyRename1.Attribute("keyfunction").Value = "JRateIncX";
            hotKeyRename2.Attribute("key_description").Value = "Jog Rate Decrease X";
            hotKeyRename2.Attribute("keyfunction").Value = "JRateDecX";

            // END FILE MANIPULATION
            UpdateHotkey.Root.Attribute("HotkeyFileVer").Value = HotKeyFileVer.ToString(); // Change HotkeyFileVer to current version

            //And save the XML file
            UpdateHotkey.Save(HotKeyFile);

            // Re-load Hotkeys
            HotKeys.LoadHotKeys();
        }

19 View Source File : JsonExtension.cs
License : MIT License
Project Creator : 4egod

public static string ToEnumString<T>(this T type)
        {
            var enumType = typeof (T);
            var name = Enum.GetName(enumType, type);
            var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single();
            return enumMemberAttribute.Value;
        }

19 View Source File : ExpressionParser.cs
License : MIT License
Project Creator : actions

private static IExpressionNode CreateTree(ParseContext context)
        {
            // Push the tokens
            while (context.Lexicalreplacedyzer.TryGetNextToken(ref context.Token))
            {
                // Unexpected
                if (context.Token.Kind == TokenKind.Unexpected)
                {
                    throw new ParseException(ParseExceptionKind.UnexpectedSymbol, context.Token, context.Expression);
                }
                // Operator
                else if (context.Token.IsOperator)
                {
                    PushOperator(context);
                }
                // Operand
                else
                {
                    PushOperand(context);
                }

                context.LastToken = context.Token;
            }

            // No tokens
            if (context.LastToken == null)
            {
                return null;
            }

            // Check unexpected end of expression
            if (context.Operators.Count > 0)
            {
                var unexpectedLastToken = false;
                switch (context.LastToken.Kind)
                {
                    case TokenKind.EndGroup:        // ")" logical grouping
                    case TokenKind.EndIndex:        // "]"
                    case TokenKind.EndParameters:   // ")" function call
                        // Legal
                        break;
                    case TokenKind.Function:
                        // Illegal
                        unexpectedLastToken = true;
                        break;
                    default:
                        unexpectedLastToken = context.LastToken.IsOperator;
                        break;
                }

                if (unexpectedLastToken || context.Lexicalreplacedyzer.UnclosedTokens.Any())
                {
                    throw new ParseException(ParseExceptionKind.UnexpectedEndOfExpression, context.LastToken, context.Expression);
                }
            }

            // Flush operators
            while (context.Operators.Count > 0)
            {
                FlushTopOperator(context);
            }

            // Check max depth
            var result = context.Operands.Single();
            CheckMaxDepth(context, result);

            return result;
        }

19 View Source File : RegistrationContext.cs
License : Apache License 2.0
Project Creator : agoda-com

private string ValidateAndDisambiguateBaseType()
        {
            if (FromType != null)
            {
                return null;
            }
            
            if (IsConcrete || _baseTypes.Count == 0)
            {
                IsConcrete = true;
                FromType = ToType;
                return null;    
            }

            // if there's only one base type then use it
            if (_baseTypes.Count == 1)
            {
                FromType = _baseTypes.Single();
                return null;
            }

            // if there are multiple base types, and only one is an interface, then use it
            var interfaces = _baseTypes.Where(t => t.IsInterface).ToList();
            if (interfaces.Count == 1)
            {
                FromType = interfaces.Single();
                return null;
            }

            // registration is ambiguous: multiple interfaces and/or base clreplacedes are implemented
            var attrName = ContainerAttributeUtils.GetFriendlyName(Attribute);
            return
                $"{_originalToType.FullName}: Registration is ambiguous as the implementation has multiple base types, and a " +
                $"single interface could not be determined. Please add one of the following to your registration attribute:\n" +
                string.Join("", _baseTypes.Select(t => $"\n - {nameof(ContainerRegistrationAttribute.For)} = typeof({t.Name})")) +
                $"\n\nOr, to register many base types to resolve to the same implementation, decorate the clreplaced with " +
                $"multiple registration attributes, eg:\n\n" +
                string.Join("", _baseTypes.Select(t => $"[{attrName}({nameof(ContainerRegistrationAttribute.For)} = typeof({t.Name}))]\n")) +
                $"public clreplaced {ToType.Name} ...";
        }

19 View Source File : ReleaseService.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public async Task UpdateAsync(ReleaseEnreplacedy release, string appOwner)
        {
            IEnumerable<ReleaseEnreplacedy> releaseDoreplacedents = await _releaseRepository.Get(appOwner, release.Build.Id);
            ReleaseEnreplacedy releaseEnreplacedy = releaseDoreplacedents.Single();

            releaseEnreplacedy.Build.Status = release.Build.Status;
            releaseEnreplacedy.Build.Result = release.Build.Result;
            releaseEnreplacedy.Build.Started = release.Build.Started;
            releaseEnreplacedy.Build.Finished = release.Build.Finished;

            await _releaseRepository.Update(releaseEnreplacedy);
        }

See More Examples