Exemplo n.º 1
0
        public void Write(IAppInfo appInfo, string id, DateTime instant, int duration, string source, string endpoint, string action, string type,
                          string errorId, bool isExpose)
        {
            Id              = id;
            Instant         = instant;
            Duration        = duration;
            Source          = source?.Left(MAX_SOURCE_SIZE) ?? string.Empty;
            Endpoint        = endpoint?.Left(MAX_ENDPOINT_SIZE) ?? string.Empty;
            Action          = action;
            Type            = type;
            EspaceId        = appInfo?.eSpaceId ?? 0;
            TenantId        = appInfo?.TenantId ?? 0;
            ErrorId         = errorId;
            ExecutedBy      = RuntimeEnvironment.MachineName;
            IsExpose        = isExpose;
            EspaceName      = appInfo?.eSpaceName;
            ApplicationName = appInfo?.ApplicationName;
            ApplicationKey  = appInfo?.ApplicationUIDAsKey;

            RequestTracer reqTracer = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                RequestKey = reqTracer.RequestKey;
            }

            log.Write();
        }
        public SessionStateStoreData DoGet(
            HttpContext context, bool exclusive, string id,
            out bool locked,
            out TimeSpan lockAge,
            out object lockId,
            out SessionStateActions actionFlags)
        {
            ItemState itemState;
            int       iLockId;

            byte[] data = exclusive ?
                          session.GetAndLock(id, out iLockId, out locked, out lockAge, out itemState) :
                          session.Get(id, out iLockId, out locked, out lockAge, out itemState);

            lockId      = iLockId;
            actionFlags = (SessionStateActions)itemState;

            RuntimePlatformUtils.SetRetrievedSessionSize(context, data == null ? 0 : data.Length);

            if (data == null)
            {
                return(null);
            }

            using (var s = new MemoryStream(data)) {
                var item = Deserialize(context, s);
                _rqOrigStreamLen = (int)s.Position;
                return(item);
            }
        }
Exemplo n.º 3
0
        public static string StaticWrite(IAppInfo appInfo, ISessionInfo sessionInfo, DateTime instant, string loginId, string errorId,
                                         string executedBy, string action, int duration, string source, string endpoint, string originalRequestKey)
        {
            ServiceAPILogDefinition logDef = new ServiceAPILogDefinition {
                Id                 = ServiceAPILogDefinition.GenerateLogId(),
                Instant            = instant,
                SessionId          = sessionInfo.SessionID,
                UserId             = sessionInfo.UserId,
                LoginId            = loginId,
                EspaceId           = appInfo.eSpaceId,
                TenantId           = appInfo.TenantId,
                ErrorId            = errorId,
                ExecutedBy         = executedBy,
                Action             = action,
                Duration           = duration,
                Source             = source,
                Endpoint           = endpoint,
                EspaceName         = appInfo.eSpaceName,
                ApplicationName    = appInfo.ApplicationName,
                ApplicationKey     = appInfo.ApplicationUIDAsKey,
                Username           = sessionInfo.UserName,
                OriginalRequestKey = originalRequestKey
            };

            RequestTracer reqTracer = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                logDef.RequestKey = reqTracer.RequestKey;
            }

            logDef.Write();
            return(logDef.Id);
        }
