/// <summary> /// Registers the deployment asynchronously. /// </summary> /// <param name="deployment">The deployment.</param> /// <returns></returns> public async Task RegisterAsync(IDeployment deployment) { Assumption.AssertNotNullOrWhiteSpace(this._writeAccessToken, nameof(this._writeAccessToken)); var config = new RollbarConfig(this._writeAccessToken) { Environment = deployment.Environment, }; RollbarClient rollbarClient = new RollbarClient(config); await rollbarClient.PostAsync(deployment); }
/// <summary> /// Initializes a new instance of the <see cref="RollbarLoggerProvider" /> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The options.</param> /// <param name="httpContextAccessor">The HTTP context accessor.</param> public RollbarLoggerProvider( IConfiguration configuration , IOptions <NetPlatformExtensions.RollbarOptions> options , IHttpContextAccessor httpContextAccessor ) : base(configuration, options) { Assumption.AssertNotNull(configuration, nameof(configuration)); Assumption.AssertNotNull(options, nameof(options)); Assumption.AssertNotNull(this._rollbarConfig, nameof(this._rollbarConfig)); Assumption.AssertNotNullOrWhiteSpace(this._rollbarConfig.AccessToken, nameof(this._rollbarConfig.AccessToken)); this._httpContextAccessor = httpContextAccessor; }
private void OnRollbarEvent(RollbarEventArgs e) { Assumption.AssertNotNull(e, nameof(e)); Assumption.AssertNotNull(e.Logger, nameof(e.Logger)); EventHandler <RollbarEventArgs> handler = InternalEvent; if (handler != null) { handler(this, e); } e.Logger.OnRollbarEvent(e); }
/// <summary> /// Initializes a new instance of the <see cref="ObjectPackage"/> class. /// </summary> /// <param name="objectToPackage">The object to package.</param> /// <param name="rollbarDataTitle">The rollbar data title.</param> /// <param name="custom">The custom.</param> /// <param name="mustApplySynchronously">if set to <c>true</c> [must apply synchronously].</param> public ObjectPackage( object objectToPackage, string?rollbarDataTitle, IDictionary <string, object?>?custom, bool mustApplySynchronously ) : base(mustApplySynchronously) { Assumption.AssertNotNull(objectToPackage, nameof(objectToPackage)); this._objectToPackage = objectToPackage; this._rollbarDataTitle = rollbarDataTitle; this._custom = custom; }
public async Task <RollbarResponse> PostAsJsonAsync(Payload payload) { Assumption.AssertNotNull(payload, nameof(payload)); if (this._payloadTruncationStrategy.Truncate(payload) > this._payloadTruncationStrategy.MaxPayloadSizeInBytes) { throw new ArgumentOutOfRangeException( paramName: nameof(payload), message: $"Payload size exceeds {this._payloadTruncationStrategy.MaxPayloadSizeInBytes} bytes limit!" ); } var jsonData = JsonConvert.SerializeObject(payload); jsonData = ScrubPayload(jsonData, this._config.GetSafeScrubFields()); var postPayload = new StringContent(jsonData, Encoding.UTF8, "application/json"); //CONTENT-TYPE header Assumption.AssertTrue(string.Equals(payload.AccessToken, this._config.AccessToken), nameof(payload.AccessToken)); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, this._payloadPostUri); const string accessTokenHeader = "X-Rollbar-Access-Token"; request.Headers.Add(accessTokenHeader, this._config.AccessToken); request.Content = postPayload; var postResponse = await this._httpClient.SendAsync(request); RollbarResponse response = null; if (postResponse.IsSuccessStatusCode) { string reply = await postResponse.Content.ReadAsStringAsync(); response = JsonConvert.DeserializeObject <RollbarResponse>(reply); response.HttpDetails = $"Response: {postResponse}" + Environment.NewLine + $"Request: {postResponse.RequestMessage}" + Environment.NewLine ; } else { postResponse.EnsureSuccessStatusCode(); } return(response); }
public async Task <RollbarResponse> PostAsJsonAsync(Payload payload, IEnumerable <string> scrubFields) { Assumption.AssertNotNull(payload, nameof(payload)); if (this._payloadTruncationStrategy.Truncate(payload) > this._payloadTruncationStrategy.MaxPayloadSizeInBytes) { throw new ArgumentOutOfRangeException( paramName: nameof(payload), message: $"Payload size exceeds {this._payloadTruncationStrategy.MaxPayloadSizeInBytes} bytes limit!" ); } using (var httpClient = this.BuildWebClient()) { var jsonData = JsonConvert.SerializeObject(payload); jsonData = ScrubPayload(jsonData, scrubFields); httpClient.DefaultRequestHeaders .Add("X-Rollbar-Access-Token", payload.AccessToken); httpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); //ACCEPT header var postPayload = new StringContent(jsonData, Encoding.UTF8, "application/json"); //CONTENT-TYPE header var uri = new Uri($"{Config.EndPoint}item/"); var postResponse = await httpClient.PostAsync(uri, postPayload); RollbarResponse response = null; if (postResponse.IsSuccessStatusCode) { string reply = await postResponse.Content.ReadAsStringAsync(); response = JsonConvert.DeserializeObject <RollbarResponse>(reply); response.HttpDetails = $"Response: {postResponse}" + Environment.NewLine + $"Request: {postResponse.RequestMessage}" + Environment.NewLine ; } else { postResponse.EnsureSuccessStatusCode(); } return(response); } }
/// <summary> /// Loads the application settings. /// </summary> /// <param name="config">The configuration.</param> /// <param name="appSettingsFolderPath">The application settings folder path.</param> /// <param name="appSettingsFileName">Name of the application settings file.</param> /// <returns>false when the configuration was not found, otherwise true.</returns> public static bool LoadAppSettings(RollbarConfig config, string appSettingsFolderPath, string appSettingsFileName) { Assumption.AssertNotNull(config, nameof(config)); IConfiguration appSettingsConfig = AppSettingsUtility.LoadAppSettings(appSettingsFolderPath, appSettingsFileName); if (appSettingsConfig == null) { return(false); } AppSettingsUtility.LoadAppSettings(config, appSettingsConfig); return(true); }
/// <summary> /// Gets the static field value. /// </summary> /// <typeparam name="TFieldDataType">The type of the field data type.</typeparam> /// <param name="staticField">The static field.</param> /// <returns></returns> public static TFieldDataType?GetStaticFieldValue <TFieldDataType>(FieldInfo staticField) { Assumption.AssertTrue(staticField.IsStatic, nameof(staticField.IsStatic)); object?valueObject = staticField.GetValue(null); if (valueObject != null) { TFieldDataType result = (TFieldDataType)valueObject; return(result); } return(default);
/// <summary> /// Unregisters the specified queue. /// </summary> /// <param name="queue">The queue.</param> private void Unregister(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!queue.Logger.IsSingleton, nameof(queue.Logger.IsSingleton)); Assumption.AssertTrue(this._allQueues.Contains(queue), nameof(queue)); this.DropIndexByToken(queue); this._allQueues.Remove(queue); this.ReevaluateUseOfLocalPayloadStore(); ((RollbarConfig)queue.Logger.Config).Reconfigured -= Config_Reconfigured; Debug.WriteLine(this.GetType().Name + ": Unregistered a queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// Loads the application settings. /// </summary> /// <param name="config">The configuration.</param> /// <returns>false when the configuration was not found, otherwise true.</returns> public static bool LoadAppSettings(RollbarInfrastructureConfig config) { Assumption.AssertNotNull(config, nameof(config)); IConfiguration?appSettingsConfig = AppSettingsUtility.LoadAppSettings(); if (appSettingsConfig == null) { return(false); } AppSettingsUtility.LoadAppSettings(config, appSettingsConfig); return(true); }
/// <summary> /// Registers the specified queue. /// </summary> /// <param name="queue">The queue.</param> internal void Register(PayloadQueue queue) { lock (this._syncLock) { Assumption.AssertTrue(!this._allQueues.Contains(queue), nameof(queue)); this._allQueues.Add(queue); this.IndexByToken(queue); ((RollbarConfig)queue.Logger.Config).Reconfigured += Config_Reconfigured; // The following debug line causes stack overflow when RollbarTraceListener is activated: Debug.WriteLineIf(RollbarTraceListener.InstanceCount == 0, this.GetType().Name + ": Registered a queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// Validates this instance. /// </summary> public override void Validate() { Assumption.AssertNotNullOrWhiteSpace(this.Environment, nameof(this.Environment)); Assumption.AssertNotNull(this.Body, nameof(this.Body)); this.Body.Validate(); this.Server?.Validate(); this.Request?.Validate(); this.Person?.Validate(); this.Client?.Validate(); base.Validate(); }
/// <summary> /// Loads the application settings. /// </summary> /// <param name="config">The configuration.</param> /// <returns>false when the configuration was not found, otherwise true.</returns> public static bool LoadAppSettings(TelemetryConfig config) { Assumption.AssertNotNull(config, nameof(config)); IConfiguration appSettingsConfig = AppSettingsUtility.LoadAppSettings(); if (appSettingsConfig == null) { return(false); } AppSettingsUtility.LoadAppSettings(config, appSettingsConfig); return(true); }
/// <summary> /// Posts the specified deployment asynchronously. /// </summary> /// <param name="deployment">The deployment.</param> /// <returns></returns> public async Task PostAsync(IDeployment deployment) { Assumption.AssertNotNull(this._config, nameof(this._config)); Assumption.AssertNotNullOrWhiteSpace(this._config.AccessToken, nameof(this._config.AccessToken)); Assumption.AssertFalse(string.IsNullOrWhiteSpace(deployment.Environment) && string.IsNullOrWhiteSpace(this._config.Environment), nameof(deployment.Environment)); Assumption.AssertNotNullOrWhiteSpace(deployment.Revision, nameof(deployment.Revision)); Assumption.AssertLessThan( deployment.Environment.Length, 256, nameof(deployment.Environment.Length) ); Assumption.AssertTrue( deployment.LocalUsername == null || deployment.LocalUsername.Length < 256, nameof(deployment.LocalUsername) ); Assumption.AssertTrue( deployment.Comment == null || StringUtility.CalculateExactEncodingBytes(deployment.Comment, Encoding.UTF8) <= (62 * 1024), nameof(deployment.Comment) ); var uri = new Uri(this._config.EndPoint + RollbarDeployClient.deployApiPath); var parameters = new Dictionary <string, string> { { "access_token", this._config.AccessToken }, { "environment", (!string.IsNullOrWhiteSpace(deployment.Environment)) ? deployment.Environment : this._config.Environment }, { "revision", deployment.Revision }, { "rollbar_username", deployment.RollbarUsername }, { "local_username", deployment.LocalUsername }, { "comment", deployment.Comment }, }; var httpContent = new FormUrlEncodedContent(parameters); var httpClient = ProvideHttpClient(); var postResponse = await httpClient.PostAsync(uri, httpContent); if (postResponse.IsSuccessStatusCode) { string reply = await postResponse.Content.ReadAsStringAsync(); } else { postResponse.EnsureSuccessStatusCode(); } this.Release(httpClient); return; }
internal Trace(string callStack, string exceptionInfo) { Assumption.AssertNotNullOrEmpty(callStack, nameof(callStack)); Assumption.AssertNotNullOrEmpty(exceptionInfo, nameof(exceptionInfo)); string[] entries = callStack.Split(new [] { Environment.NewLine, }, StringSplitOptions.None); List <DTOs.Frame> frames = new List <Frame>(entries.Length); foreach (var entry in entries) { if (string.IsNullOrWhiteSpace(entry)) { continue; } frames.Add(new DTOs.Frame(entry)); } if (frames.Count > 0) { this.Frames = frames.ToArray(); } entries = exceptionInfo.Split(new [] { ": ", }, StringSplitOptions.None); DTOs.Exception ex = null; switch (entries.Length) { case 3: ex = new DTOs.Exception(entries[0], entries[1], entries[2]); break; case 2: ex = new DTOs.Exception(entries[0], entries[1]); break; case 1: ex = new DTOs.Exception(entries[0]); break; default: System.Diagnostics.Trace.WriteLine( $"Unexpected exception info component/entry..." ); break; } if (ex != null) { this.Exception = ex; } }
private void EvaluateUsing(Method theClassifier, ClassificationDeclaration classificationDeclaration) { classificationDeclaration.Method = theClassifier; switch (classificationDeclaration.Method) { case Method.Log: EvaluateLogMethod(classificationDeclaration); break; default: Assumption.FailValidation("Unexpected value!", nameof(classificationDeclaration.Method)); break; } }
/// <summary> /// Gets the deployments page asynchronously. /// </summary> /// <param name="environment">The environment.</param> /// <param name="pageNumber">The page number.</param> /// <returns></returns> public async Task <IDeploymentDetails[]> GetDeploymentsPageAsync(string environment, int pageNumber) { Assumption.AssertNotNullOrWhiteSpace(this._readAccessToken, nameof(this._readAccessToken)); var config = new RollbarConfig(this._readAccessToken); using (var httpClient = new HttpClient()) { RollbarDeployClient rollbarClient = new RollbarDeployClient(config, httpClient); var result = await rollbarClient.GetDeploymentsAsync(this._readAccessToken, pageNumber); return(result.DeploysPage.Deploys); } }
/// <summary> /// Post as json as an asynchronous operation. /// </summary> /// <param name="accessToken">The access token.</param> /// <param name="jsonContent">Content of the json.</param> /// <param name="cancellationToken"> /// The cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>A Task<RollbarResponse> representing the asynchronous operation.</returns> public async Task <RollbarResponse?> PostAsJsonAsync( string accessToken, string jsonContent, CancellationToken?cancellationToken = null ) { Assumption.AssertNotNullOrWhiteSpace(accessToken, nameof(accessToken)); Assumption.AssertNotNullOrWhiteSpace(jsonContent, nameof(jsonContent)); return(await PostAsJsonAsync( accessToken, new StringContent(jsonContent), cancellationToken )); }
/// <summary> /// Adds the Rollbar logging client. /// </summary> /// <param name="factory">The factory.</param> /// <param name="configuration">The configuration.</param> /// <param name="rollbarOptions">The rollbar options.</param> /// <param name="httpContextAccessor">The HTTP context accessor.</param> /// <returns></returns> public static ILoggerFactory AddRollbar( this ILoggerFactory factory , IConfiguration configuration , IOptions <RollbarOptions> rollbarOptions , IHttpContextAccessor httpContextAccessor ) { Assumption.AssertNotNull(configuration, nameof(configuration)); factory.AddProvider( new RollbarLoggerProvider(configuration, rollbarOptions, httpContextAccessor) ); return(factory); }
/// <summary> /// Initializes a new instance of the <see cref="RollbarConfig"/> class. /// </summary> /// <param name="accessToken">The access token.</param> public RollbarConfig(string accessToken) { Assumption.AssertNotNullOrWhiteSpace(accessToken, nameof(accessToken)); this.SetDefaults(); if (!string.IsNullOrWhiteSpace(accessToken)) { this.AccessToken = accessToken; } else { // initialize based on application configuration file (if any): NetStandard.RollbarConfigUtility.Load(this); } }
private void SnapProperties(HttpRequest httpRequest) { Assumption.AssertNotNull(httpRequest, nameof(httpRequest)); this.Url = httpRequest.Host.Value + httpRequest.Path; this.QueryString = httpRequest.QueryString.Value; this.Params = null; this.Headers = new Dictionary <string, string>(httpRequest.Headers.Count()); foreach (var header in httpRequest.Headers) { this.Headers.Add(header.Key, StringUtility.Combine(header.Value, ", ")); } this.Method = httpRequest.Method; }
public override object GetHtml(Assumption assumption, Func <MemberInfo, object> memberHtml, Func <Type, object> typeHtml) { var member = GetMember(); return(member != null ? memberHtml(member) : new SPAN { class_ = "Method", title = Original } ._( Member.GetHtml(Assumption.Member, memberHtml, typeHtml), "(", ParameterTypes.Select(p => p.GetHtml(Assumption.Type, memberHtml, typeHtml)).InsertBetween <object>(", "), ")" )); }
/// <summary> /// Gets the deployment asynchronously. /// </summary> /// <param name="deploymentID">The deployment identifier.</param> /// <returns></returns> public async Task <IDeploymentDetails> GetDeploymentAsync(string deploymentID) { Assumption.AssertNotNullOrWhiteSpace(deploymentID, nameof(deploymentID)); Assumption.AssertNotNullOrWhiteSpace(this._readAccessToken, nameof(this._readAccessToken)); var config = new RollbarConfig(this._readAccessToken); using (var httpClient = new HttpClient()) { RollbarDeployClient rollbarClient = new RollbarDeployClient(config, httpClient); var result = await rollbarClient.GetDeploymentAsync(this._readAccessToken, deploymentID); return(result.Deploy); } }
private object ProvideObjectToLog(ClassificationDeclaration classificationDeclaration) { switch (classificationDeclaration.PayloadType) { case PayloadType.Message: return(ProvideMessage(classificationDeclaration.PayloadSize)); case PayloadType.Exception: return(ProvideException(classificationDeclaration.PayloadSize)); default: Assumption.FailValidation("Unexpected value!", nameof(classificationDeclaration.PayloadType)); break; } return(null); }
/// <summary> /// Initializes a new instance of the <see cref="HttpRequestMessagePackageDecorator"/> class. /// </summary> /// <param name="packageToDecorate">The package to decorate.</param> /// <param name="httpRequestMessage">The HTTP request message.</param> /// <param name="rollbarConfig">The rollbar configuration.</param> /// <param name="arbitraryKeyValuePairs">The arbitrary key value pairs.</param> /// <param name="mustApplySynchronously">if set to <c>true</c> [must apply synchronously].</param> public HttpRequestMessagePackageDecorator( IRollbarPackage packageToDecorate, HttpRequestMessage httpRequestMessage, IRollbarConfig rollbarConfig, IDictionary <string, object> arbitraryKeyValuePairs, bool mustApplySynchronously ) : base(packageToDecorate, mustApplySynchronously) { Assumption.AssertNotNull(httpRequestMessage, nameof(httpRequestMessage)); Assumption.AssertNotNull(rollbarConfig, nameof(rollbarConfig)); this._httpRequestMessage = httpRequestMessage; this._rollbarConfig = rollbarConfig; this._arbitraryKeyValuePairs = arbitraryKeyValuePairs; }
/// <summary> /// Initializes a new instance of the <see cref="RollbarLoggerProvider" /> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="options">The options.</param> /// <param name="httpContextAccessor">The HTTP context accessor.</param> public RollbarLoggerProvider( IConfiguration configuration , IOptions <RollbarOptions> options , IHttpContextAccessor httpContextAccessor ) { Assumption.AssertNotNull(configuration, nameof(configuration)); Assumption.AssertNotNull(options, nameof(options)); this._rollbarOptions = options.Value; this._rollbarConfig = RollbarConfigurationUtil.DeduceRollbarConfig(configuration); this._httpContextAccessor = httpContextAccessor; Assumption.AssertNotNull(this._rollbarConfig, nameof(this._rollbarConfig)); Assumption.AssertNotNullOrWhiteSpace(this._rollbarConfig.AccessToken, nameof(this._rollbarConfig.AccessToken)); }
private void Config_Reconfigured(object sender, EventArgs e) { lock (this._syncLock) { RollbarConfig config = (RollbarConfig)sender; Assumption.AssertNotNull(config, nameof(config)); PayloadQueue queue = config.Logger.Queue; Assumption.AssertNotNull(queue, nameof(queue)); //refresh indexing: this.DropIndexByToken(queue); this.IndexByToken(queue); Debug.WriteLine(this.GetType().Name + ": Re-indexed a reconfigured queue. Total queues count: " + this._allQueues.Count + "."); } }
/// <summary> /// post as json as an asynchronous operation. /// </summary> /// <param name="payloadBundle">The payload bundle.</param> /// <returns>Task<RollbarResponse>.</returns> public async Task <RollbarResponse> PostAsJsonAsync(PayloadBundle payloadBundle) { Assumption.AssertNotNull(payloadBundle, nameof(payloadBundle)); // make sure there anything meaningful to send: if (!EnsureHttpContentToSend(payloadBundle)) { return(null); } return(await PostAsJsonAsync( this._payloadPostUri, this._rollbarLogger.Config.AccessToken, payloadBundle.AsHttpContentToSend )); }
/// <summary> /// This event is executed when the remove assumption buttin is clicked. /// The method will move all selected items in the selected pane to the deselected pane. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveAssumptionButton_Click(object sender, RoutedEventArgs e) { ParseGroup selectedGroup = GroupSelector.SelectedValue as ParseGroup; if (selectedGroup == null) { return; } foreach (object value in SelectedAssumptions.SelectedItems) { Assumption a = value as Assumption; selectedGroup.Assumptions.Remove(a); } RefreshAssumptionLists(selectedGroup); }
/// <summary> /// Initializes the specified configuration. /// </summary> /// <param name="config">The configuration.</param> /// <exception cref="RollbarException"> /// Exception while initializing the internal services! /// </exception> public void Init(IRollbarInfrastructureConfig config) { Assumption.AssertNotNull(config, nameof(config)); lock (this._syncLock) { if (this._isInitialized) { string msg = $"{typeof(RollbarInfrastructure).Name} can not be initialized more than once!"; traceSource.TraceInformation(msg); throw new RollbarException( InternalRollbarError.InfrastructureError, msg ); } this._config = config; this.ValidateConfiguration(); this._config.Reconfigured += _config_Reconfigured; this._isInitialized = true; // now, since the basic infrastructure seems to be good and initialized, // let's initialize all the dependent services of the infrastructure: try { RollbarQueueController.Instance !.Init(config); RollbarTelemetryCollector.Instance !.Init(config.RollbarTelemetryOptions); // NOTE: RollbarConfig // - init ConnectivityMonitor service as needed // NOTE: It should be sufficient to make ConnectivityMonitor as internal class // It is only used by RollbarClient and RollbarQueueController that are // already properly deactivated in single-threaded environments. } catch (Exception ex) { this._isInitialized = false; throw new RollbarException( InternalRollbarError.InfrastructureError, "Exception while initializing the internal services!", ex ); } } }
public override Statement VisitAssumption(Assumption assumption){ if (assumption == null || assumption.Condition == null) return null; StatementList stmts = new StatementList(); if (!(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableInternalContractsMetadata)) { foreach (Statement s in this.SerializeAssertion(this.currentModule, assumption.Condition, null, assumption.SourceContext, "AssumeStatement")) { stmts.Add(s); } } if (!(this.currentCompilation != null && this.currentCompilation.CompilerParameters is CompilerOptions && ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableAssumeChecks)) stmts.Add(this.MarkAsInstrumentationCodeNormalized(this.currentMethod, this.CreateAssertionCheckingCode(assumption.Condition, "Assume"))); return new Block(stmts); }
public virtual Statement VisitAssumption(Assumption Assumption1, Assumption Assumption2) { if (Assumption1 == null) return null; if (Assumption2 == null) Assumption1.Condition = this.VisitExpression(Assumption1.Condition, null); else Assumption1.Condition = this.VisitExpression(Assumption1.Condition, Assumption2.Condition); return Assumption1; }
public override Statement VisitAssumption(Assumption Assumption) { if (Assumption == null) return null; this.insideAssertOrAssume = true; Assumption.Condition = this.VisitBooleanExpression(Assumption.Condition); this.insideAssertOrAssume = false; return Assumption; }
public override Method VisitMethod(Method method) { if (method == null) return null; if (method.IsNormalized) return method; this.MayReferenceThisAndBase = !(method is InstanceInitializer) || method.DeclaringType == null || method.DeclaringType.IsValueType; if (method.Name != null && method.Name.UniqueIdKey == StandardIds.Finalize.UniqueIdKey && method.HasCompilerGeneratedSignature && method.DeclaringType is Class && ((Class)method.DeclaringType).IsAbstractSealedContainerForStatics) this.HandleError(method.Name, Error.DestructorInAbstractSealedClass); method.Attributes = this.VisitAttributeList(method.Attributes, method); method.ReturnAttributes = this.VisitAttributeList(method.ReturnAttributes); method.SecurityAttributes = this.VisitSecurityAttributeList(method.SecurityAttributes); if ((method.ReturnType == SystemTypes.DynamicallyTypedReference || method.ReturnType == SystemTypes.ArgIterator) && (this.currentOptions == null || !this.currentOptions.NoStandardLibrary) ) { this.HandleError(method.Name, Error.CannotReturnTypedReference, this.GetTypeName(method.ReturnType)); method.ReturnType = SystemTypes.Object; } if (method.Body != null) { if (method.DeclaringType is Interface && !method.IsStatic) { this.HandleError(method.Name, Error.InterfaceMemberHasBody, this.GetMethodSignature(method)); method.Body = null; } else if (method.IsAbstract) { this.HandleError(method.Name, Error.AbstractHasBody, this.GetMethodSignature(method)); method.Body = null; } } else if (!method.IsAbstract && !method.IsExtern && !this.isCompilingAContractAssembly) { this.HandleError(method.Name, Error.ConcreteMissingBody, this.GetMethodSignature(method)); return null; } else if (method.TemplateParameters != null && method.TemplateParameters.Count > 0 && !this.useGenerics) { SourceContext ctx = method.TemplateParameters[0].SourceContext; ctx.EndPos = method.TemplateParameters[method.TemplateParameters.Count-1].SourceContext.EndPos; Debug.Assert(ctx.EndPos >= ctx.StartPos); Node n = new UnaryExpression(); n.SourceContext = ctx; if (method.DeclaringType is Interface) this.HandleError(n, Error.AbstractInterfaceMethod); else this.HandleError(n, Error.AbstractMethodTemplate); return null; } BlockScope savedCurrentFinallyClause = this.currentFinallyClause; Method savedCurrentMethod = this.currentMethod; Return savedReturnNode = this.returnNode; Yield savedYieldNode = this.yieldNode; this.currentFinallyClause = null; this.currentMethod = method; this.returnNode = null; this.yieldNode = null; MethodScope scope = method.Scope; this.CheckForDuplicateDeclarations(scope); if ((this.currentPreprocessorDefinedSymbols != null && this.currentPreprocessorDefinedSymbols.ContainsKey("DefaultExposeBlocks")) && !method.IsStatic && !(method is InstanceInitializer) && method.DeclaringType is Class && !method.IsAbstract && method.CciKind == CciMemberKind.Regular && method.ApplyDefaultContract) { This thisOb = method.ThisParameter; MethodCall thisIsExposable = new MethodCall( new MemberBinding(null, SystemTypes.Guard.GetMethod(Identifier.For("FrameIsExposable"), SystemTypes.Object, SystemTypes.Type)), new ExpressionList(thisOb, new UnaryExpression(new Literal(method.DeclaringType, SystemTypes.Type), NodeType.Typeof, OptionalModifier.For(SystemTypes.NonNullType, SystemTypes.Type))), NodeType.Call, SystemTypes.Boolean, method.Body.SourceContext); Assumption assumption = new Assumption(thisIsExposable); Expose expose = new Expose(NodeType.Write); expose.SourceContext = method.Body.SourceContext; expose.Instance = thisOb; expose.Body = method.Body; if (this.currentOptions != null && this.currentOptions.DisableGuardedClassesChecks) method.Body = new Block(new StatementList(assumption, expose)); else method.Body = new Block(new StatementList(expose)); } #region Check contract rules for all interface methods and base methods this method implements/overrides bool ok = true; if (method.IsVirtual && !method.IsCompilerControlled) { // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method); if (overridden != null) { ok &= this.CheckContractRules(overridden, method, method.DeclaringType); } for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) { Method ifaceMethod = method.ImplementedInterfaceMethods[i]; ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType); } for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) { Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i]; ok &= this.CheckContractRules(ifaceMethod, method, method.DeclaringType); } } #endregion #region Contract Inheritance for method overrides and interface implementations (do this somewhere else?) // This needs to be done here (and not in VisitMethodContract) because method might not even have a contract if (method.IsVirtual && ok && !method.IsCompilerControlled) { // use FindNearest..., can't rely on method.OverriddenMethod since it might not be set further up the chain Method overridden = method.DeclaringType.FindNearestOverriddenMethod(method); // FindNearestOverriddenMethod doesn't care if method is "new" or an "override", so explicity test IsVirtual property MethodContract cumulativeContract = method.Contract == null ? new MethodContract(method) : method.Contract; bool somethingWasCopied = false; while (overridden != null && overridden.IsVirtual) { if (overridden.Contract != null) { cumulativeContract.CopyFrom(overridden.Contract); somethingWasCopied = true; break; } overridden = overridden.DeclaringType.FindNearestOverriddenMethod(overridden); } // Can inherit from at most one interface method bool ifaceContractWasCopied = false; for (int i = 0, n = method.ImplementedInterfaceMethods == null ? 0 : method.ImplementedInterfaceMethods.Count; i < n; i++) { Method ifaceMethod = method.ImplementedInterfaceMethods[i]; if (ifaceMethod == null) continue; if (ifaceMethod.Contract != null) { if (ifaceContractWasCopied) { this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod)); break; } cumulativeContract.CopyFrom(ifaceMethod.Contract); somethingWasCopied = true; ifaceContractWasCopied = true; } } for (int i = 0, n = method.ImplicitlyImplementedInterfaceMethods == null ? 0 : method.ImplicitlyImplementedInterfaceMethods.Count; i < n; i++) { Method ifaceMethod = method.ImplicitlyImplementedInterfaceMethods[i]; if (ifaceMethod == null) continue; if (ifaceMethod.Contract != null) { if (ifaceContractWasCopied) { this.HandleError(method, Error.RequiresNotAllowedInInterfaceImplementation, this.GetMethodSignature(ifaceMethod)); break; } cumulativeContract.CopyFrom(ifaceMethod.Contract); somethingWasCopied = true; ifaceContractWasCopied = true; } } if (method.Contract == null && somethingWasCopied) { // otherwise it was already copied into the method's contract method.Contract = cumulativeContract; } } #endregion // For checked exceptions, the actual exceptions thrown must be a subset of the allowed exceptions TypeNodeList aes = new TypeNodeList(); if (method.Contract != null && method.Contract.Ensures != null) { for (int i = 0, n = method.Contract.Ensures.Count; i < n; i++) { EnsuresExceptional ee = method.Contract.Ensures[i] as EnsuresExceptional; if (ee == null || ee.Inherited) continue; aes.Add(ee.Type); } } TypeNodeList saveAllowedExceptions = this.allowedExceptions; this.allowedExceptions = aes; // don't check method body of proxy methods. Method result = (method is ProxyMethod) ? method : base.VisitMethod(method); this.allowedExceptions = saveAllowedExceptions; if (this.yieldNode != null && TypeNode.StripModifiers(method.ReturnType) is Interface) { StatementList statements = new StatementList(1); TypeNode elementType = SystemTypes.Object; Interface stype = (Interface)TypeNode.StripModifiers(method.ReturnType); if (stype.TemplateArguments != null && stype.TemplateArguments.Count == 1) elementType = stype.TemplateArguments[0]; Class state = scope.ClosureClass; elementType = scope.FixTypeReference(elementType); state.Flags |= TypeFlags.Abstract; //So that no complaints are given about missing methods added by Normalizer state.Interfaces = new InterfaceList(5); state.Interfaces.Add(SystemTypes.IEnumerable); state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerator.GetTemplateInstance(this.currentType, elementType)); state.Interfaces.Add(SystemTypes.IEnumerator); state.Interfaces.Add(SystemTypes.IDisposable); state.Interfaces.Add((Interface)SystemTypes.GenericIEnumerable.GetTemplateInstance(this.currentType, elementType)); //Add these methods so that Normalizer can find them even when reference to iterator is forward Method moveNext = new Method(state, null, StandardIds.MoveNext, null, SystemTypes.Boolean, null); moveNext.CallingConvention = CallingConventionFlags.HasThis; moveNext.Flags = MethodFlags.Public|MethodFlags.Virtual; moveNext.Body = new Block(new StatementList()); state.Members.Add(moveNext); Method getCurrent = new Method(state, null, StandardIds.getCurrent, null, elementType, null); getCurrent.CallingConvention = CallingConventionFlags.HasThis; getCurrent.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.SpecialName; getCurrent.Body = new Block(new StatementList()); state.Members.Add(getCurrent); Return ret = new Return(new ConstructIterator(state, method.Body, elementType, state)); if (method.Name.SourceContext.Document != null) { ret.SourceContext = method.SourceContext; ret.SourceContext.EndPos = method.Name.SourceContext.EndPos; Debug.Assert(ret.SourceContext.EndPos >= ret.SourceContext.StartPos); } statements.Add(ret); method.Body = new Block(statements); method.Body.Scope = new BlockScope(scope, method.Body); } if (method.IsStatic && method.IsVirtual && !method.IsSpecialName) { method.Flags &= ~MethodFlags.Static; this.HandleError(method.Name, Error.StaticNotVirtual, this.GetMethodSignature(method)); } if (!method.OverridesBaseClassMember) { if (method.NodeType == NodeType.InstanceInitializer || !method.IsSpecialName) { if (!(method.DeclaringType is Interface) && !(method.DeclaringType is DelegateNode)) { if (this.IsLessAccessible(method.ReturnType, method)) { this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanMethod, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method)); this.HandleRelatedError(method.ReturnType); } this.CheckParameterTypeAccessibility(method.Parameters, method); } } else { if (method.Name != null && Checker.OperatorName[method.Name.UniqueIdKey] != null) { if (this.IsLessAccessible(method.ReturnType, method)) { this.HandleError(method.Name, Error.ReturnTypeLessAccessibleThanOperator, this.GetTypeName(method.ReturnType), this.GetMethodSignature(method)); this.HandleRelatedError(method.ReturnType); } this.CheckParameterTypeAccessibility(method.Parameters, method); } } } if (!method.IsSpecialName) { TypeNodeList implementedTypes = method.ImplementedTypes; if (implementedTypes != null) { InterfaceList declaringTypeInterfaces = this.GetTypeView(method.DeclaringType).Interfaces; for (int i = 0, n = implementedTypes.Count; i < n; i++) { Interface iface = implementedTypes[i] as Interface; if (iface == null) continue; if (!this.IsAllowedAsImplementedType(declaringTypeInterfaces, iface)) { Node offendingNode = method.ImplementedTypeExpressions[i]; this.HandleError(offendingNode, Error.ContainingTypeDoesNotImplement, this.GetMethodSignature(method), this.GetTypeName(iface)); this.HandleRelatedError(iface); implementedTypes = null; break; } } } MethodList implementedMethods = method.ImplementedInterfaceMethods; for (int i = 0, n = implementedTypes == null ? 0 : implementedTypes.Count; i < n; i++) { Interface iface = implementedTypes[i] as Interface; if (iface == null) continue; Method m = implementedMethods == null ? null : implementedMethods[i]; if (m == null) { this.HandleError(method.Name, Error.InterfaceMemberNotFound, this.GetMemberSignature(method), this.GetTypeName(iface)); this.HandleRelatedError(iface); } else if (m.IsSpecialName) this.HandleError(method.Name, Error.CannotExplicitlyImplementAccessor, this.GetMethodSignature(method), this.GetMethodSignature(m)); } } if ((method.Flags & MethodFlags.PInvokeImpl) != 0) { Error e = Error.None; if (this.shadowedAssembly != null) { // Make sure this method has a counterpart in the shadowed method TypeNode type = this.GetCorrespondingShadowedTypeNode(method.DeclaringType); if (type == null) { this.HandleError(method.DeclaringType, Error.TypeMissingInShadowedAssembly, this.GetTypeName(method.DeclaringType)); } else { int numParams = method.Parameters == null ? 0 : method.Parameters.Count; TypeNode[] types = new TypeNode[numParams]; for (int i = 0; i < numParams; i++) { types[i] = this.GetCorrespondingShadowedTypeNode(TypeNode.StripModifiers(method.Parameters[i].Type)); } if (this.GetTypeView(type).GetMethod(method.Name, types) == null) { this.HandleError(method, Error.MethodMissingInShadowedAssembly, this.GetMethodSignature(method)); } } } else if (this.isCompilingAContractAssembly) e = Error.None; else if (method.Body != null) e = Error.PInvokeHasBody; else if (method.IsAbstract) e = Error.AbstractAndExtern; else if (method.PInvokeImportName == null || method.PInvokeModule == null) { if (method.Attributes == null || method.Attributes.Count == 0) e = Error.PInvokeWithoutModuleOrImportName; else method.Flags &= ~MethodFlags.PInvokeImpl; } if (e != Error.None) this.HandleError(method.Name, e, this.GetMethodSignature(method)); } if (method.IsPropertySetter && (method.IsPure || method.IsConfined || method.IsStateIndependent)) { this.HandleError(method, Error.MemberCannotBeAnnotatedAsPure, this.GetMethodSignature(method)); } this.currentFinallyClause = savedCurrentFinallyClause; this.currentMethod = savedCurrentMethod; this.returnNode = savedReturnNode; this.yieldNode = savedYieldNode; return result; }
public override Statement VisitAssumption(Assumption assumption){ bool savedInsideAssertion = this.insideAssertion; this.insideAssertion = true; try{ return base.VisitAssumption(assumption); }finally{ this.insideAssertion = savedInsideAssertion; } }
public virtual void VisitAssumption(Assumption assumption) { if (assumption == null) return; this.VisitExpression(assumption.Condition); }
public void TestToString() { string representation = "!(A->B|C&D)"; Formula f = Formula.Parse(representation); Assert.IsTrue(f.ToString() == representation); representation = "(A->B)->(A->B&C)->D|F"; f = Formula.Parse(representation); Assert.IsTrue(f.ToString() == representation); f = new Assumption(new List<string> {"A", "B&C"}.Select(Formula.Parse).ToList(), Formula.Parse("A->B&C")); Assert.IsTrue(f.ToString() == "A, B&C|-A->B&C"); }
public virtual Statement VisitAssumption(Assumption assumption){ if (assumption == null) return null; assumption.Condition = this.VisitExpression(assumption.Condition); return assumption; }
public override Statement VisitAssumption(Assumption Assumption) { if (Assumption == null) return null; return base.VisitAssumption((Assumption)Assumption.Clone()); }