/// <summary> /// Add a decorator to the enumerable for additional processing /// </summary> /// <param name="operation">The operation.</param> /// <param name="enumerator">The enumerator.</param> protected override IEnumerable<Row> DecorateEnumerableForExecution(IOperation operation, IEnumerable<Row> enumerator) { foreach (Row row in new EventRaisingEnumerator(operation, enumerator)) { yield return row; } }
private void ResolveTouchClick(IPuzzle puzzle, IOperation op) { IQuad quad = puzzle[op.row, op.column]; if (quad.value == QuadValue.Front || quad.value == QuadValue.Back) { List<Tween> playings = DOTween.PlayingTweens(); if (playings != null) { playings.ForEach((Tween each) => { if (each.id != null && each.id.ToString().StartsWith(Style.QuadUnifiedRotateId)) { each.Kill(true); } }); } puzzle.touchEnable = false; TweenDepot depot = new TweenDepot(); ResolvePresent(depot, puzzle, op, op, 0); Sequence sequence = depot.ToSequence(); sequence.SetId(Style.QuadUnifiedRotateId); sequence.OnComplete(() => { ResolveTouchData(puzzle, op); if (IsSolved(puzzle)) { puzzle.solved = true; } else { puzzle.touchEnable = true; } }); } }
public override bool BeforeExecute(IOperation operation) { if ((InRoles == null || InRoles.Length == 0) && (Users == null || Users.Length == 0)) return true; try { if (InRoles != null) if (InRoles.Any(role => _context.User.IsInRole(role))) { return true; } if (Users != null) if (Users.Any(user => _context.User.Identity.Name == user)) { return true; } } catch { // todo: decide where to log this error. } _context.OperationResult = new OperationResult.Unauthorized(); return false; }
public IList<OperationBehavior> CreateBehaviors(IOperation operation, WorkflowConfiguration configuration) { Verify.NotNull(operation, nameof(operation)); var decoratorAttributes = operation.GetType().GetCustomAttributes(typeof(OperationBehaviorAttribute), inherit: false); return decoratorAttributes.OfType<OperationBehaviorAttribute>().Select(b => b.CreateBehavior(configuration)).ToList(); }
public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": // result = Add(operands[0], operands[1]); //foreach (var addMethod in AddMethods) //{ // if (addMethod.Metadata.ContainsKey("speed") && (string)addMethod.Metadata["speed"] == "fast") // result = addMethod.Value(operands[0], operands[1]); //} foreach (var addMethod in AddMethods) { if (addMethod.Metadata.Speed == Speed.Fast) result = addMethod.Value(operands[0], operands[1]); } // result = operands[0] + operands[1]; break; case "-": result = Subtract(operands[0], operands[1]); // result = operands[0] - operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; default: throw new InvalidOperationException( String.Format("invalid operation {0}", operation.Name)); } return result; }
public override IEnumerable<IOperationInterceptor> GetInterceptors(IOperation operation) { return new[] { new PrincipalAuthorizationInterceptor(DependencyManager.GetService<ICommunicationContext>()) }; }
public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": result = operands[0] + operands[1]; break; case "-": result = operands[0] - operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; case "%": result = operands[0] % operands[1]; break; case "++": result = ++operands[0]; break; case "--": result = --operands[0]; break; default: throw new InvalidOperationException($"invalid operation {operation.Name}"); } return result; }
private AresExecutor(IOperation operation) { var props = new PropertiesCommandDefault(new OperationPropertiesSetter()); this.cb = CircuitBreakerFactory.Get(operation.Name, props); this.metrics = AresMetricsFactory.Get(operation.Name, props); this.operation = operation; }
public void Prepare(IOperation initialOperation) { base.Prepare(); executionStack.Clear(); if (initialOperation != null) executionStack.Push(initialOperation); OnPrepared(); }
protected override void EmitOperation(IOperation operation) { switch (operation.OperationCode) { case OperationCode.Ret: base.EmitOperation(new Operation() { OperationCode = OperationCode.Ldarg_0 }); base.EmitOperation(new Operation() { OperationCode = OperationCode.Ldstr, Value = PropertyName, }); var method = TypeHelper2.GetMethodRecursive( Type, host.NameTable.GetNameFor("InvokePropertyChanged"), host.PlatformType.SystemString); if (method == Dummy.Method || method == null) { throw new InvalidOperationException(); } base.EmitOperation(new Operation() { OperationCode = OperationCode.Call, Value = method, }); break; } base.EmitOperation(operation); }
public override bool BeforeExecute(IOperation operation) { foreach (InputMember input in operation.Inputs) { if (input == null) continue; var parameter = input.Binder.BuildObject(); try { IValidator validator = ResolveValidator(parameter); if (validator == null) continue; var errors = validator.Validate(parameter.Instance, operation.Name.ToUpper()).ToList(); if (errors.Count > 0) { _context.OperationResult = new OperationResult.BadRequest { ResponseResource = parameter.Instance, Errors = errors }; return false; } } catch (Exception ex) {} } return true; }
public DeploymentCreateForecastWorker( IDeployment deployment, IOperation operation, Guid subscriptionId, string certificateThumbprint, string serviceName, string deploymentSlot, ScheduleDay[] scheduleDays, string deploymentName, Uri packageUrl, string label, string configurationFilePath, bool startDeployment, bool treatWarningsAsError, int pollingIntervalInMinutes) : base(GetWorkerId(serviceName, deploymentSlot)) { this.deployment = deployment; this.operation = operation; this.subscriptionId = subscriptionId; this.certificateThumbprint = certificateThumbprint; this.serviceName = serviceName; this.deploymentSlot = deploymentSlot; this.scheduleDays = scheduleDays; this.deploymentName = deploymentName; this.packageUrl = packageUrl; this.label = label; this.configurationFilePath = configurationFilePath; this.startDeployment = startDeployment; this.treatWarningsAsError = treatWarningsAsError; this.pollingIntervalInMinutes = pollingIntervalInMinutes; }
public void OperationFailed(IOperation operation, Exception error) { if(!OperationFailures.ContainsKey(operation)) OperationFailures.Add(operation, new List<Exception>()); OperationFailures[operation].Add(error); }
public void HandleOperation(IOperation operation) { var handlerType = typeof (IOperationHandler<>).MakeGenericType(operation.GetType()); var handler = _handlerFactory(handlerType); handlerType.GetMethod("Handle").Invoke(handler, new object[] {operation}); }
public override IEnumerable<IOperationInterceptor> GetInterceptors(IOperation operation) { yield return DependencyManager.GetService<RequiresAuthenticationInterceptor>(); var roleInterceptor = DependencyManager.GetService<RequiresRoleInterceptor>(); roleInterceptor.Role = _roleName; yield return roleInterceptor; }
/// <summary> /// Add a decorator to the enumerable for additional processing /// </summary> /// <param name="operation">The operation.</param> /// <param name="enumerator">The enumerator.</param> protected override IEnumerable<Row> DecorateEnumerableForExecution(IOperation operation, IEnumerable<Row> enumerator) { ThreadSafeEnumerator<Row> threadedEnumerator = new ThreadSafeEnumerator<Row>(); ThreadPool.QueueUserWorkItem(delegate { try { foreach (Row t in new EventRaisingEnumerator(operation, enumerator)) { threadedEnumerator.AddItem(t); } } catch (Exception e) { Error(e, "Failed to execute operation {0}", operation); threadedEnumerator.MarkAsFinished(); throw; } finally { threadedEnumerator.MarkAsFinished(); } }); return threadedEnumerator; }
public FaceSearchController( IFrameStream source, IOperation<Frame> frameProcessor, IConvertor<Frame, Portrait> convertor, IOperation<Portrait> portraitProcessor) { _source = source; _frameProcessor = frameProcessor; _convertor = convertor; _portraitProcessor = portraitProcessor; _worker.DoWork = delegate { var frames = frameProcessor.Execute(null).ToList(); var portraits = _convertor.Execute(frames).ToList(); var portraitsAfterProcess = _portraitProcessor.Execute(portraits).ToList(); foreach (var portrait in portraitsAfterProcess) { portrait.Dispose(); } }; _worker.OnExceptionRetry = () => _source.Connect(); }
public void clearOpInfo(IOperation op) { cur_checksum.Text = ""; app_path.Text = ""; appName.Text = ""; appIcon.Image = null; }
protected virtual OperationStatus DoOperation(IOperation operation) { Logger.LogEvent(string.Format("Doing operation of type {0} syncronously.", operation.GetType().Name), this, ImportanceLevels.gUnimportant); var status = operation.RunSync(); Logger.LogEvent(string.Format("Operation of type {0} is done.", operation.GetType().Name), this, ImportanceLevels.gUnimportant); return status; }
protected OperationStartInformation DoOperationAsync(IOperation operation) { Logger.LogEvent(string.Format("Doing operation of type {0} asyncronously.", operation.GetType().Name), this, ImportanceLevels.gUnimportant); var operationAttribute = (OperationAttribute)operation.GetType().GetCustomAttributes(typeof(OperationAttribute), true).SingleOrDefault(); var operationStart = operation.RunAsync(); var operationStartInformation = new OperationStartInformation { OperationId = operationStart.OperationId }; if (operationAttribute != null) { operationStartInformation.IsReportingProgress = operationAttribute.IsReportingProgress; operationStartInformation.IsSupportingCancel = operationAttribute.IsSupportingCancel; operationStartInformation.ExpectedCompletionTimeMilliseconds = operationAttribute.ExpectedCompletionTimeMilliseconds; operationStartInformation.SuggestedPollingIntervalMilliseconds = operationAttribute.SuggestedPollingIntervalMilliseconds; } Logger.LogEvent( string.Format( "Operation of type {0} has started. OperationStartInformation: {1}.", operation.GetType().Name, new { operationStartInformation.OperationId, operationStartInformation.IsReportingProgress, operationStartInformation.IsSupportingCancel, operationStartInformation.ExpectedCompletionTimeMilliseconds, operationStartInformation.SuggestedPollingIntervalMilliseconds }), this, ImportanceLevels.gUnimportant); return operationStartInformation; }
public override IEnumerable<IOperationInterceptor> GetInterceptors(IOperation operation) { return new[] { new RequiresAuthenticationInterceptor(DependencyManager.GetService<ICommunicationContext>()) }; }
public ScheduledHorizontalScaleForecastWorker( IDeployment deployment, IOperation operation, Guid subscriptionId, string certificateThumbprint, string serviceName, string deploymentSlot, HorizontalScale[] horizontalScales, ScheduleDay[] scheduleDays, bool treatWarningsAsError, string mode, int pollingIntervalInMinutes) : base(GetWorkerId(serviceName, deploymentSlot)) { this.deployment = deployment; this.operation = operation; this.subscriptionId = subscriptionId; this.certificateThumbprint = certificateThumbprint; this.serviceName = serviceName; this.deploymentSlot = deploymentSlot; this.horizontalScales = horizontalScales; this.scheduleDays = scheduleDays; this.treatWarningsAsError = treatWarningsAsError; this.mode = mode; this.pollingIntervalInMinutes = pollingIntervalInMinutes; }
protected CompositeOperationBase(IOperationResultBuilder operationResultBuilder, IOperation leftOperation, IOperation rightOperation) : base(operationResultBuilder) { this.leftOperation = leftOperation; this.rightOperation = rightOperation; }
public IList<OperationBehavior> CreateBehaviors(IOperation operation, WorkflowConfiguration configuration) { if (!(operation is IConditionalOperation)) return new OperationBehavior[0]; return new OperationBehavior[] { new ConditionalExecutionBehavior() }; }
public static void OperationFound(this ILogger<CodecLogSource> logger, IOperation operation) { if (operation.GetRequestCodec() != null) logger.WriteInfo("Operation {0} was selected with a codec score of {1}", operation, operation.GetRequestCodec().Score); else logger.WriteInfo("Operation {0} was selected without a codec.", operation); }
protected void WaitForResultOfRequest(ILog logger, string workerTypeName, IOperation operation, Guid subscriptionId, string certificateThumbprint, string requestId) { OperationResult operationResult = new OperationResult(); operationResult.Status = OperationStatus.InProgress; bool done = false; while (!done) { operationResult = operation.StatusCheck(subscriptionId, certificateThumbprint, requestId); if (operationResult.Status == OperationStatus.InProgress) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}', the operation was found to be in process, waiting for '{3}' seconds.", workerTypeName, this.Id, requestId, FiveSecondsInMilliseconds / 1000); logger.Info(logMessage); Thread.Sleep(FiveSecondsInMilliseconds); } else { done = true; } } if (operationResult.Status == OperationStatus.Failed) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it failed. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message); logger.Error(logMessage); } else if (operationResult.Status == OperationStatus.Succeeded) { string logMessage = string.Format(CultureInfo.CurrentCulture, "{0} '{1}' submitted a deployment request with ID '{2}' and it succeeded. The code was '{3}' and message '{4}'.", workerTypeName, this.Id, requestId, operationResult.Code, operationResult.Message); logger.Info(logMessage); } }
public IEnumerable<IOperationInterceptor> GetInterceptors(IOperation operation) { return this.systemInterceptors .Concat(GetInterceptorAttributes(operation)) .Concat(GetInterceptorProviderAttributes(operation)) .ToList(); }
public void CanPassOnRemovedProcessedEvents() { //Arrange var branching = new TestAbstractBranchingOperation(); const int nOps = 5; var ops = new IOperation[nOps]; for (var i = 0; i < nOps; i++) { ops[i] = MockRepository.GenerateMock<IOperation>(); ops[i].Expect(x => x.OnRowProcessed += processAction); ops[i].Expect(x => x.OnRowProcessed -= processAction); branching.Add(ops[i]); } //Act branching.OnRowProcessed += processAction; branching.OnRowProcessed -= processAction; //Assert foreach (var op in ops) op.VerifyAllExpectations(); var handlerInfos = typeof(AbstractOperation).GetField("OnRowProcessed", BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic); Assert.Equal(1, ((Delegate)(handlerInfos.GetValue(branching))).GetInvocationList().Length); }
public void OnOperationComplete(IOperation next) { if (OperationComplete != null) { OperationComplete(next); } }
public void SetUp() { _communicationContext = MockRepository.GenerateStub<ICommunicationContext>(); _communicationContext.Stub(x => x.Request).Return(MockRepository.GenerateStub<IRequest>()); _authenticationScheme = MockRepository.GenerateStub<IAuthenticationScheme>(); _operation = MockRepository.GenerateStub<IOperation>(); }
private bool IsDisposableCreation(IOperation operation) => (s_DisposableCreationKinds.Contains(operation.Kind) ||
/// <summary> /// Der Konstruktor, dem zwei Operatoren übergeben werden. /// </summary> /// <param name="op1">Der erste Operator.</param> /// <param name="op2">Der zweite Operator</param> public LessThanOrEqual(IOperation op1, IOperation op2) { _operatorList = new IOperation[2]; _operatorList[0] = op1; _operatorList[1] = op2; }
private IConditionalAccessInstanceOperationWrapper(IOperation operation) { this.operation = operation; }
private static IOperation RemoveImplicitConversion(IOperation operation) { return(operation is IConversionOperation conversion && conversion.IsImplicit ? RemoveImplicitConversion(conversion.Operand) : operation); }
internal DisposeAbstractValue WithNewDisposingOperation(IOperation disposingOperation) { Debug.Assert(Kind != DisposeAbstractValueKind.NotDisposable); return(new DisposeAbstractValue(DisposingOrEscapingOperations.Add(disposingOperation), DisposeAbstractValueKind.Disposed)); }
/// <summary> /// This method is the workhorse that does the rewrite of the IOperation op. /// </summary> /// <param name="op">The MSIL operation to rewrite.</param> protected void RewriteOpertation(IOperation op) { Contract.Requires(this.generator != null); Contract.Requires(op != null); if (op.Value == null) { generator.Emit(op.OperationCode); return; } var typeCode = System.Convert.GetTypeCode(op.Value); switch (typeCode) { case TypeCode.Byte: this.generator.Emit(op.OperationCode, (byte)op.Value); break; case TypeCode.Double: this.generator.Emit(op.OperationCode, (double)op.Value); break; case TypeCode.Int16: this.generator.Emit(op.OperationCode, (short)op.Value); break; case TypeCode.Int32: this.generator.Emit(op.OperationCode, (int)op.Value); break; case TypeCode.Int64: this.generator.Emit(op.OperationCode, (long)op.Value); break; case TypeCode.Object: IFieldReference fieldReference = op.Value as IFieldReference; if (fieldReference != null) { this.generator.Emit(op.OperationCode, fieldReference); break; } ILocalDefinition localDefinition = op.Value as ILocalDefinition; if (localDefinition != null) { this.generator.Emit(op.OperationCode, localDefinition); break; } IMethodReference methodReference = op.Value as IMethodReference; if (methodReference != null) { this.generator.Emit(op.OperationCode, methodReference); break; } IParameterDefinition parameterDefinition = op.Value as IParameterDefinition; if (parameterDefinition != null) { this.generator.Emit(op.OperationCode, parameterDefinition); break; } ISignature signature = op.Value as ISignature; if (signature != null) { this.generator.Emit(op.OperationCode, signature); break; } ITypeReference typeReference = op.Value as ITypeReference; if (typeReference != null) { this.generator.Emit(op.OperationCode, typeReference); break; } throw new Exception("Should never get here: no other IOperation argument types should exist"); case TypeCode.SByte: this.generator.Emit(op.OperationCode, (sbyte)op.Value); break; case TypeCode.Single: this.generator.Emit(op.OperationCode, (float)op.Value); break; case TypeCode.String: this.generator.Emit(op.OperationCode, (string)op.Value); break; default: // The other cases are the other enum values that TypeCode has. // But no other argument types should be in the Operations. ILGenerator cannot handle anything else, // so such IOperations should never exist. //case TypeCode.Boolean: //case TypeCode.Char: //case TypeCode.DateTime: //case TypeCode.DBNull: //case TypeCode.Decimal: //case TypeCode.Empty: // this would be the value for null, but the case when op.Value is null is handled before the switch statement //case TypeCode.UInt16: //case TypeCode.UInt32: //case TypeCode.UInt64: throw new Exception("Should never get here: no other IOperation argument types should exist"); } }
public static void Verify(IOperation operation, string expectedOperationTree, int initialIndent = 0) { var actual = GetOperationTree(operation, initialIndent); Assert.Equal(expectedOperationTree, actual); }
public IOperationBuilder PrevEvent(Action action) { Debug.Assert(action != null, ErrorMessages.NotNull); _operation = _operation.AddPreEvent(action); return(this); }
public Builder(IOperation operation) { Debug.Assert(operation != null, ErrorMessages.NotNull); _operation = operation; }
/// <summary> /// Sets the right part of the join /// </summary> /// <value>The right.</value> public NestedLoopsJoinOperation Right(IOperation value) { right.Register(value); return(this); }
public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterCompilationStartAction( (CompilationStartAnalysisContext compilationContext) => { TaintedDataConfig taintedDataConfig = TaintedDataConfig.GetOrCreate(compilationContext.Compilation); TaintedDataSymbolMap <SourceInfo> sourceInfoSymbolMap = taintedDataConfig.GetSourceSymbolMap(this.SinkKind); if (sourceInfoSymbolMap.IsEmpty) { return; } TaintedDataSymbolMap <SinkInfo> sinkInfoSymbolMap = taintedDataConfig.GetSinkSymbolMap(this.SinkKind); if (sinkInfoSymbolMap.IsEmpty) { return; } compilationContext.RegisterOperationBlockStartAction( operationBlockStartContext => { ISymbol owningSymbol = operationBlockStartContext.OwningSymbol; if (owningSymbol.IsConfiguredToSkipAnalysis(operationBlockStartContext.Options, TaintedDataEnteringSinkDescriptor, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken)) { return; } PooledHashSet <IOperation> rootOperationsNeedingAnalysis = PooledHashSet <IOperation> .GetInstance(); operationBlockStartContext.RegisterOperationAction( operationAnalysisContext => { IPropertyReferenceOperation propertyReferenceOperation = (IPropertyReferenceOperation)operationAnalysisContext.Operation; IOperation rootOperation = operationAnalysisContext.Operation.GetRoot(); if (sourceInfoSymbolMap.IsSourceProperty(propertyReferenceOperation.Property)) { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add(rootOperation); } } }, OperationKind.PropertyReference); operationBlockStartContext.RegisterOperationAction( operationAnalysisContext => { IInvocationOperation invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation; if (!sourceInfoSymbolMap.IsSourceMethodFast( invocationOperation.TargetMethod, invocationOperation.Arguments, out bool isSourceMethod, out bool requiresPointsTo, out bool requiresValueContent)) { return; } IOperation rootOperation = operationAnalysisContext.Operation.GetRoot(); if (isSourceMethod) { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add(rootOperation); } return; } else if (!requiresPointsTo && !requiresValueContent) { return; } PooledDictionary <PointsToCheck, ImmutableHashSet <string> > evaluateWithPointsToAnalysis = null; PooledDictionary <ValueContentCheck, ImmutableHashSet <string> > evaluateWithValueContentAnalysis = null; PointsToAnalysisResult pointsToAnalysisResult = null; ValueContentAnalysisResult valueContentAnalysisResult = null; if (rootOperation.TryGetEnclosingControlFlowGraph(out ControlFlowGraph cfg)) { pointsToAnalysisResult = PointsToAnalysis.TryGetOrComputeResult( cfg, owningSymbol, operationAnalysisContext.Options, WellKnownTypeProvider.GetOrCreate(operationAnalysisContext.Compilation), InterproceduralAnalysisConfiguration.Create( operationAnalysisContext.Options, SupportedDiagnostics, defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive, cancellationToken: operationAnalysisContext.CancellationToken), interproceduralAnalysisPredicateOpt: null); if (pointsToAnalysisResult == null) { return; } } if (requiresValueContent) { valueContentAnalysisResult = ValueContentAnalysis.TryGetOrComputeResult( cfg, owningSymbol, operationAnalysisContext.Options, WellKnownTypeProvider.GetOrCreate(operationAnalysisContext.Compilation), InterproceduralAnalysisConfiguration.Create( operationAnalysisContext.Options, SupportedDiagnostics, defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive, cancellationToken: operationAnalysisContext.CancellationToken), out var copyAnalysisResult, out pointsToAnalysisResult); if (valueContentAnalysisResult == null) { return; } } try { if (sourceInfoSymbolMap.IsSourceMethod( invocationOperation.TargetMethod, invocationOperation.Arguments, invocationOperation.Arguments.Select(o => pointsToAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), invocationOperation.Arguments.Select(o => valueContentAnalysisResult[o.Kind, o.Syntax]).ToImmutableArray(), out _)) { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add(rootOperation); } } } finally { evaluateWithPointsToAnalysis?.Free(); evaluateWithValueContentAnalysis?.Free(); } }, OperationKind.Invocation); if (taintedDataConfig.HasTaintArraySource(SinkKind)) { operationBlockStartContext.RegisterOperationAction( operationAnalysisContext => { IArrayInitializerOperation arrayInitializerOperation = (IArrayInitializerOperation)operationAnalysisContext.Operation; if (arrayInitializerOperation.GetAncestor <IArrayCreationOperation>(OperationKind.ArrayCreation)?.Type is IArrayTypeSymbol arrayTypeSymbol && sourceInfoSymbolMap.IsSourceConstantArrayOfType(arrayTypeSymbol)) { lock (rootOperationsNeedingAnalysis) { rootOperationsNeedingAnalysis.Add(operationAnalysisContext.Operation.GetRoot()); } } }, OperationKind.ArrayInitializer); } operationBlockStartContext.RegisterOperationBlockEndAction( operationBlockAnalysisContext => { try { lock (rootOperationsNeedingAnalysis) { if (!rootOperationsNeedingAnalysis.Any()) { return; } foreach (IOperation rootOperation in rootOperationsNeedingAnalysis) { if (!rootOperation.TryGetEnclosingControlFlowGraph(out var cfg)) { continue; } TaintedDataAnalysisResult taintedDataAnalysisResult = TaintedDataAnalysis.TryGetOrComputeResult( cfg, operationBlockAnalysisContext.Compilation, operationBlockAnalysisContext.OwningSymbol, operationBlockAnalysisContext.Options, TaintedDataEnteringSinkDescriptor, sourceInfoSymbolMap, taintedDataConfig.GetSanitizerSymbolMap(this.SinkKind), sinkInfoSymbolMap, operationBlockAnalysisContext.CancellationToken); if (taintedDataAnalysisResult == null) { return; } foreach (TaintedDataSourceSink sourceSink in taintedDataAnalysisResult.TaintedDataSourceSinks) { if (!sourceSink.SinkKinds.Contains(this.SinkKind)) { continue; } foreach (SymbolAccess sourceOrigin in sourceSink.SourceOrigins) { // Something like: // CA3001: Potential SQL injection vulnerability was found where '{0}' in method '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'. Diagnostic diagnostic = Diagnostic.Create( this.TaintedDataEnteringSinkDescriptor, sourceSink.Sink.Location, additionalLocations: new Location[] { sourceOrigin.Location }, messageArgs: new object[] { sourceSink.Sink.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), sourceSink.Sink.AccessingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), sourceOrigin.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), sourceOrigin.AccessingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) }); operationBlockAnalysisContext.ReportDiagnostic(diagnostic); } } } } } finally { rootOperationsNeedingAnalysis.Free(); } }); }); }); }
private void AnalyzeOperation(OperationAnalysisContext context, IOperation operation, IOperation instanceOperation) { // this is a static reference so we don't care if it's qualified if (instanceOperation == null) { return; } // if we're not referencing `this.` or `Me.` (e.g., a parameter, local, etc.) if (instanceOperation.Kind != OperationKind.InstanceReference) { return; } // Initializer lists are IInvocationOperation which if passed to GetApplicableOptionFromSymbolKind // will incorrectly fetch the options for method call. // We still want to handle InstanceReferenceKind.ContainingTypeInstance if ((instanceOperation as IInstanceReferenceOperation)?.ReferenceKind == InstanceReferenceKind.ImplicitReceiver) { return; } // If we can't be qualified (e.g., because we're already qualified with `base.`), we're done. if (!CanMemberAccessBeQualified(context.ContainingSymbol, instanceOperation.Syntax)) { return; } // if we can't find a member then we can't do anything. Also, we shouldn't qualify // accesses to static members. if (IsStaticMemberOrTargetMethod(operation)) { return; } var simpleName = instanceOperation.Syntax as TSimpleNameSyntax; if (simpleName == null) { return; } var syntaxTree = context.Operation.Syntax.SyntaxTree; var cancellationToken = context.CancellationToken; var optionSet = context.Options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return; } var applicableOption = QualifyMembersHelpers.GetApplicableOptionFromSymbolKind(operation); var optionValue = optionSet.GetOption(applicableOption, context.Operation.Syntax.Language); var shouldOptionBePresent = optionValue.Value; var severity = optionValue.Notification.Severity; if (!shouldOptionBePresent || severity == ReportDiagnostic.Suppress) { return; } if (!IsAlreadyQualifiedMemberAccess(simpleName)) { context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, GetLocation(operation), severity, additionalLocations: null, properties: null)); } }
protected abstract Location GetLocation(IOperation operation);
public NewsTypeController() { this.newsType = new OpertionClass <tblNewsType>(); }
private static bool IsWriteUsage(IOperation operation) { return(operation.Parent is IAssignmentOperation a && a.Target == operation || operation is IParameterReferenceOperation pro && pro.Parameter.RefKind == RefKind.Ref); }
static bool IsNullLiteral(IOperation o) => (o.IsImplicit && o is IConversionOperation conversion)
/// <summary> /// This method is called for every operation code. If a client needs to intercept each opcode, this is the method to override. Note that doing so means that /// the other RewriteOpertation methods will not be called. /// </summary> /// <param name="op">The MSIL operation to rewrite.</param> protected virtual void RewriteAny(IOperation op) { switch (op.OperationCode) { // Branches case OperationCode.Beq: case OperationCode.Bge: case OperationCode.Bge_Un: case OperationCode.Bgt: case OperationCode.Bgt_Un: case OperationCode.Ble: case OperationCode.Ble_Un: case OperationCode.Blt: case OperationCode.Blt_Un: case OperationCode.Bne_Un: case OperationCode.Br: case OperationCode.Brfalse: case OperationCode.Brtrue: case OperationCode.Leave: case OperationCode.Beq_S: case OperationCode.Bge_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_S: case OperationCode.Blt_Un_S: case OperationCode.Bne_Un_S: case OperationCode.Br_S: case OperationCode.Brfalse_S: case OperationCode.Brtrue_S: case OperationCode.Leave_S: case OperationCode.Switch: this.RewriteBranch(op); break; // calls case OperationCode.Call: case OperationCode.Calli: case OperationCode.Callvirt: case OperationCode.Jmp: this.RewriteCall(op); break; // loads from args/locals case OperationCode.Ldloc: case OperationCode.Ldloc_0: case OperationCode.Ldloc_1: case OperationCode.Ldloc_2: case OperationCode.Ldloc_3: case OperationCode.Ldloc_S: case OperationCode.Ldarg_0: case OperationCode.Ldarg_1: case OperationCode.Ldarg_2: case OperationCode.Ldarg_3: case OperationCode.Ldarg_S: this.RewriteLoadLocal(op); break; // stores to locals case OperationCode.Stloc: case OperationCode.Stloc_S: case OperationCode.Stloc_0: case OperationCode.Stloc_1: case OperationCode.Stloc_2: case OperationCode.Stloc_3: this.RewriteStoreLocal(op); break; // return opcode: always the last of funtion case OperationCode.Ret: this.RewriteReturn(op); break; // new objects case OperationCode.Newarr: case OperationCode.Newobj: this.RewriteNewObject(op); break; // set field case OperationCode.Stfld: this.RewriteStoreField(op); break; // load field case OperationCode.Ldflda: case OperationCode.Ldfld: this.RewriteLoadField(op); break; // Everything else default: this.RewriteOpertation(op); break; } }
public AbstractMonitor(IOperation operation) { docInfos = new List <Document>(); _operation = operation; }
public CSharpConversionExpression(IOperation operand, Conversion conversion, bool isTryCast, bool isChecked, SemanticModel semanticModel, SyntaxNode syntax, ITypeSymbol type, Optional <object> constantValue, bool isImplicit) : base(conversion, isTryCast, isChecked, semanticModel, syntax, type, constantValue, isImplicit) { OperandImpl = operand; }
public bool TryCreate(IOperation operation, [NotNullWhen(returnValue: true)] out AnalysisEntity?analysisEntity) { if (_analysisEntityMap.TryGetValue(operation, out analysisEntity)) { return(analysisEntity != null); } analysisEntity = null; ISymbol?symbol = null; ImmutableArray <AbstractIndex> indices = ImmutableArray <AbstractIndex> .Empty; IOperation? instance = null; ITypeSymbol?type = operation.Type; switch (operation) { case ILocalReferenceOperation localReference: symbol = localReference.Local; break; case IParameterReferenceOperation parameterReference: symbol = parameterReference.Parameter; break; case IMemberReferenceOperation memberReference: instance = memberReference.Instance; GetSymbolAndIndicesForMemberReference(memberReference, ref symbol, ref indices); // Workaround for https://github.com/dotnet/roslyn/issues/22736 (IPropertyReferenceExpressions in IAnonymousObjectCreationExpression are missing a receiver). if (instance == null && symbol != null && memberReference is IPropertyReferenceOperation propertyReference) { instance = propertyReference.GetAnonymousObjectCreation(); } break; case IArrayElementReferenceOperation arrayElementReference: instance = arrayElementReference.ArrayReference; indices = CreateAbstractIndices(arrayElementReference.Indices); break; case IDynamicIndexerAccessOperation dynamicIndexerAccess: instance = dynamicIndexerAccess.Operation; indices = CreateAbstractIndices(dynamicIndexerAccess.Arguments); break; case IConditionalAccessInstanceOperation conditionalAccessInstance: IConditionalAccessOperation?conditionalAccess = conditionalAccessInstance.GetConditionalAccess(); instance = conditionalAccess?.Operation; if (conditionalAccessInstance.Parent is IMemberReferenceOperation memberReferenceParent) { GetSymbolAndIndicesForMemberReference(memberReferenceParent, ref symbol, ref indices); } break; case IInstanceReferenceOperation instanceReference: if (_getPointsToAbstractValue != null) { instance = instanceReference.GetInstance(_getIsInsideAnonymousObjectInitializer()); if (instance == null) { // Reference to this or base instance. analysisEntity = _interproceduralCallStack != null && _interproceduralCallStack.Peek().DescendantsAndSelf().Contains(instanceReference) ? _interproceduralThisOrMeInstanceForCaller : ThisOrMeInstance; } else { var instanceLocation = _getPointsToAbstractValue(instanceReference); analysisEntity = AnalysisEntity.Create(instanceReference, instanceLocation); } } break; case IConversionOperation conversion: return(TryCreate(conversion.Operand, out analysisEntity)); case IParenthesizedOperation parenthesized: return(TryCreate(parenthesized.Operand, out analysisEntity)); case IArgumentOperation argument: return(TryCreate(argument.Value, out analysisEntity)); case IFlowCaptureOperation flowCapture: analysisEntity = GetOrCreateForFlowCapture(flowCapture.Id, flowCapture.Value.Type, flowCapture, _getIsLValueFlowCapture(flowCapture)); break; case IFlowCaptureReferenceOperation flowCaptureReference: analysisEntity = GetOrCreateForFlowCapture(flowCaptureReference.Id, flowCaptureReference.Type, flowCaptureReference, flowCaptureReference.IsLValueFlowCaptureReference()); break; case IDeclarationExpressionOperation declarationExpression: switch (declarationExpression.Expression) { case ILocalReferenceOperation localReference: return(TryCreateForSymbolDeclaration(localReference.Local, out analysisEntity)); case ITupleOperation tupleOperation: return(TryCreate(tupleOperation, out analysisEntity)); } break; case IVariableDeclaratorOperation variableDeclarator: symbol = variableDeclarator.Symbol; type = variableDeclarator.Symbol.Type; break; case IDeclarationPatternOperation declarationPattern: var declaredLocal = declarationPattern.DeclaredSymbol as ILocalSymbol; symbol = declaredLocal; type = declaredLocal?.Type; break; default: break; } if (symbol != null || !indices.IsEmpty) { TryCreate(symbol, indices, type !, instance, out analysisEntity); } _analysisEntityMap[operation] = analysisEntity; return(analysisEntity != null); }
private void VisitInstanceExpression(IOperation instance) { Visit(instance, header: "Instance Receiver"); }
private static IEnumerable <NameAndType> GetParameters(IOperation operation) { var semanticModel = operation.SemanticModel; var node = operation.Syntax; while (node != null) { switch (node) { case AccessorDeclarationSyntax accessor: { if (accessor.IsKind(SyntaxKind.SetAccessorDeclaration)) { var property = node.Ancestors().OfType <PropertyDeclarationSyntax>().FirstOrDefault(); if (property != null) { var symbol = operation.SemanticModel.GetDeclaredSymbol(property); if (symbol != null) { yield return(new NameAndType("value", symbol.Type)); } } } break; } case PropertyDeclarationSyntax _: yield break; case IndexerDeclarationSyntax indexerDeclarationSyntax: { var symbol = semanticModel.GetDeclaredSymbol(indexerDeclarationSyntax); if (symbol != null) { foreach (var parameter in symbol.Parameters) { yield return(new NameAndType(parameter.Name, parameter.Type)); } } yield break; } case MethodDeclarationSyntax methodDeclaration: { var symbol = semanticModel.GetDeclaredSymbol(methodDeclaration); if (symbol != null) { foreach (var parameter in symbol.Parameters) { yield return(new NameAndType(parameter.Name, parameter.Type)); } } yield break; } case LocalFunctionStatementSyntax localFunctionStatement: { var symbol = semanticModel.GetDeclaredSymbol(localFunctionStatement) as IMethodSymbol; if (symbol != null) { foreach (var parameter in symbol.Parameters) { yield return(new NameAndType(parameter.Name, parameter.Type)); } } break; } case ConstructorDeclarationSyntax constructorDeclaration: { var symbol = semanticModel.GetDeclaredSymbol(constructorDeclaration); if (symbol != null) { foreach (var parameter in symbol.Parameters) { yield return(new NameAndType(parameter.Name, parameter.Type)); } } yield break; } } node = node.Parent; } }
static void Main(string[] args) { var eval = "5 1 2 + 4 * + 3 - 12 - 5 pow"; // result 32 Dictionary <String, IOperation> dictionary = new Dictionary <string, IOperation>(); dictionary.Add("sqrt", new UnaryOperation(x => Math.Sqrt(x))); dictionary.Add("abs", new UnaryOperation((x) => Math.Abs(x))); dictionary.Add("+", new BinaryOperation((x, y) => (x + y))); dictionary.Add("-", new BinaryOperation((x, y) => (x - y))); dictionary.Add("*", new BinaryOperation((x, y) => (x * y))); dictionary.Add("/", new BinaryOperation((x, y) => (x / y))); dictionary.Add("pow", new BinaryOperation((x, y) => Math.Pow(x, y))); //IOperation oper = new UnaryOperation(x => Math.Sqrt(x)); //IOperation oper1 = new BinaryOperation((x, y) => (x + y)); //Console.WriteLine(oper.Execute(9)); //Console.WriteLine(oper1.Execute(7, 79)); string[] split = eval.Split(' '); List <double> stack = new List <double>(); double tempResult = 0; for (int i = 0; i < split.Length; i++) { double temp; if (double.TryParse(split[i], out temp)) { stack.Add(temp); } else { try { IOperation oper = dictionary[split[i]]; if (oper is UnaryOperation) { tempResult = oper.Execute(stack[stack.Count - 1]); stack.RemoveAt(stack.Count - 1); stack.Add(tempResult); } else if (oper is BinaryOperation) { tempResult = oper.Execute(stack[stack.Count - 2], stack[stack.Count - 1]); stack.RemoveAt(stack.Count - 2); stack.RemoveAt(stack.Count - 1); stack.Add(tempResult); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } if (stack.Count == 1) { Console.WriteLine(stack[0]); } Console.ReadKey(); }
public static IConditionalAccessInstanceOperationWrapper FromOperation(IOperation operation) { if (operation == null) { return(default);
public NewsTypeController(IOperation <tblNewsType> _newsType) { this.newsType = _newsType; }
/// <summary> /// Sets the left part of the join /// </summary> /// <value>The left.</value> public NestedLoopsJoinOperation Left(IOperation value) { left.Register(value); leftRegistered = true; return(this); }
/// <summary> /// Initialises a new instance of the Dynamics365SetStateUserProvidedValue class with the specified parent operation. /// </summary> /// <param name="parentOperation">The parent operation.</param> public Dynamics365SetStateUserProvidedValue(IOperation parentOperation) : base(parentOperation) { }
internal static PerLanguageOption <CodeStyleOption <bool> > GetApplicableOptionFromSymbolKind(IOperation operation) { switch (operation) { case IMemberReferenceOperation memberReferenceOperation: return(GetApplicableOptionFromSymbolKind(memberReferenceOperation.Member.Kind)); case IInvocationOperation invocationOperation: return(GetApplicableOptionFromSymbolKind(invocationOperation.TargetMethod.Kind)); default: throw ExceptionUtilities.UnexpectedValue(operation); } }
public ForToLoopOperationUserDefinedInfo(IBinaryOperation addition, IBinaryOperation subtraction, IOperation lessThanOrEqual, IOperation greaterThanOrEqual) { Addition = addition; Subtraction = subtraction; LessThanOrEqual = lessThanOrEqual; GreaterThanOrEqual = greaterThanOrEqual; }
public ConsoleOperation(IOperation parent) : base(parent) { }