Exemplo n.º 4
0
        private static ContextInfoForStack FillContextInfoStruct(HeContext context)
        {
            ContextInfoForStack contextForStack = new ContextInfoForStack();

            if (context != null)
            {
                try { contextForStack.sessionId = context.Session.SessionID; } catch { }
                try { contextForStack.userId = context.Session.UserId; } catch { }
                try { contextForStack.username = context.Session.UserName; } catch { }
                try {
                    if (context.RequestTracer != null)
                    {
                        RequestTracer requestTracer = context.RequestTracer;
                        contextForStack.requestKey     = requestTracer.RequestKey;
                        contextForStack.actionName     = requestTracer.EntryActionName;
                        contextForStack.entryPointName = requestTracer.EntryEndpointName;
                        requestTracer.RegisterError();
                    }
                } catch { }
                try { contextForStack.requestUrl = context.Context.Request.Url.ToString(); } catch { }
                try { contextForStack.requestMethod = context.Context.Request.HttpMethod; } catch { }
                try {
                    contextForStack.requestQuery = context.Context.Request.QueryString != null?context.Context.Request.QueryString.ToString() : "";
                } catch { }
                try { contextForStack.currentLocale = context.CurrentLocale; } catch { }
                try { contextForStack.clientIp = RuntimePlatformUtils.GetClientIpForLogging(); } catch { }
                try { contextForStack.deviceUuid = RuntimePlatformUtils.GetDeviceUuidForLogging(); } catch { }
                try { contextForStack.CurrentExecutionFileName = context.CurrentExecutionFileName; } catch { }
            }

            return(contextForStack);
        }
Exemplo n.º 5
0
        private void Write(IAppInfo appInfo, ISessionInfo sessionInfo, DateTime instant, int duration, string screen, string msisdn,
                           string screenType, string accessMode, string executedBy, int viewstateBytes, int sessionBytes, int sessionRequests)
        {
            Instant         = instant;
            Duration        = duration;
            Screen          = screen;
            SessionId       = sessionInfo.SessionID;
            EspaceId        = appInfo.eSpaceId;
            TenantId        = appInfo.TenantId;
            UserId          = sessionInfo.UserId;
            Msisdn          = msisdn;
            ScreenType      = screenType;
            AccessMode      = ScreenLogDefinition.NotNullAccessMode(accessMode);
            ExecutedBy      = executedBy;
            ViewstateBytes  = viewstateBytes;
            SessionBytes    = sessionBytes;
            SessionRequests = sessionRequests;

            RequestTracer reqTracer = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                RequestKey = reqTracer.RequestKey;
                ActionName = reqTracer.EntryActionName;
            }

            ClientIP        = RuntimePlatformUtils.GetRequestSourceForLogging()?.Left(MAX_CLIENT_IP_SIZE);
            EspaceName      = appInfo.eSpaceName;
            ApplicationName = appInfo.ApplicationName;
            ApplicationKey  = appInfo.ApplicationUIDAsKey;
            Username        = sessionInfo.UserName;

            log.Write();
        }
Exemplo n.º 6
0
        internal static IRuntimeDatabaseConfiguration CreateDatabaseConfiguration(IPlatformDatabaseProvider databaseProvider, string connectionString,
                                                                                  string onsClusterConfig, string connectionStringExtras, string schema, bool forConnectionState)
        {
            var config = databaseProvider.CreateEmptyRuntimeDatabaseConfiguration();


            connectionStringExtras = connectionStringExtras ?? "";
            var fullConnectionString   = RuntimePlatformUtils.connectionStringJoin(connectionString, connectionStringExtras);
            var databaseIdentifier     = schema;
            var databaseUnicodeSupport = Settings.GetBool(Settings.Configs.Compiler_DatabaseUnicodeSupport);

            var wrapper = new MetaDatabaseConfiguration(config);

            wrapper.GetParameter("ConnectionString").Set(fullConnectionString);
            var sch = wrapper.GetParameter("Schema");

            if (sch != null)
            {
                sch.Set(databaseIdentifier);
            }

            var unicode = wrapper.GetParameter("DatabaseUnicodeSupport");

            if (unicode != null)
            {
                unicode.Set(databaseUnicodeSupport + "");
            }

            return(config);
        }
        public override string getImagePath(bool forInternalAccess, bool includeSessionIdIfNeeded, string nameOverride)
        {
            HttpRequest request = HttpContext.Current.Request;

            try {
                HeContext heContext = Global.App.OsContext;
                string    path      = heContext.OsISAPIFilter.GetHostSuffix(request, "");
                bool      keepPTA   = AppInfo.GetAppInfo().eSpaceId == Global.eSpaceId && nameOverride == null;
                if (!keepPTA || forInternalAccess)
                {
                    path += RuntimePlatformUtils.GetEspacePrettyNamePath(nameOverride ?? "Address_CS", heContext);
                }
                else
                {
                    path += (heContext.OsISAPIFilter.IsActiveInRequest(request) ? heContext.OsISAPIFilter.GetPath(request, "") + "/": "/Address_CS/");
                }
                if (keepPTA)
                {
                    path += AppInfo.GetAppInfo().PtaPath;
                }
                return(RuntimePlatformUtils.CheckUriSecurity(request, path));
            } catch {
                return("");
            }
        }
