/// <summary> /// Executes the filter action asynchronously. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="cancellationToken">The cancellation token assigned for this task.</param> /// <param name="continuation">The delegate function to continue after the action method is invoked.</param> /// <returns> /// The newly created task for this operation. /// </returns> public Task <HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation) { // Get web context string entryPoint = "Failed"; try { entryPoint = actionContext.ControllerContext.Controller.GetType( ).Name + "." + actionContext.ActionDescriptor.ActionName; } catch { } using (DatabaseContextInfo.SetContextInfo($"WebApi - {actionContext.ControllerContext.ControllerDescriptor.ControllerName}.{actionContext.ActionDescriptor.ActionName}")) using (EntryPointContext.SetEntryPoint(entryPoint)) { ProcessMonitorWriter.Instance.Write(entryPoint); RequestContext requestContext = RequestContext.GetContext( ); if (requestContext != null && requestContext.IsValid) { // Attach timezone string tz = HttpContext.Current.Request.Headers.Get("Tz"); if (!string.IsNullOrEmpty(tz)) { // Set the timezone in the logical context var contextData = new RequestContextData(requestContext.Identity, requestContext.Tenant, requestContext.Culture, tz); RequestContext.SetContext(contextData); } } // Do the actual API call work return(continuation( )); } }
/// <summary> /// Setups the specified context. /// </summary> /// <param name="context">The context.</param> void IDataTarget.Setup(IProcessingContext context) { context?.WriteInfo("Initializing..."); long userId; RequestContext.TryGetUserId(out userId); using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = CommandText.TenantRepairTargetSetupCommandText; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); command.CommandText = @" IF ( @context IS NOT NULL ) BEGIN DECLARE @contextInfo VARBINARY(128) = CONVERT( VARBINARY(128), @context ) SET CONTEXT_INFO @contextInfo END"; command.AddParameter("@context", DbType.AnsiString, DatabaseContextInfo.GetMessageChain(userId), 128); command.ExecuteNonQuery( ); } }
/// <summary> /// Entry point to the thread running background workflows. Used by monitoring software. /// </summary> /// <param name="o"> /// The <see cref="Action"/> to run. This cannot be null. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="o"/> cannot be null and must be an <see cref="Action"/>. /// </exception> private static void StartThread(object o) { using (EntryPointContext.SetEntryPoint("WorkflowThread")) { ProcessMonitorWriter.Instance.Write("WorkflowThread"); try { Action action; action = o as Action; if (action == null) { throw new ArgumentException("Null or not an Action", "o"); } using (DeferredChannelMessageContext deferredMsgContext = new DeferredChannelMessageContext()) using (DatabaseContext.GetContext()) { action(); } } catch (Exception ex) { EventLog.Application.WriteError("WorkflowRunContext.StartThread: Unexpected exception thrown: {0}", ex); } } }
/// <summary> /// Tears down this instance. /// </summary> void IDataSource.TearDown(IProcessingContext context) { using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = @"DROP TABLE #candidateList DROP TABLE #dependents"; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); } }
/// <summary> /// Sets up this instance. /// </summary> void IDataSource.Setup(IProcessingContext context) { using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = @"CREATE TABLE #candidateList ( UpgradeId UNIQUEIDENTIFIER PRIMARY KEY, [Explicit] BIT ) CREATE TABLE #dependents ( Id BIGINT PRIMARY KEY )"; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); } }
/// <summary> /// Creates a structured query expression. /// </summary> /// <remarks> /// This method does not add the new expression to the target structured query, however it will add new tree nodes to the structured query as they are requred. /// </remarks> public ScalarExpression CreateQueryEngineExpression(IExpression expression, QueryBuilderSettings settings) { if (expression == null) { throw new ArgumentNullException("expression"); } Expression expressionToCreate = expression as Expression; if (expressionToCreate == null) { throw new ArgumentException("Expected instance of type Expression.", "expression"); } using (EntryPointContext.AppendEntryPoint("ExprQuery")) using (new SecurityBypassContext( )) using (Profiler.Measure("ExpressionEngine.CreateQueryEngineExpression")) { if (settings == null) { settings = new QueryBuilderSettings(); } var queryContext = new QueryBuilderContext { Settings = settings }; // Add nodes to the query tree, if necessary. expressionToCreate.ListRoot.BuildQueryNode(queryContext, true); // Build up the expression itself ScalarExpression result = expressionToCreate.Root.BuildQuery(queryContext); // Special handing for bools //if (expressionToCreate.ResultType.Type == DataType.Bool) //{ // if (settings.ConvertBoolsToString) // result = CastFromBool.CastToString(result); //} // Set result type // TODO: return entity type // TODO: return for any expression type var calcExpression = result as CalculationExpression; if (calcExpression != null) { calcExpression.DisplayType = ExprTypeHelper.ToDatabaseType(expressionToCreate.ResultType); } return(result); } }
/// <summary> /// Tears down. /// </summary> /// <param name="context">The context.</param> void IDataTarget.TearDown(IProcessingContext context) { context?.WriteInfo("Finalizing..."); using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = CommandText.TenantRepairTargetTearDownCommandText; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); } }
/// <summary> /// Convert a string into an expression tree and perform static evaluation. /// </summary> /// <param name="script">The script to parse.</param> /// <param name="settings">Additional settings that control parsing. In particular, contains the type of the root context object, if any.</param> /// <returns>An expression tree.</returns> public IExpression Compile(string script, BuilderSettings settings) { using (EntryPointContext.AppendEntryPoint("ExprCompile")) using (new SecurityBypassContext( )) using (Profiler.Measure("ExpressionEngine.Compile")) { // Parse the expression ParseTree parseTree = ExpressionGrammar.ParseMacro(script); ParseTreeNode parseRoot = parseTree.Root; // Compile the parse tree IExpression result = CompileParseTreeNode(parseRoot, settings); return(result); } }
/// <summary> /// Setups the specified context. /// </summary> /// <param name="context">The context.</param> void IDataTarget.Setup(IProcessingContext context) { if (context != null) { context.WriteInfo("Initializing..."); } using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = CommandText.TenantMergeTargetSetupCommandText; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); } }
/// <summary> /// Log the access control check before passing it to <see cref="Checker"/>. /// </summary> /// <param name="entities"> /// The entities to check. This cannot be null or contain null. /// </param> /// <param name="permissions"> /// The permissions or operations to check. This cannot be null or contain null. /// </param> /// <param name="user"> /// The user requesting access. This cannot be null. /// </param> /// <returns> /// A mapping of each entity ID to whether the user has access (true) or not (false). /// </returns> /// <exception cref="ArgumentNullException"> /// No argument can be null. /// </exception> /// <exception cref="ArgumentException"> /// Neither <paramref name="entities"/> nor <paramref name="permissions"/> can contain null. /// </exception> public IDictionary <long, bool> CheckAccess(IList <EntityRef> entities, IList <EntityRef> permissions, EntityRef user) { if (entities == null) { throw new ArgumentNullException("entities"); } if (permissions == null) { throw new ArgumentNullException("permissions"); } if (user == null) { throw new ArgumentNullException("user"); } IDictionary <long, bool> result; Stopwatch stopwatch = null; using (EntryPointContext.AppendEntryPoint("AccessControl")) { try { stopwatch = Stopwatch.StartNew( ); result = Checker.CheckAccess(entities, permissions, user); } finally { if (stopwatch != null) { stopwatch.Stop( ); } } } if (!EntityAccessControlChecker.SkipCheck(user)) { Dictionary <long, bool> cacheResult = null; var cachingResult = result as ICachingEntityAccessControlCheckerResult; if (cachingResult != null) { cacheResult = cachingResult.CacheResult; } Trace.TraceCheckAccess(result, permissions, user, cacheResult, stopwatch.ElapsedMilliseconds); } return(result); }
/// <summary> /// Wrap an action so it can be run in a separate thread. /// </summary> protected Action WrapActionForThread(Action act) { var originalRunContext = WorkflowRunContext.Current; return(() => { using (EntryPointContext.AppendEntryPoint("WorkflowTrigger")) using (new WorkflowRunContext { TriggerDepth = originalRunContext.TriggerDepth, RunTriggersInCurrentThread = true }) // Note that the context is coppied across from the original thread in the WorkflowRunContext DefaultQueueTask { EventLog.Application.WriteTrace("Starting workflow thread at depth {0}", originalRunContext.TriggerDepth); act(); } }); }
/// <summary> /// Setups the specified context. /// </summary> /// <param name="context">The context.</param> void IDataTarget.Setup(IProcessingContext context) { if (context != null) { context.WriteInfo("Initializing..."); } using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = "CREATE TABLE #Binary ( OldDataHash NVARCHAR(MAX) COLLATE Latin1_General_CI_AI NULL, NewDataHash NVARCHAR(MAX) COLLATE Latin1_General_CI_AI NULL, FileExtension NVARCHAR(20) COLLATE Latin1_General_CI_AI NULL )"; command.CommandType = CommandType.Text; command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE #Document ( OldDataHash NVARCHAR(MAX) COLLATE Latin1_General_CI_AI NULL, NewDataHash NVARCHAR(MAX) COLLATE Latin1_General_CI_AI NULL, FileExtension NVARCHAR(20) COLLATE Latin1_General_CI_AI NULL )"; command.CommandType = CommandType.Text; command.ExecuteNonQuery(); } }
/// <summary> /// Tears down. /// </summary> /// <param name="context">The context.</param> void IDataTarget.TearDown(IProcessingContext context) { if (context != null) { context.WriteInfo("Finalizing..."); } using (EntryPointContext.UnsafeToIncludeEntryPoint( )) using (IDbCommand command = CreateCommand( )) { command.CommandText = "DROP TABLE #Binary"; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); command.CommandText = "DROP TABLE #Document"; command.CommandType = CommandType.Text; command.ExecuteNonQuery( ); } }
private void ProcessTask(BackgroundTask task) { HandleTask(task, handler => { using (EntryPointContext.SetEntryPoint("BackgroundTask")) { ProcessMonitorWriter.Instance.Write("BackgroundTask"); using (DeferredChannelMessageContext deferredMsgContext = new DeferredChannelMessageContext()) { var contextData = task.Context; using (CustomContext.SetContext(contextData)) { handler.HandleTask(task); } } } }); }
/// <summary> /// Is there an access rule for the specified type(s) that includes the requested permission? E.g. create. /// </summary> /// <param name="entityTypes">The <see cref="EntityType"/>s to check. This cannot be null or contain null.</param> /// <param name="permission">The permission being sought.</param> /// <param name="user"> The user requesting access. This cannot be null. </param> /// <returns> /// A mapping the entity type ID to whether the user can create instances of that /// type (true) or not (false). /// </returns> public IDictionary <long, bool> CheckTypeAccess(IList <EntityType> entityTypes, EntityRef permission, EntityRef user) { if (entityTypes == null) { throw new ArgumentNullException(nameof(entityTypes)); } if (permission == null) { throw new ArgumentNullException(nameof(permission)); } if (user == null) { throw new ArgumentNullException(nameof(user)); } IDictionary <long, bool> result; Stopwatch stopwatch = null; using (EntryPointContext.AppendEntryPoint("AccessControl")) { try { stopwatch = Stopwatch.StartNew( ); result = Checker.CheckTypeAccess(entityTypes, permission, user); } finally { stopwatch?.Stop( ); } } if (!EntityAccessControlChecker.SkipCheck(user)) { Trace.TraceCheckTypeAccess( result, permission, user, entityTypes.Select(et => new EntityRef(et)).ToList(), stopwatch.ElapsedMilliseconds); } return(result); }
/// <summary> /// Evaluates an expression tree. /// </summary> /// <param name="expression">The expression tree.</param> /// <param name="settings">Additional settings to be used in evaluation, such as the root context object, timezone info, etc.</param> /// <returns>The result of the evaluation.</returns> public ExpressionRunResult Run(IExpression expression, EvaluationSettings settings) { if (expression == null) { throw new ArgumentNullException("expression"); } if (settings == null) { throw new ArgumentNullException("settings"); } Expression expressionToRun = expression as Expression; if (expressionToRun == null) { throw new ArgumentException("Expected instance of type Expression.", "expression"); } if (expressionToRun.Root == null) { throw new ArgumentException("expression.Root"); } using (EntryPointContext.AppendEntryPoint("ExprRun")) using (Profiler.Measure("ExpressionEngine.Run")) { var evalContext = new EvaluationContext { Settings = settings, }; object result = expressionToRun.Evaluate(evalContext); var resultList = result as IEnumerable <IEntity>; if (resultList != null) { result = resultList.ToList( ); } ExpressionRunResult runResult = new ExpressionRunResult(result); return(runResult); } }
/// <summary> /// Gets the solution dependencies. /// </summary> /// <param name="context">The context.</param> /// <param name="solution">The solution.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">No active database connection.</exception> private IList <SolutionDependency> GetSolutionDependencies(IProcessingContext context, Solution solution) { IList <SolutionDependency> solutionDependencies = new List <SolutionDependency>( ); using (EntryPointContext.UnsafeToIncludeEntryPoint( )) { IList <ApplicationDependency> applicationDependencies = solution.GetDependencies(true); if (applicationDependencies != null && applicationDependencies.Count > 0) { foreach (ApplicationDependency applicationDependency in applicationDependencies) { solutionDependencies.Add(new SolutionDependency(applicationDependency)); } } if (context != null) { context.Report.SolutionDependencies = solutionDependencies; } } return(solutionDependencies); }
/// <summary> /// Run various queries to pre-fill the entity cache for the current tenant. /// </summary> public static void TenantWarmup( ) { using (new DeferredChannelMessageContext()) using (EntryPointContext.SetEntryPoint("Warmup TenantId=" + RequestContext.TenantId)) using (Profiler.Measure("BulkPreloader.TenantWarmup TenantId=" + RequestContext.TenantId)) { ProcessMonitorWriter.Instance.Write("Warmup TenantId=" + RequestContext.TenantId); _tenantWarmupRunning = true; try { CacheRelationships( ); // Fetch all aliases in the tenant EntityIdentificationCache.PreloadAliases( ); // Prewarm type hierarchy PerTenantEntityTypeCache.Instance.Prewarm( ); // Includes relationships, as they inherit type. const string typePreloaderQuery = "alias, name, isOfType.{id, isMetadata}, inherits.id, {k:defaultEditForm, defaultPickerReport, defaultDisplayReport}.isOfType.id, allowEveryoneRead, isAbstract, relationships.{id, isOfType.id}, reverseRelationships.{id, isOfType.id}, instanceFlags.id"; Preload(new EntityRequest("type", typePreloaderQuery, QueryType.Instances, "Preload types")); const string derivedTypePreloaderQuery = "derivedTypes.id"; Preload(new EntityRequest("type", derivedTypePreloaderQuery, QueryType.Instances, "Preload types")); // Includes enum definitions const string relationshipPreloaderQuery = "reverseAlias, cardinality.id, fromType.id, toType.id, fromName, toName, securesTo, securesFrom, securesToReadOnly, securesFromReadOnly, flags.id, relationshipInKey.id"; Preload(new EntityRequest("relationship", relationshipPreloaderQuery, QueryType.Instances, "Preload relationships")); const string resourceKeyPreloaderQuery = "resourceKeyRelationships.id, keyFields.id"; Preload(new EntityRequest("resourceKey", resourceKeyPreloaderQuery, QueryType.ExactInstances, "Preload resourcekeys")); const string fieldTypesPreloaderQuery = "alias, isOfType.id, dbFieldTable, dbType, dbTypeFull, readiNowType, { k:renderingControl, k:defaultRenderingControls }.{ isOfType.id, k:context.isOfType.id }"; Preload(new EntityRequest("fieldType", fieldTypesPreloaderQuery, QueryType.ExactInstances, "Preload field types")); const string fieldPreloaderQuery = @"alias, name, isOfType.id, description, isFieldReadOnly, defaultValue, isRequired, isFieldWriteOnly, allowMultiLines, pattern.{isOfType.id, regex, regexDescription},{flags, fieldRepresents}.{ isOfType.id, alias }, minLength, maxLength, minInt, maxInt, minDecimal, maxDecimal, minDate, maxDate, minTime, maxTime, minDateTime, maxDateTime, decimalPlaces, autoNumberDisplayPattern, isCalculatedField, fieldCalculation"; Preload(new EntityRequest("field", fieldPreloaderQuery, QueryType.Instances, "Preload field definitions")); const string tenantSettingsPreloaderQuery = "alias, isOfType.id, finYearStartMonth.isOfType.id"; Preload(new EntityRequest("tenantGeneralSettings", tenantSettingsPreloaderQuery, QueryType.ExactInstances, "Preload tenant settings")); const string enumValuesPreloaderQuery = "alias, name, enumOrder, isOfType.instancesOfType.id"; Preload(new EntityRequest("enumValue", enumValuesPreloaderQuery, QueryType.Instances, "Preload enum values")); const string accessRulesPreloaderQuery = "alias, isOfType.id, allowAccess.{ isOfType.id, accessRuleReport.isOfType.id, controlAccess.isOfType.id, permissionAccess.isOfType.id, accessRuleEnabled, accessRuleHidden, accessRuleIgnoreForReports }"; Preload(new EntityRequest("subject", accessRulesPreloaderQuery, QueryType.Instances, "Preload access rules")); const string userPreloaderQuery = "alias, name, isOfType.id, userHasRole.{id, isOfType.id}"; Preload(new EntityRequest("userAccount", userPreloaderQuery, QueryType.Instances, "Preload users")); const string rolesPreloaderQuery = "alias, name, isOfType.id, includesRoles.{id, isOfType.id}, includedByRoles.{id, isOfType.id}, roleMembers.{id, isOfType.id}"; Preload(new EntityRequest("role", rolesPreloaderQuery, QueryType.Instances, "Preload roles")); // edit form controls const string controlsTypePreloaderQueryCommon = @" name, alias, isOfType.id, instancesOfType.{ name, k:requiresContext, k:isHiddenFromFormDesigner, k:designControl, k:control, k:viewControl, k:context.{alias, isOfType.id} }"; const string controlsTypePreloaderQuery = controlsTypePreloaderQueryCommon + @", instancesOfType.{ k:wbcHideSuccessConfirmation, { k:wbcWorkflowToRun, k:wbcResourceInputParameter, k:wbcDisableControlBasedOnRelationshipControl, k:wbcDisableControlBasedOnResources, k:reportToRender, k:chartToRender, k:formToRender }.{alias, isOfType.id} }"; Preload(new EntityRequest("k:renderControlType", controlsTypePreloaderQuery, QueryType.Instances, "Preload editForm controls")); const string fieldControlsTypePreloaderQuery = controlsTypePreloaderQueryCommon + @", instancesOfType.{ {k:fieldTypeToRender, k:defaultFieldTypesToRender, k:fieldInstanceToRender}.{alias, isOfType.id}, k:textControlWidth, k:textControlHeight }"; Preload(new EntityRequest("k:fieldRenderControlType", fieldControlsTypePreloaderQuery, QueryType.Instances, "Preload editForm field controls")); const string relControlsTypePreloaderQuery = controlsTypePreloaderQueryCommon + @", instancesOfType.{ {k:thumbnailScalingSetting, k:thumbnailSizeSetting}.{alias, id} }"; Preload(new EntityRequest("k:relationshipRenderControlType", relControlsTypePreloaderQuery, QueryType.Instances, "Preload editForm rel controls")); Preload(new EntityRequest("k:structureRenderControlType", controlsTypePreloaderQuery, QueryType.Instances, "Preload editForm struct controls")); PrecompileEntityQuery(ReportHelpers.ReportPreloaderQuery, "Precompile report query"); PrecompileEntityQuery(ReportHelpers.QueryPreloaderQuery, "Precompile report-query query"); PrecompileEntityQuery(ActionServiceHelpers.ReportRequest, "Precompile report actions query"); PrecompileEntityQuery(ActionServiceHelpers.ResourceRequest, "Precompile resource actions query"); PrecompileEntityQuery(ActionServiceHelpers.ResourceViewerRequest, "Precompile resource viewer actions query"); PrecompileEntityQuery(ActionServiceHelpers.WorkflowRequest, "Precompile workflow actions query"); PrecompileEntityQuery(CustomEditFormHelper.GetHtmlFormQuery( ), "Precompile form view query"); PrecompileEntityQuery(CustomEditFormHelper.GetHtmlFormQuery(true), "Precompile form design query"); PrecompileEntityQuery(DefaultLayoutGenerator.FormGenerationPreloaderQuery, "Precompile default form generator query"); Factory.ExpressionCompiler.Prewarm( ); TimeZoneHelper.Prewarm( ); PreloadAccessRuleReports( ); _tenantWarmupDone = true; } finally { _tenantWarmupRunning = false; } } }
public override int GetHashCode() { return(EntryPointContext.GetHashCode() + TargetName.GetHashCode()); }