public string GetDynamicHtmlInjection(AppInfo app, SessionInfo session, string locale, string data) { int userId = (session != null ? session.UserId : 0); ObjectKey userProviderEspaceKey = (HttpContext.Current != null ? app.UserProviderEspaceKeyAsKey : null); if (userId == BuiltInFunction.NullIdentifier()) { return(string.Empty); } InboxQueries.PaginationInfo?inboxActivityCount; using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { // Check if the User Providers are shared between the Inbox and the current eSpace if (inboxUserProviderEspaceKey == null) { inboxUserProviderEspaceKey = ObjectKey.Parse(DBRuntimePlatform.Instance.GetUserProviderKey(trans, Constants.EPATaskboxESpaceKey)); } if (userProviderEspaceKey != inboxUserProviderEspaceKey) { return(string.Empty); } inboxActivityCount = InboxQueries.GetActivityCount(trans, userId); } if (!inboxActivityCount.HasValue) { throw new DataBaseException("No activity data found for userId = " + userId); } return("<script type='text/javascript'> EPATaskbox.instance = new EPATaskbox(outsystems.internal.$('.EPATaskbox_Container'), " + userId + ", " + inboxActivityCount.Value.Total + ", " + (inboxActivityCount.Value.Unseen > 0 ? "true" : "false") + ", null); </script>"); }
private bool ExecuteActivityWebService(HeContext heContext, string ssKey, int activityId, int processId, int tenantId, int userId, string locale, Action <IProcessActivity> activityMethod) { ValidateToken(heContext, userId, tenantId, heContext.AppInfo.eSpaceUID); ObjectKey activityKey = ObjectKey.Parse(ssKey); IProcessActivity execObj = null; if (AbstractProcessActivity.GetProcessActivityImplementation(processId, activityId, activityKey, true, out execObj)) { SetContextInfo(heContext, tenantId, userId, locale); heContext.AppInfo.CheckIsApplicationEnabled(); try { heContext.AllowTenantSwitch = false; activityMethod(execObj); } finally { heContext.AllowTenantSwitch = true; } return(true); } else { ErrorLog.StaticWrite(DateTime.Now, heContext.Session.SessionID, Global.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, "Activity '" + ssKey + "' isn't mapped to an object at Runtime", (new System.Diagnostics.StackTrace(true)).ToString(), ""); return(false); } }
public void SaveUnsetProcessOutputs(HeContext heContext) { using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { int tenantId = heContext.AppInfo.Tenant.Id; List <IActivityVariable> defaultOutputs = new List <IActivityVariable>(); using (IDataReader reader = DBRuntimePlatform.Instance.GetUnsetProcessOutputs(trans, ProcessId)) { while (reader.Read()) { string sskey = (string)reader["SS_KEY"]; IActivityVariable outputDef; if (AllProcessOutputsDefinitions.TryGetValue(ObjectKey.Parse(sskey), out outputDef)) { defaultOutputs.Add(outputDef); } } } foreach (IActivityVariable output in defaultOutputs) { DBRuntimePlatform.Instance.AddProcessOutput(trans, ProcessId, tenantId, output); } } }
protected void Application_Start(Object sender, EventArgs e) { try { Application["ApplicationStartError"] = null; Application["EspaceName"] = "ContactManager"; // Workaround: Force first access to HeContext to correctly save CurrentCulture var firstAccess = HeContext.UnknownEntryPoint; // Set default date/time format FormatInfo.SetDefaultDateAndDateTimeFormatString("yyyy-M-d", "yyyy-MM-dd"); // Set decimal and group separator FormatInfo.SetInputDecimalSeparator("."); FormatInfo.SetInputGroupSeparator(""); ESpaceInfoForAppStart eSpaceInfo = new ESpaceInfoForAppStart(); // Check the eSpaceName from the begining of the path eSpaceInfo.ESpaceName = (string)Application["EspaceName"]; eSpaceInfo.ESpaceId = eSpaceId; eSpaceInfo.ESpaceKey = eSpaceKey; eSpaceInfo.IsMultiTenant = false; eSpaceInfo.IsMobileRuntime = false; eSpaceInfo.CacheInvalidationSuffix = (AppUtils.Instance.CacheInvalidationSuffix ?? String.Empty).RemoveIfStartsWith("?"); // User Provider eSpaceInfo.UserProviderName = ""; eSpaceInfo.UserProviderKey = ObjectKey.Parse(""); // Module Version eSpaceInfo.ESpaceVersionId = RuntimePlatformSettings.Module.VersionId.GetValue(); eSpaceInfo.ESpaceJQueryVersion = JQueryVersion.JQuery142; eSpaceInfo.GetStaticEntities = () => GetStaticEntities(new HashSet <GlobalObjectKey>(), new HashSet <ObjectKey>()); // Catalog var catalogName = RuntimePlatformSettings.Catalog.ForModule(ObjectKeyUtils.DatabaseValue(eSpaceKey)).Catalog.GetValue(); eSpaceInfo.CatalogName = catalogName; eSpaceInfo.DataBaseConfigurationDetails = RuntimePlatformSettings.Catalog.Configuration(catalogName).All; AppInfo App = new AppInfo(eSpaceInfo); if (!forTestAction) { App.SetupInvalidateCallbackCache(); } OutSystems.HubEdition.WebWidgets.OSPage.ValidationMessagesInstance = new ValidationMessages(); OutSystems.HubEdition.WebWidgets.OSUserControl.ValidationMessagesInstance = new ValidationMessages(); System.Net.ServicePointManager.Expect100Continue = RuntimePlatformSettings.Misc.RuntimeExpect100Continue.GetValue(); LifecyleListenerManager.RegisterListener("OutSystems.RESTService.ServiceConfiguration", new System.Reflection.AssemblyName("OutSystems.RESTService.Runtime")); LifecyleListenerManager.OnApplicationStart(); } catch (Exception excep) { Application["ApplicationStartError"] = excep; AppInfo.SetAppInfo(HttpContext.Current, null); ErrorLog.LogApplicationError(excep, /*context*/ null, "Global"); } }
protected virtual string GetRequestInfoJavaScript(string webScreenKey, string webScreenName) { var info = AppInfo.GetAppInfo(); using (var writer = new StringWriter()) { writer.Write(" <script id=\"_OSrequestInfoScript\" type=\"text/javascript\">(function(global) { "); writer.Write("global.outsystems = global.outsystems || {};"); writer.Write("global.outsystems.internal = global.outsystems.internal || {};"); if (Settings.GetBool(Settings.Configs.JavascriptAPI_ShowHiddenFields)) { writer.Write("global.outsystems.internal.showHiddenFields = true;"); } writer.Write("global.outsystems.internal.requestInfo = {"); // #564602 OSVisit and OSVisitor cookies allow HTML injection -check if cookies' value was modified writer.Write("visitorKey:'{0}',", GuidUtils.IsGuid(info.VisitorId) ? info.VisitorId : ""); writer.Write("visitKey:'{0}',", GuidUtils.IsGuid(info.VisitId) ? info.VisitId : ""); writer.Write("sessionKey:'{0}',", info.OsContext.Session.SessionIDHash); writer.Write("userKey:'{0}',", info.OsContext.Session.UserIdGuid); var perfTracer = info.OsContext.RequestTracer; bool perfTracerExists = perfTracer != null; writer.Write("requestKey:'{0}',", (perfTracerExists) ? perfTracer.RequestKey : ""); writer.Write("webScreenKey:'{0}',", ObjectKeyUtils.DatabaseValue(ObjectKey.Parse(webScreenKey))); writer.Write("webScreenName:'{0}',", webScreenName); writer.Write("espaceKey:'{0}',", (perfTracerExists) ? perfTracer.ModuleKey : info.eSpaceUID); writer.Write("espaceName:'{0}',", (perfTracerExists) ? perfTracer.ModuleName : info.eSpaceName); writer.Write("applicationKey:'{0}',", (perfTracerExists) ? perfTracer.ApplicationKey : info.ApplicationUID); writer.Write("applicationName:'{0}',", (perfTracerExists) ? perfTracer.ApplicationName : info.ApplicationName); writer.Write("tenantKey:'{0}',", (perfTracerExists) ? perfTracer.TenantKey : info.Tenant.Id_Guid); writer.Write("tenantName:'{0}',", (perfTracerExists) ? perfTracer.TenantName : info.Tenant.Name); writer.Write("environmentKey:'{0}',", (perfTracerExists) ? perfTracer.EnvironmentKey : info.EnvironmentKey); writer.Write("environmentName:'{0}',", (perfTracerExists) ? perfTracer.EnvironmentName : info.EnvironmentName); if (Settings.GetBool(Settings.Configs.JavascriptAPI_ShowHiddenFields)) { writer.Write("username:'******',", info.OsContext.Session.UserName); writer.Write("frontendName:'{0}',", (perfTracerExists) ? perfTracer.FrontEndName : info.FrontendName); } // #664816 - When the host serial on OSSYS_SERVER is different from the one in the windows registry the FrontendName will not be read from the DB. // We do a null check here to prevent this not vital information from stopping the application load. string value = null; if (perfTracerExists) { value = string.IsNullOrEmpty(perfTracer.FrontEndName) ? "" : SecureConfidentialInformationEncryption.EncryptWithAlgorithm(perfTracer.FrontEndName, SecureConfidentialInformationEncryption.FixedKeyAES128.Instance); } else { value = string.IsNullOrEmpty(info.FrontendName) ? "" : SecureConfidentialInformationEncryption.EncryptWithAlgorithm(info.FrontendName, SecureConfidentialInformationEncryption.FixedKeyAES128.Instance); } writer.Write("frontendKey:'{0}'", value); writer.Write("}"); writer.Write("})(this);"); writer.Write("</script>\n"); return(writer.ToString()); } }
// This should be discontinued, so we'll just return false for new databases protected virtual bool TaskboxUsesEnterpriseManagerUserProvider(Transaction trans) { lock (typeof(InboxQueries)) { if (!epaTaskboxHasEMUserProvider.HasValue) { epaTaskboxHasEMUserProvider = ObjectKey.Parse(Instance.GetUserProviderKey(trans, Constants.EPATaskboxESpaceKey)) == Constants.EnterpriseManagerESpaceKey; } return(epaTaskboxHasEMUserProvider.Value); } }
public void Init(string breakpointIdStr) { if (string.IsNullOrEmpty(breakpointIdStr)) { return; } string[] parts = breakpointIdStr.Split(SeparatorChar); eSpaceKey = ObjectKey.Parse(parts[0]); objectKey = ObjectKey.Parse(parts[1]); compoundKeyStr = parts.Length > 2 && !string.IsNullOrEmpty(parts[2]) ? parts[2] : null; debuggerHashStr = parts.Length > 3 && !string.IsNullOrEmpty(parts[3]) ? parts[3] : null; }
private bool ValidateConsumerAndProducerKeys(string consumerKey, string producerKey) { bool consumerKeysAreValid = ObjectKey.Parse(consumerKey) == ConsumerModuleKey; bool producerKeysAreValid = ObjectKey.Parse(producerKey) == ProducerModuleKey; if (!consumerKeysAreValid) { OSTrace.Error($"Consumer Module keys don't match. Expected '{ObjectKeyUtils.DatabaseValue(ConsumerModuleKey)}' but was '{consumerKey}'"); } if (!producerKeysAreValid) { OSTrace.Error($"Producer Module keys don't match. Expected '{ObjectKeyUtils.DatabaseValue(ProducerModuleKey)}' but was '{producerKey}'"); } return(producerKeysAreValid && consumerKeysAreValid); }
/// <summary> /// Read a record from database /// </summary> /// <param name="r"> Data base reader</param> public void Read(IDataReader r) { Object column = null; try { _dataId = IdReader(r); //So conversion is only done once column = r["Name"]; Name = (column != System.DBNull.Value ? (string)column : string.Empty); column = r["SS_Key"]; Key = (column != System.DBNull.Value ? ObjectKey.Parse((string)column) : ObjectKey.Dummy); Valid = true; } catch (Exception excep) { throw new System.InvalidCastException("Could not load the Record Metadata: " + excep.Message); } }
public int ExecuteTimer(string ssKey, int timeout, int tenantId) { ObjectKey timerKey = ObjectKey.Parse(ssKey); if (HttpContext.Current == null) { GeneralLog.StaticWrite(DateTime.Now, "", 0, 0, 0, "ExecuteTimer Called (Context is null)", GeneralLogType.WARNING.ToString(), "", ""); } else { HeContext context = Global.App.OsContext; // Check if the request is from a valid IP if (!NetworkInterfaceUtils.IsLoopbackAddress(HttpContext.Current.Request.UserHostAddress)) { ErrorLog.LogApplicationError("Access to timerhandler with invalid IP: " + HttpContext.Current.Request.UserHostAddress, "The timer handler can only be accessed by the 127.0.0.1 IP", context, "ExecuteTimer"); return(0); } if (tenantId > 0) { context.Session.TenantId = tenantId; } bool processedOk = false; try { if (timerKey == TimerBootstrap.TimerKey) { TimerBootstrap.Execute(context, timeout); } else { GeneralLog.StaticWrite(DateTime.Now, context.Session.SessionID, Global.eSpaceId, context.AppInfo.Tenant.Id, context.Session.UserId, "Timer " + ssKey + " isn't mapped", GeneralLogType.INFO.ToString(), "", ""); } processedOk = true; } finally { DatabaseAccess.FreeupResources(processedOk); } } return(1); }
private bool ExecuteProcessWebService(HeContext heContext, string ssKey, int tenantId, int userId, string locale, Action <IProcess> processMethod) { ObjectKey processKey = ObjectKey.Parse(ssKey); IProcess execObj = null; if (AbstractProcess.GetProcessDefinition(processKey, out execObj)) { SetContextInfo(heContext, tenantId, userId, locale); heContext.AppInfo.CheckIsApplicationEnabled(); processMethod(execObj); return(true); } else { ErrorLog.StaticWrite(DateTime.Now, heContext.Session.SessionID, Global.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, "Process " + ssKey + " isn't mapped to an object at Runtime", (new System.Diagnostics.StackTrace(true)).ToString(), ""); return(false); } }
private IEnumerable <SiteProperty> ReadSitePropertiesFromDatabase() { yield return(new SiteProperty("TenantName", TenantName)); yield return(new SiteProperty("TenantId", TenantId)); // Read the properties from the database using (Transaction tran = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) { using (IDataReader reader = DBRuntimePlatform.Instance.GetSitePropertiesInfo(tran, ESpaceId, TenantId)) { while (reader.Read()) { int defId = reader.SafeGet <int>("Def_Id"); ObjectKey propKey = ObjectKey.Parse(Convert.ToString(reader["SS_Key"])); bool isShared = reader.SafeGet <bool>("Is_Shared"); string datatype = Convert.ToString(reader["Data_Type"]); string databaseValue = reader.SafeGet <string>("Value", ""); string name = Convert.ToString(reader["Name"]); yield return(new SiteProperty(defId, name, propKey, isShared, databaseValue, datatype)); } } } }
public CustomLog(object ssRecord) { if (ssRecord is IRecord) { // Record inspection: // - get structure field from record // - get its EntityRecordDetails attribute // - there must be a single structure in the record (this is an entity record and not a recordjoin) EntityRecordDetails entityDetails = null; if (ssRecord is ISimpleRecord) { entityDetails = ssRecord.GetType().GetCustomAttributes(typeof(EntityRecordDetails), false).FirstOrDefault() as EntityRecordDetails; } else { var entAttr = ssRecord.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance) .Select( field => new { Field = field, EntityDetails = field.FieldType.GetCustomAttributes(typeof(EntityRecordDetails), false).FirstOrDefault() }) .Where(fa => fa.EntityDetails != null) .FirstIfSingleOrDefault(); if (entAttr != null) { entityDetails = (EntityRecordDetails)entAttr.EntityDetails; ssRecord = entAttr.Field.GetValue(ssRecord); } } if (entityDetails != null) { var entityName = entityDetails.Name; var entityGeneration = entityDetails.Generation; var physicalTableName = entityDetails.PhysicalTableName; var dbConnection = entityDetails.DBConnection; var structAttrs = ssRecord.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); // This method uses cache var dbCatalog = DatabaseAccess.ForEspaceDatabase(ObjectKeyUtils.DatabaseValue(ObjectKey.Parse(entityDetails.OwnerKey))).DatabaseServices.DatabaseConfiguration.DatabaseIdentifier; log = new CustomLogDefinition(entityName: entityName, physicalTableName: physicalTableName, dbConnection: dbConnection, entityGeneration: entityGeneration, dbCatalog: dbCatalog); for (int i = 0; i < structAttrs.Length; i++) { var attrs = (Attribute[])structAttrs[i].GetCustomAttributes(typeof(EntityAttributeDetails), false); if (attrs.Length == 1) { EntityAttributeDetails entityAttributeDetails = (EntityAttributeDetails)attrs[0]; if (!entityAttributeDetails.IsAutonumber) { var customLogField = new CustomLogDefinition.CustomLogFieldDefinition(structAttrs[i].GetValue(ssRecord), entityAttributeDetails.IsEntityReference, entityAttributeDetails.IsMandatory); log.Fields.Add(entityAttributeDetails.Name, customLogField); } } } return; } } throw new InvalidCastException("Unable to convert to record"); }
/// <summary> /// Function to dump expression (Key = vlbpl12VY0KA5IIiWBGINw) Expression: /// GetMenuItem(Contacts).MenuItem.Caption /// </summary> /// <returns>Returns the value of the Expression</returns> public string expression_InlineExpression6() { ObjectKey oldCurrentESpaceKey = heContext.CurrentESpaceKey; try { heContext.CurrentESpaceKey = ssContactManager.Global.eSpaceKey; return(Functions.ssGetMenuItem(heContext, ENMenuItemEntity.GetRecordByKey(ObjectKey.Parse("bQMfrwAt5UaQWFeNE2K7bg")).ssId).ssENMenuItem.ssCaption); } finally { heContext.CurrentESpaceKey = oldCurrentESpaceKey; } }
/// <summary> /// Closes a process, all its activities and sets the parent activity (if any) to execute /// </summary> /// <param name="heContext"></param> /// <param name="processDefiniton">Instance of the process to close, can be a dummy instance</param> /// <param name="processId">Id of the process, cannot be dummy</param> /// <param name="recursive"></param> private static void TerminateProcessInstance(HeContext heContext, IProcess processDefiniton, int processId, bool recursive) { using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { int tenantId = heContext.AppInfo.Tenant.Id; int parentActivityId = 0; List <Pair <int, ObjectKey> > nonTerminatedActivities = new List <Pair <int, ObjectKey> >(); ProcessStatus processStatus = ProcessStatus.Unknown; using (IDataReader reader = DBRuntimePlatform.Instance.GetProcessForUpdate(trans, tenantId, processId)) { if (reader.Read()) { parentActivityId = reader.SafeGet <int>("PARENT_ACTIVITY_ID"); processStatus = (ProcessStatus)reader.SafeGet <int>("STATUS_ID"); } else { throw new InvalidOperationException("Could not close process #" + processId + " because the process does not exist."); } } using (IDataReader reader = DBRuntimePlatform.Instance.GetNonTerminatedActivities(trans, tenantId, processId)) { while (reader.Read()) { nonTerminatedActivities.Add(Pair.Create(reader.SafeGet <int>("ID"), ObjectKey.Parse(reader.SafeGet <string>("SS_Key")))); } } foreach (var nonTerminatedActivity in nonTerminatedActivities) { IProcessActivity activityToClose; if (processDefiniton.GetProcessActivityInstance(processId, nonTerminatedActivity.First, nonTerminatedActivity.Second, false, out activityToClose)) { bool success = activityToClose.TerminateActivity(heContext, recursive); if (!success) { throw new InvalidOperationException("Could not terminate activity " + activityToClose.ActivityId); } } } if (processStatus == ProcessStatus.Closed || processStatus == ProcessStatus.Terminated) { return; } if (parentActivityId > 0) { int parentTenantId; DBRuntimePlatform.Instance.GetParentProcessId(trans, parentActivityId, out parentTenantId); DBRuntimePlatform.Instance.UpdateActivity(trans, parentTenantId, parentActivityId, null, null, null, null, null, null, null, ActivityStatus.Closing, null, null, null, null, true, null, null, null, null, null, null); } DBRuntimePlatform.Instance.SetProcessStatus(trans, tenantId, processId, ProcessStatus.Terminated, heContext.Session.UserId); } }
public string cnt_Container7_setInlineAttributes(object sender, System.EventArgs e) { ObjectKey oldCurrentESpaceKey = heContext.CurrentESpaceKey; try { heContext.CurrentESpaceKey = ssContactManager.Global.eSpaceKey; ((WebControl)sender).CssClass = Functions.ActionMenu_GetStyle(heContext, (inParamActiveMenuItemId == ENMenuItemEntity.GetRecordByKey(ObjectKey.Parse("bQMfrwAt5UaQWFeNE2K7bg")).ssId), "Menu_TopMenu Menu_TopMenuActive", "Menu_TopMenu"); if (!cnt_Container7_isVisible()) { string stylevalue = ((IAttributeAccessor)sender).GetAttribute("style"); { string newstyledef; string oldstyledef; newstyledef = stylevalue + ((stylevalue != null && !stylevalue.TrimEnd().EndsWith(";")) ? ";": "") + "display:none"; oldstyledef = ((IAttributeAccessor)sender).GetAttribute("style"); if (oldstyledef != null) { if (!oldstyledef.TrimEnd().EndsWith(";")) { newstyledef = ";" + newstyledef; } if (!oldstyledef.EndsWith(newstyledef)) { ((IAttributeAccessor)sender).SetAttribute("style", oldstyledef + newstyledef.ToString()); } else { ((IAttributeAccessor)sender).SetAttribute("style", oldstyledef.ToString()); } } else { ((IAttributeAccessor)sender).SetAttribute("style", newstyledef.ToString()); } } } else { string stylevalue = ((IAttributeAccessor)sender).GetAttribute("style"); if (stylevalue != null) { ((IAttributeAccessor)sender).SetAttribute("style", stylevalue.Replace("display:none;", "").Replace("display:none", "").ToString()); } } return(""); } finally { heContext.CurrentESpaceKey = oldCurrentESpaceKey; } }
public static int CreateProcessInstance(HeContext heContext, int tenantId, ObjectKey espaceSSKey, ObjectKey processSSKey, int parentActivityId, int parentProcessId, out Pair <int, ObjectKey> startActivity) { int startActivityId; ObjectKey activityDefKey; int newProcessId; using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { int processDefId = 0; int topProcessId = 0; int createdBy = 0; using (IDataReader reader = DBRuntimePlatform.Instance.GetProcessDefinition(trans, processSSKey, espaceSSKey)) { if (reader.Read()) { processDefId = reader.SafeGet <int>("ID"); } else { throw new DataBaseException("No process definition exists with key '" + processSSKey + "'."); } } if (parentActivityId != BuiltInFunction.NullIdentifier()) { int parentTenantId; parentProcessId = DBRuntimePlatform.Instance.GetParentProcessId(trans, parentActivityId, out parentTenantId); } if (parentProcessId != BuiltInFunction.NullIdentifier()) { topProcessId = DBRuntimePlatform.Instance.GetTopProcessId(trans, parentProcessId); } else { // Is not sub-process so we need to set the CreatedBy field createdBy = heContext.Session.UserId; } newProcessId = DBRuntimePlatform.Instance.CreateProcess(trans, tenantId, BuiltInFunction.CurrDateTime(), createdBy, processDefId, parentProcessId, parentActivityId, topProcessId, ProcessStatus.Active); int activityDefId = 0; string activityDefName; using (IDataReader reader = DBRuntimePlatform.Instance.GetActivityDefinitionsForKind(trans, newProcessId, ActivityKind.Start)) { if (reader.Read()) { activityDefId = reader.SafeGet <int>("ID"); activityDefKey = ObjectKey.Parse(reader.SafeGet <string>("SS_KEY")); activityDefName = reader.SafeGet <string>("NAME", string.Empty); } else { throw new DataBaseException("No active " + ActivityKind.Start.ToString() + " activity exists for process #" + newProcessId + "."); } } startActivityId = CreateActivityInstance(heContext, trans, tenantId, activityDefId, newProcessId, activityDefName, 0, null); } startActivity = Pair.Create(startActivityId, activityDefKey); return(newProcessId); }
/// <summary> /// Closes a process, all its activities and sets the parent activity (if any) to execute /// </summary> /// <param name="heContext"></param> /// <param name="processDefiniton">Instance of the process to close, can be a dummy instance</param> /// <param name="processId">Id of the process, cannot be dummy</param> /// <param name="manualTerminate"></param> private static void CloseProcessInstance(HeContext heContext, IProcess processDefiniton, int processId, bool manualTerminate) { using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { int tenantId = heContext.AppInfo.Tenant.Id; List <Pair <int, ObjectKey> > nonTerminatedActivities = new List <Pair <int, ObjectKey> >(); int userId = manualTerminate? heContext.Session.UserId: 0; int parentActivityId = 0; ProcessStatus processStatus = ProcessStatus.Unknown; using (IDataReader reader = DBRuntimePlatform.Instance.GetProcessForUpdate(trans, tenantId, processId)) { if (reader.Read()) { parentActivityId = reader.SafeGet <int>("PARENT_ACTIVITY_ID"); processStatus = (ProcessStatus)reader.SafeGet <int>("STATUS_ID"); } else { throw new InvalidOperationException("Could not close process #" + processId + " because the process does not exist."); } } using (IDataReader reader = DBRuntimePlatform.Instance.GetNonTerminatedActivities(trans, tenantId, processId)) { while (reader.Read()) { nonTerminatedActivities.Add(Pair.Create(reader.SafeGet <int>("ID"), ObjectKey.Parse(reader.SafeGet <string>("SS_Key")))); } } foreach (var nonTerminatedActivity in nonTerminatedActivities) { //Change all the pending activity status WITHOUT any commits InnerSetActivityStatus(heContext, processId, nonTerminatedActivity.First, ActivityStatus.Closed, manualTerminate? heContext.Session.UserId: userId); IProcessActivity activityToClose; if (processDefiniton.GetProcessActivityInstance(processId, nonTerminatedActivity.First, nonTerminatedActivity.Second, false, out activityToClose)) { //We cant call the StartRemoveEventFilters here because that would make an implicit commit ((ProcessBase.AbstractProcessActivityBase)activityToClose).RemoveEventFilters(heContext); } } if (processStatus == ProcessStatus.Closed) { return; } if (parentActivityId > 0) { int parentTenantId; DBRuntimePlatform.Instance.GetParentProcessId(trans, parentActivityId, out parentTenantId); //Change status of parent activity and reschedule it DBRuntimePlatform.Instance.UpdateActivity(trans, parentTenantId, parentActivityId, null, null, null, null, null, null, null, ActivityStatus.Closing, null, null, null, null, true, null, null, null, null, null, null); } DBRuntimePlatform.Instance.SetProcessStatus(trans, tenantId, processId, ProcessStatus.Closed, userId); } }
private void Page_Load(object sender, System.EventArgs e) { // init vars AppInfo appInfo = Global.App; if (appInfo != null) { heContext = appInfo.OsContext; } Response.ContentType = "text/html; charset=" + Response.ContentEncoding.WebName; // No session SessionFixationValidation because screen is accessible by anonymous users or uses a readonly session. if (appInfo != null) { heContext = appInfo.OsContext; heContext.RequestTracer.MainEventType = RequestTracerEventType.WebScreenServerExecuted; heContext.RequestTracer.RegisterEndpoint("2dcd742c-96b7-4e62-ae6f-1644bcab95a5", "InvalidPermissions"); } OutSystems.HubEdition.RuntimePlatform.Web.JavaScriptManager.CheckRelativeJavaScriptPrefix(AppUtils.Instance.getImagePath()); appInfo.IsLoadingScreen = !IsPostBack; if (!IsPostBack) { ArrayList screenParameters = (ArrayList)Global.App.OsContext.Session["ContactManager._ScreenParameters_InvalidPermissions"]; bool screenParametersInSession = false; object screenParametersKey = heContext.Session["_ScreenParametersKey"]; if ((screenParametersKey == null || this.Key.Equals(ObjectKey.Parse(Convert.ToString(screenParametersKey)))) && screenParameters != null) { try { screenParametersInSession = true; } catch (Exception parametersException) { ErrorLog.LogApplicationError("Failed to load Screen Input Parameters from session.", "ScreenParametersKey = " + screenParametersKey + ", Count = " + screenParameters.Count + "\r\n" + parametersException.StackTrace, heContext, "Global"); } finally { Global.App.OsContext.Session["ContactManager._ScreenParameters_InvalidPermissions"] = null; heContext.Session["_ScreenParametersKey"] = null; } } else if (Request.HttpMethod == "GET") { } else if (Request.HttpMethod == "POST") { } } if (!appInfo.IsApplicationEnabled) { ErrorLog.LogApplicationError(message: "eSpace " + appInfo.eSpaceName + " is disabled", stackTrace: Environment.StackTrace, context: heContext, moduleName: "Global"); String contact = RuntimePlatformUtils.GetAdministrationEmail(); try { Context.Items[Constants.AppOfflineCustomHandler.ContactKey] = contact; Context.Items[Constants.AppOfflineCustomHandler.ErrorCodeKey] = "APPLICATION_OFFLINE"; Server.Transfer("/ContactManager/CustomHandlers/app_offline.aspx"); } catch (System.Threading.ThreadAbortException) {} catch { Response.Redirect("/ContactManager/CustomHandlers/internalerror.aspx"); } } InitializeUrls(); Actions.ActionOnBeginWebRequest(heContext); if (appInfo.IsForcingSecurityForScreens() && !RuntimePlatformUtils.RequestIsSecure(Request)) { Response.Redirect("https://" + Request.Url.Host + "" + AppUtils.Instance.getImagePath() + "InvalidPermissions.aspx" + Request.Url.Query); HttpContext.Current.ApplicationInstance.CompleteRequest(); } if (!IsPostBack) { CheckPermissions(heContext); bool bindEditRecords = !IsPostBack; Title = "Invalid Permissions"; Page.DataBind(); if (RuntimePlatformUtils.GetRequestTracer() != null) { RuntimePlatformUtils.GetRequestTracer().RegisterSessionSize(); if (heContext.Session != null) { RuntimePlatformUtils.GetRequestTracer().RegisterUserId(heContext.Session.UserId); } } if (!heContext.AppInfo.SelectiveLoggingEnabled || heContext.AppInfo.Properties.AllowLogging) { ScreenLog.StaticWrite(heContext.AppInfo, heContext.Session, heContext.StartInstant, (int)((TimeSpan)(DateTime.Now - heContext.StartInstant)).TotalMilliseconds, "InvalidPermissions", (string)heContext.Session["MSISDN"], "WEB", "Screen", RuntimeEnvironment.MachineName, RuntimePlatformUtils.GetViewstateSize(), RuntimePlatformUtils.GetRetrievedSessionSize(), RuntimePlatformUtils.GetRetrievedSessionRequests()); } } else { if (heContext.AppInfo.IsForcingSecurityForScreens() && !RuntimePlatformUtils.RequestIsSecure(Request)) { Response.Redirect("https://" + Request.Url.Host + "" + AppUtils.Instance.getImagePath() + "InvalidPermissions.aspx" + Request.Url.Query); HttpContext.Current.ApplicationInstance.CompleteRequest(); } FetchViewState(); } }
public int ProcessLaunch(HeContext heContext, int parentActivityId, int parentProcessId, List <Pair <string, object> > inputs, out List <Pair <int, ActivityKind> > nextActIds) { nextActIds = new List <Pair <int, ActivityKind> >(); //Sanity check to make sure we dont get here with the singleton process instance for the "definitions" if (Object.ReferenceEquals(((IProcess)this).Instance, this)) { return(NewInstance().ProcessLaunch(heContext, parentActivityId, parentProcessId, inputs, out nextActIds)); } int tenantId = heContext.AppInfo.Tenant.Id; Pair <int, ObjectKey> startActivity; processIdOverride = BPMRuntime.CreateProcessInstance(heContext, tenantId, GlobalKey.OwnerKey, GlobalKey.Key, parentActivityId, parentProcessId, out startActivity); var inputDefinitions = AllProcessInputsDefinitions; Dictionary <ObjectKey, IActivityVariable> inputsProcessed = new Dictionary <ObjectKey, IActivityVariable>(inputDefinitions.Count); IActivityVariable curInput; foreach (Pair <string, object> input in inputs) { ObjectKey key = ObjectKey.Parse(input.First); if (inputDefinitions.TryGetValue(key, out curInput)) { inputsProcessed[key] = curInput.NewInstance(input.Second); } } using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { foreach (var input in inputsProcessed.Values) { DBRuntimePlatform.Instance.AddProcessInput(trans, ProcessId, tenantId, input); this.ProcessInputs[input.Key] = input; } } Debugger.SetRequestName("Launch '" + Name + "'"); OnProcessStartCallback(heContext); //#586734 Check if the process was created. //A rollback in the OnProcessStart can delete the process that was created. using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { if (!DBRuntimePlatform.Instance.CheckProcessExists(trans, ProcessId)) { throw new InvalidOperationException("Failed to created process " + ProcessId); } } int previousTenantId = tenantId; tenantId = heContext.AppInfo.Tenant.Id; if (previousTenantId != tenantId) { //Do not use the same variable as above because that transaction can already be commited using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) { DBRuntimePlatform.Instance.SwitchProcessTenant(trans, ProcessId, previousTenantId, tenantId); } } SaveProcessOutputs(heContext); DatabaseAccess.CommitAllTransactions(); try { IProcessActivity startActivityInstance; if (GetProcessActivityInstance(ProcessId, startActivity.First, startActivity.Second, true, out startActivityInstance)) { var nextActivities = startActivityInstance.StartWork(heContext, false, ActivityStatus.Created) .Select(nextAct => Pair.Create(nextAct.First, nextAct.Second)); nextActIds = new List <Pair <int, ActivityKind> >(nextActivities); //TODO #124852 //if (!nextActivities.IsEmpty()) { // //Do not use the same variable as above because that transaction will already be commited // nextHumanActivity = BPMRuntime.GetNextHumanActivity(heContext, // DBTransactionManager.Current.SystemConnectionManager.GetMainTransaction(), nextActivities, heContext.Session.UserId); //} } } catch (Exception e) { // This should only happen if there are problems getting the next human activity, but we still want to return the process Id that was already created. Log.ErrorLog.StaticWrite(DateTime.Now, "", heContext.AppInfo.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, e.Message, e.StackTrace, "BPM"); } return(ProcessId); }