Exemplo n.º 8
0
        public IntegrationLog(IAppInfo appInfo, string id, DateTime instant, int duration, string source, string endpoint, string action, string type,
                              string errorId, string executedBy, bool isExpose)
        {
            log = new IntegrationLogDefinition();

            Id              = id;
            Instant         = instant;
            Duration        = duration;
            Source          = source?.Left(MAX_SOURCE_SIZE) ?? string.Empty;
            Endpoint        = endpoint?.Left(MAX_ENDPOINT_SIZE) ?? string.Empty;
            Action          = action;
            Type            = type;
            EspaceId        = appInfo?.eSpaceId ?? 0;
            TenantId        = appInfo?.TenantId ?? 0;
            ErrorId         = errorId;
            ExecutedBy      = executedBy;
            IsExpose        = isExpose;
            EspaceName      = appInfo?.eSpaceName;
            ApplicationName = appInfo?.ApplicationName;
            ApplicationKey  = appInfo?.ApplicationUIDAsKey;

            RequestTracer reqTracer = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                RequestKey = reqTracer.RequestKey;
            }
        }
Exemplo n.º 9
0
        public static void DownloadBinary(Hashtable htDbBinaryConfig)
        {
            HttpRequest  request  = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            if ((request.HttpMethod.ToUpper() != "GET") && (request.HttpMethod.ToUpper() != "HEAD"))
            {
                response.AppendHeader("Allow", "GET, HEAD");
                ResponseError(response, 405, "Method Not Allowed");
                return;
            }
            string parametersString = GetParameters(request).TrimEnd('/').TrimStart('/').Replace("-", "+").Replace("_", "/");    /* Replace invalid URL chars */

            parametersString = SymmCryptHelper.DecryptWithAES256FixedIV(BinaryContentUtils.DatabaseBinaryEnvironmentPassword, parametersString, Convert.FromBase64String(PRIVATE_SALT));

            var parameters = parametersString.Split('/');

            if (parameters.Length < 3)
            {
                ResponseError(response, 400, "Bad Request");
                return;
            }

            var entity    = parameters[0].ToLower();
            var attribute = parameters[1].ToLower();
            var id        = parameters[2];

            object objt = htDbBinaryConfig[entity + "/" + attribute];

            if (objt == null)
            {
                ResponseError(response, 404, "Not Found");
                return;
            }

            DbBinaryConfig dbBinaryConfig;

            dbBinaryConfig = (DbBinaryConfig)objt;

            byte[] buffer = GetDatabaseBinaryAttribute(id, dbBinaryConfig);
            if (buffer == null)
            {
                ResponseError(response, 404, "Not Found");
            }
            else
            {
                string md5Hash = SecureHashHelper.Hash(buffer);
                response.Clear();
                response.StatusCode  = 200; //OK
                response.ContentType = RuntimePlatformUtils.GetMIMEType(buffer);
                response.AppendHeader("ETag", "\"" + md5Hash + "\"");
                response.AppendHeader("Accept-Ranges", "none");
                if (request.HttpMethod.ToUpper() == "GET")
                {
                    BinaryWrite(response, buffer);
                }
                End(response);
            }
        }
