protected StaticRecordMetadata GetRecordMetadataByKey(ObjectKey key) { StaticRecordMetadata record; if (!RecordsMetaByKey.TryGetValue(key, out record) || record == null || !record.Valid) { record = newStaticRecord(); using (Transaction systemTransaction = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) { using (IDataReader reader = DBRuntimePlatform.Instance.GetStaticRecordBykey(systemTransaction, key, EntityKey, EspaceId)) { if (reader.Read()) { record.Read(reader); AddToMetadataCache(record); } else { //Not found on db so we can return a empty record OSTrace.Error("GetRecordMetadataByKey(Key=" + ObjectKeyUtils.DatabaseValue(key) + ", EntityKey=" + ObjectKeyUtils.DatabaseValue(EntityKey) + ", EspaceId=" + EspaceId + ") found no metadata!"); } } } } return(record); }
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()); } }
public void ClearCache() { OSTrace.Debug("StaticEntityRuntime.ClearCache: Clearing cache for " + ObjectKeyUtils.DatabaseValue(EntityKey) + "."); _recordsMetaByName.Clear(); _recordsMetaByKey.Clear(); foreach (Hashtable recordsById in _recordsByIdByLocale.Values) { recordsById.Clear(); } }
protected HttpWebRequest BuildServiceAPIMethodRequest(HeContext context, string sapimName, object inputs) { var zoneSettings = DeploymentZoneResolution.ByModuleKey(ProducerModuleKey); var securityProtocol = zoneSettings.EnableHttps ? "https" : "http"; var sapimEndpoint = $"{securityProtocol}://{zoneSettings.Address}/{ProducerModuleName}/serviceapi/{UrlEncode(sapimName)}"; string httpMethod = "POST"; var headers = new Dictionary <string, string>(); headers.Add("User-Agent", "OutSystemsPlatform"); headers.Add("Content-Type", "application/json"); headers.Add("Content-Language", context.CurrentLocale); var requestPayload = new CoreServicesApiController.Payload.RequestPayload(); requestPayload.RequestKey = RuntimePlatformUtils.GetRequestTracer()?.RequestKey ?? Guid.NewGuid().ToString(); requestPayload.InputParameters = JObject.FromObject(inputs); string payloadString = JsonConvert.SerializeObject(requestPayload, Formatting.None); var stringToken = SecurityTokenAPI.GenerateJWTTokenString( settingsProvider: RuntimeSettingsProvider.Instance, consumerModuleKey: ObjectKeyUtils.DatabaseValue(ConsumerModuleKey), producerModuleKey: ObjectKeyUtils.DatabaseValue(ProducerModuleKey), userId: context.Session.UserId, tenantId: context.Session.TenantId, requestHash: SecurityTokenAPI.GeneratePayloadHash(RuntimeSettingsProvider.Instance, payloadString), requestLifetime: RuntimePlatformSettings.ServiceAPIs.RequestLifetime.GetValue() ); headers.Add(AuthorizationHeaderKey, AuthorizationTokenType + stringToken); var request = (HttpWebRequest)HttpWebRequest.Create(sapimEndpoint); request.Method = httpMethod; // set the timeout for the request request.Timeout = DefaultTimeoutInSeconds * 1000; // set headers in request foreach (var header in headers.Keys) { SetRequestHeader(request, header, headers[header]); } // set request body using (Stream requestStream = request.GetRequestStream()) { var requestBody = Encoding.UTF8.GetBytes(payloadString); requestStream.Write(requestBody, 0, requestBody.Length); } return(request); }
public static int ProcessLaunch(HeContext heContext, ObjectKey SSKey, ObjectKey espaceSSKey, int parentActivityId, int parentProcessId, List <Pair <string, object> > inputs, out List <Pair <int, ActivityKind> > nextActIds) { string ssKey = ObjectKeyUtils.DatabaseValue(SSKey); BPMRuntime.GetProcessDataForWS(heContext, SSKey, espaceSSKey, out string url); using (ActivityHandler activityHandler = new ActivityHandler(url, heContext.Session.TenantId, heContext.Session.UserId, heContext.AppInfo.eSpaceUID, ObjectKeyUtils.DatabaseValue(espaceSSKey))) { int newProcessId = activityHandler.ExecuteProcessLaunch(ssKey, heContext.Session.TenantId, heContext.Session.UserId, parentActivityId, parentProcessId, inputs, out nextActIds, out string failureMessage); if (!failureMessage.IsEmpty() || newProcessId == 0) { ProcessBase.ThrowSpecificException(failureMessage); } return(newProcessId); } }
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); }
public DataParameter CreateParameter(string name, DbType dbType, ObjectKey key) { if (key == null) { /* The key should never be null, if something like that happens we should * go to the other AddParameter because .Net will use the most specific method instead * of using the most generic one or giving some kind of warning/error. * * This happens when we call an AddParameter in SqlStateConnection.TempGet and other places. */ return(CreateParameter(name, dbType, (object)null)); } string keyToInsert = ObjectKeyUtils.DatabaseValue(key); return(CreateParameter(name, dbType, keyToInsert)); }
private static IRuntimeDatabaseConfiguration ConfigurationForCurrent() { HttpContext context = HttpContext.Current; if (context != null) { AppInfo app; try { app = AppInfo.GetAppInfo(context); } catch (LicensingException) { return(null); // Fallback to the Runtime Catalog } if (app != null) { return(CatalogConfigurationForESpace(ObjectKeyUtils.DatabaseValue(app.OsContext.CurrentESpaceKey))); } } return(null); }
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"); }
protected override bool GetPrecedentActivity(ObjectKey targetSSKey, out IProcessActivity instance) { int prededentActivityId; using (Transaction trans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) { prededentActivityId = DBRuntimePlatform.Instance.GetPrecedentActivityId(trans, ActivityId, ObjectKeyUtils.DatabaseValue(targetSSKey)); } instance = null; if (prededentActivityId != 0) { return(GetProcessActivityImplementation(ProcessId, prededentActivityId, targetSSKey, false, out instance)); } return(false); }
protected void LoadAllEntriesMetadata() { using (OSTrace.Timer("StaticEntityRuntime.LoadAllEntriesMetadata: Loading metadata for " + ObjectKeyUtils.DatabaseValue(EntityKey) + ".")) { using (Transaction tran = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) { using (IDataReader reader = DBRuntimePlatform.Instance.GetStaticRecordsByEntity(tran, EntityKey, EspaceId)) { int count = 0; while (reader.Read()) { StaticRecordMetadata record = newStaticRecord(); record.Read(reader); AddToMetadataCache(record); count++; } OSTrace.Debug("StaticEntityRuntime.LoadAllEntriesMetadata: Loaded " + count + " metadata records."); } } } }