Exemplo n.º 10
0
        public static string DecimalToText(decimal value)
        {
            NumberFormatInfo format = FormatInfoLogic.Number;

            format = (NumberFormatInfo)format.Clone();
            format.NumberDecimalDigits = 28;
            return(RuntimePlatformUtils.RemoveTrailingZeros(value.ToString("N", format), format));
        }
        private void HandleLicensingError(LicensingException excep)
        {
            string contact     = BuiltInFunction.EncodeUrl(RuntimePlatformUtils.GetAdministrationEmail());
            string errorCode   = "APPLICATION_LICENSING_ERROR";
            string errorDetail = BuiltInFunction.EncodeUrl(excep.Detail.IsEmpty() ? excep.Message: excep.Detail);

            Server.Transfer("/customHandlers/app_offline.aspx?contact=" + contact + "&errorCode=" + errorCode + "&errorDetail=" + errorDetail);
        }
        protected void Application_PostAcquireRequestState(Object sender, EventArgs e)
        {
            RequestTracer perfTracer = RuntimePlatformUtils.GetRequestTracer();

            if (perfTracer != null)
            {
                perfTracer.RegisterSessionAcquisitionTime();
            }
        }
        private byte[] _GetExternalItem(String sessionId, string itemId)
        {
            var data = session.GetModuleItem(sessionId + appSufix, itemId);

            if (data != null)
            {
                RuntimePlatformUtils.IncrementRetrievedSessionSize(data.Length);
            }
            RuntimePlatformUtils.IncrementRetrievedSessionRequests();
            return(data);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns the current RequestKey, consistent with RequestEvents being logged in the database for the current request.
        /// If there is no RequestKey available in the current context, an empty string is returned.
        /// </summary>
        /// <returns>A string containing the request key.</returns>
        public static string GetRequestKey()
        {
            RequestTracer tracer = RuntimePlatformUtils.GetRequestTracer();

            if (tracer != null)
            {
                return(tracer.RequestKey);
            }

            return("");
        }
Exemplo n.º 15
0
        private void HandleLicensingError(LicensingException excep)
        {
            string contact     = RuntimePlatformUtils.GetAdministrationEmail();
            string errorCode   = "APPLICATION_LICENSING_ERROR";
            string errorDetail = excep.Detail.IsEmpty() ? excep.Message: excep.Detail;

            // The Context object only works with Server.Transfer, and not with Response.Redirect
            Context.Items[Constants.AppOfflineCustomHandler.ContactKey]     = contact;
            Context.Items[Constants.AppOfflineCustomHandler.ErrorCodeKey]   = errorCode;
            Context.Items[Constants.AppOfflineCustomHandler.ErrorDetailKey] = errorDetail;
            Server.Transfer("/ContactManager/CustomHandlers/" + Constants.AppOfflineCustomHandler.FileName);
        }
        protected string GetVisitCode()
        {
            SessionInfo session = AppInfo.GetAppInfo().OsContext.Session;

            if (session["osIsNewVisit"] != null && ((bool)session["osIsNewVisit"])
                // && !NetworkInterfaceUtils.IsLoopbackAddress(Request.UserHostAddress)
                && RuntimePlatformUtils.IsValidRequestForVisit())
            {
                return("<script type=\"text/javascript\">outsystems.internal.$.get(\"/ContactManager/_status.aspx\")</script>");
            }
            return("");
        }
        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 void MssOnSessionStart(HeContext heContext)
        {
            int oldCurrentESpaceId = heContext.CurrentESpaceId;

            try {
                heContext.CurrentESpaceId = ssBusiness_CS.Global.eSpaceId;
                if (RuntimePlatformUtils.TestAndSetProducerSession("Business_CS"))
                {
                    ssBusiness_CS.Actions.ActionOnSessionStart(heContext);
                }
            } finally {
                heContext.CurrentESpaceId = oldCurrentESpaceId;
            }
        }
        public virtual string GetRedirectionProtocol(bool destinationIsSecure)
        {
            var page     = (IWebScreen)Page;
            var protocol = (RuntimePlatformUtils.RequestIsHttps(Request) ? "https://" : "http://");

            if (destinationIsSecure)
            {
                return((!page.isSecure && !RuntimePlatformUtils.RequestIsHttps(Request)) ? "https://" : protocol);
            }
            else
            {
                return((page.isSecure && RuntimePlatformUtils.RequestIsHttps(Request)) ? "http://" : protocol);
            }
        }
Exemplo n.º 20
0
        public void Write(IAppInfo appInfo, string id, DateTime instant, string screen, string endpoint, string source, int duration,
                          string executedBy, string errorId, string loginId, int userId, string username)
        {
            string        requestKey = RequestKey;
            RequestTracer reqTracer  = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                requestKey = reqTracer.RequestKey;
            }

            log.Write(id, instant, appInfo.eSpaceId, appInfo.TenantId, screen, endpoint, source, duration, executedBy, errorId, loginId, userId, requestKey,
                      appInfo.eSpaceName, appInfo.ApplicationName, appInfo.ApplicationUIDAsKey, username);
        }
Exemplo n.º 21
0
        protected string GetMIMEType()
        {
            object acceptHeader = Request.Headers["Accept"];

            string[] accept;

            if (acceptHeader == null)
            {
                accept = new string[0];
            }
            else
            {
                accept = acceptHeader.ToString().Split(new char[] { ',' }
                                                       , 250);
            }

            int    nTakesJPEG = 100000;
            int    nTakesJPG  = 100000;
            string mime;

            for (int i = 0; i < accept.Length; i++)
            {
                mime = accept[i].Trim();
                if (string.Equals(mime, "image/jpeg", StringComparison.CurrentCultureIgnoreCase))
                {
                    nTakesJPEG = i;
                }
                if (string.Equals(mime, "image/jpg", StringComparison.CurrentCultureIgnoreCase))
                {
                    nTakesJPG = i;
                }
            }
            mime = RuntimePlatformUtils.GetMIMEType(getExtension());

            if (string.Equals(mime, "image/jpeg", StringComparison.CurrentCultureIgnoreCase) ||
                string.Equals(mime, "image/jpg", StringComparison.CurrentCultureIgnoreCase))
            {
                if (nTakesJPEG < nTakesJPG)
                {
                    mime = "image/jpeg";
                }
                else
                {
                    mime = "image/jpg";
                }
            }

            return(mime);
        }
Exemplo n.º 22
0
        public MobileRequestLog(string id, DateTime instant, int espaceId, int tenantId, string screen, string endpoint,
                                string source, int duration, string executedBy, string errorId, string loginId, int userId,
                                string eSpaceName, string applicationName, ObjectKey applicationKey, string username)
        {
            string        requestKey = string.Empty;
            RequestTracer reqTracer  = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                requestKey = reqTracer.RequestKey;
            }

            log = new MobileRequestLogDefinition(id, instant, espaceId, tenantId, screen, endpoint, source, duration, executedBy, errorId,
                                                 requestKey, loginId, userId, eSpaceName, applicationName, applicationKey, username);
        }
Exemplo n.º 23
0
        public void Write(DateTime instant, int duration, ObjectKey cyclicJobKey, int espaceId, int tenantId,
                          string executedBy, string errorId, DateTime shouldHaveRunAt, DateTime nextRun, string eSpaceName, string applicationName,
                          ObjectKey applicationKey, string cyclicJobName)
        {
            string        requestKey = RequestKey;
            RequestTracer reqTracer  = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                requestKey = reqTracer.RequestKey;
            }

            log.Write(instant, duration, cyclicJobKey, espaceId, tenantId, executedBy, errorId, shouldHaveRunAt, nextRun, requestKey,
                      eSpaceName, applicationName, applicationKey, cyclicJobName);
        }
 public virtual SmsNode Execute(HeContext heContext)
 {
     try {
         heContext.AppInfo.CheckIsApplicationEnabled();
         LoadDefaultLargeAccount(heContext);
         CheckPermissions(heContext);
         Render(heContext);
         ScreenLog.StaticWrite(heContext.StartInstant, (int)((TimeSpan)(DateTime.Now - heContext.StartInstant)).TotalMilliseconds, (_Name != null)?_Name:"", heContext.Session.SessionID, heContext.AppInfo.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, (string)(heContext.MOMsg != null ? heContext.MOMsg.MSISDN : ""), "SMS", "Screen", Environment.MachineName,
                               RuntimePlatformUtils.GetViewstateSize(),
                               RuntimePlatformUtils.GetRetrievedSessionSize(), RuntimePlatformUtils.GetRetrievedSessionRequests());
         return(this);
     }
     catch (Exception e) {
         return(HandleException(heContext, e));
     }
 }
Exemplo n.º 25
0
        private string GetTextResource(string espaceName, string resourceName, bool enableWarnings)
        {
            var resourceBinary = RuntimePlatformUtils.TryGetResourceBinary(resourceName, espaceName);

            if (resourceBinary != null && resourceBinary.Length > 0)
            {
                return(Encoding.UTF8.GetStringWithoutBOM(resourceBinary));
            }

            if (enableWarnings)
            {
                OSTrace.Warning("Could not get " + resourceName + " file for '{0}'.", espaceName);
            }

            return(null);
        }
Exemplo n.º 26
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            HttpContext  current    = HttpContext.Current;
            HttpRequest  request    = current.Request;
            HttpResponse response   = current.Response;
            string       parameters = request.PathInfo.Substring(1);
            string       dwldhash   = parameters.Split('/')[0];
            string       filename   = parameters.Split('/')[1];

            string   mimeType, dummydisposition, dummyfilename;
            DateTime timestamp;

            byte[] buffer;
            bool   foundFile = RuntimePlatformUtils.GetTemporaryAndroidDownload(dwldhash, out mimeType, out timestamp, out buffer, out dummyfilename, out dummydisposition);

            // all dates are UTC dates
            if (!foundFile || timestamp < DateTime.UtcNow)
            {
                // Note: if seeing strange 404 requests, consider logging more information here
                response.Clear();
                response.Status            = "404 Not Found";
                response.StatusCode        = 404;
                response.StatusDescription = "Not Found";
                response.Write("Bad Request");
                response.End();
            }

            response.Clear();
            response.Status            = "200 OK";
            response.StatusCode        = 200;
            response.StatusDescription = "OK";
            response.ContentType       = mimeType;
            response.AppendHeader("Cache-Control", "private");
            if (filename != String.Empty)
            {
                response.AppendHeader("Content-Disposition", "attachment; filename=" + RuntimePlatformUtils.EscapeFilenameForDownload(filename));
            }

            if (buffer.Length > 0)
            {
                response.BinaryWrite(buffer);
            }

            response.End();
        }
Exemplo n.º 27
0
        protected static ActivityVariable <T> GetVariable <T>(ActivityVariable <T> variableDefinition, GetVariablesDelegate getMethod, int id)
        {
            object rawVariable = null;

            if (id != DummyId)
            {
                using (Transaction trans = DatabaseAccess.ForSystemDatabase.GetRequestTransaction()) {
                    using (IDataReader reader = getMethod(trans, variableDefinition.Key, id)) {
                        if (reader.Read())
                        {
                            rawVariable = RuntimePlatformUtils.ConvertFromString((string)reader["Value"], (string)reader["Data_Type"]);
                        }
                    }
                }
            }

            return((rawVariable != null) ? variableDefinition.NewInstance <T>(rawVariable) : variableDefinition.NewInstance <T>());
        }
Exemplo n.º 28
0
        public static string StaticWrite(DateTime instant, string sessionId, int espaceId, int tenantId, int userId, string message,
                                         string stack, string environmentInformation, string moduleName,
                                         string eSpaceName, string applicationName, ObjectKey applicationKey, string username)
        {
            string requestKey, actionName, entryPointName;

            requestKey = actionName = entryPointName = String.Empty;

            RequestTracer reqTracer = RuntimePlatformUtils.GetRequestTracer();

            if (reqTracer != null)
            {
                requestKey     = reqTracer.RequestKey;
                actionName     = reqTracer.EntryActionName;
                entryPointName = reqTracer.EntryEndpointName;
            }

            return(ErrorLogDefinition.StaticWrite(instant, sessionId, espaceId, tenantId, userId, message, stack, environmentInformation, moduleName, requestKey, entryPointName, actionName,
                                                  eSpaceName, applicationName, applicationKey, username));
        }
        public void ValidateRequestSecurity()
        {
            var useSSL = BehaviorsConfiguration.HTTPSecurity == HTTPSecurity.SSL;

            if (useSSL || ShouldEnforceSecureRequests(AppInfo.GetAppInfo()))
            {
                if (!RuntimePlatformUtils.RequestIsSecure(HttpContext.Current.Request, !useSSL))
                {
                    throw new ExposeRestException("HTTPS connection required.", HttpStatusCode.Forbidden);
                }
            }

            if (BehaviorsConfiguration.InternalAccessOnly)
            {
                if (!RuntimePlatformUtils.InternalAddressIdentification(HttpContext.Current.Request))
                {
                    throw new ExposeRestException("Access Denied.", HttpStatusCode.Forbidden);
                }
            }
        }
Exemplo n.º 30
0
        public static void MssStringBuilder_Create(HeContext heContext, int inParamInitialCapacity, out object outParamStringBuilder)
        {
            DateTime startTime  = DateTime.Now;
            String   errorLogId = "";

            try {
                issText.MssStringBuilder_Create(inParamInitialCapacity, out outParamStringBuilder);
            } catch (Exception ex) {
                errorLogId = ErrorLog.LogApplicationError(ex, heContext, "Extension method execution: Text.StringBuilder_Create");
                throw ex;
            } finally {
                if (errorLogId != string.Empty || (!heContext.AppInfo.SelectiveLoggingEnabled ||
                                                   (heContext.AppInfo.ExtensionProperties.AllowLogging("b69aa077-acf4-4bdc-bcd5-9def81d7ddcd") && heContext.AppInfo.Properties.AllowLogging)))
                {
                    int extLogCount = heContext.ExtensionLogCount;
                    if (extLogCount == _maxExtensionLogsPerRequest)
                    {
                        // issue warning
                        GeneralLog.StaticWrite(
                            DateTime.Now, heContext.Session.SessionID, heContext.AppInfo.eSpaceId, heContext.AppInfo.Tenant.Id,
                            heContext.Session.UserId, "The maximum number (" + _maxExtensionLogsPerRequest + ") of allowed Extension Log entries per request has been exceeded. No more entries will be logged in this request.",
                            "WARNING", "SLOWEXTENSION", "");
                        heContext.ExtensionLogCount = extLogCount + 1;
                    }
                    else if (extLogCount < _maxExtensionLogsPerRequest)
                    {
                        DateTime instant           = DateTime.Now;
                        int      executionDuration = Convert.ToInt32(DateTime.Now.Subtract(startTime).TotalMilliseconds);
                        ExtensionLog.StaticWrite(heContext.AppInfo, heContext.Session,
                                                 instant, executionDuration, "StringBuilder_Create", errorLogId, 20, "Text");
                        heContext.ExtensionLogCount = extLogCount + 1;
                        RequestTracer reqTracer = heContext.RequestTracer;
                        if (reqTracer != null)
                        {
                            reqTracer.RegisterExtensionExecuted("f13768e4-0fbe-4be7-a870-51b5c8362fed", "StringBuilder_Create", "794c445f-f27d-4f61-b47a-0da71440df68", "ContactManager", executionDuration, instant);
                        }
                    }
                }
                RuntimePlatformUtils.LogSlowExtensionCall(startTime, "Text.StringBuilder_Create");
            }
        }