Esempio n. 1
0
        protected override string EntityToTablename(string entity, int tenantId)
        {
            string entityLC = entity.ToLowerInvariant();

            switch (entityLC)
            {
            case "recentitem":
                return(ENRecentItemEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "messagetype":
                return(ENMessageTypeEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "menuitem":
                return(ENMenuItemEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "contact":
                return(ENContactEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "application":
                return(ENApplicationEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "user":
                return(ENUserEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));
            }

            throw new DataBaseException("'" + entity + "' found in 'Expand Inline' parameter is an unknown Entity");
        }
Esempio n. 2
0
        public static Value invokeBuiltInFunction(BuiltInFunction function, params object[] arguments)
        {
            List <Value> value_args = new List <Value>();

            foreach (object arg in arguments)
            {
                if (arg.GetType() == typeof(string))
                {
                    value_args.Add(new Value((string)arg));
                }
                else if (arg.GetType() == typeof(char))
                {
                    value_args.Add(new Value((char)arg));
                }
                else if (arg.GetType() == typeof(int))
                {
                    value_args.Add(new Value((double)arg));
                }
                else if (arg.GetType() == typeof(double))
                {
                    value_args.Add(new Value((double)arg));
                }
                else if (arg == null)
                {
                    value_args.Add(null);
                }
                else
                {
                    throw new Exception("Invalid Value type.");
                }
            }
            return(function.Invoke(new List <Value>(value_args)));
        }
Esempio n. 3
0
        /// <summary>
        /// Action <code>ActionPrivate_HashGet</code> that represents the Service Studio user action
        ///  <code>Private_HashGet</code> <p> Description: </p>
        /// </summary>
        public static void ActionPrivate_HashGet(HeContext heContext, string inParamHash, string inParamKey, out string outParamValue)
        {
            lcoPrivate_HashGet result    = new lcoPrivate_HashGet();
            lcvPrivate_HashGet localVars = new lcvPrivate_HashGet(inParamHash, inParamKey);

            if (heContext != null && heContext.RequestTracer != null)
            {
                heContext.RequestTracer.RegisterInternalCall("iDMk1w28PUC8Sv34YvikpQ", "Private_HashGet", "X0RMeX3yYU+0eg2nFEDfaA", "ContactManager");
            }
            try {
                // List_Key
                // Index = Index
                localVars.varLcIndex = BuiltInFunction.IndexSC(localVars.inParamHash, localVars.inParamKey, 0, false, false);
                // Found Key?
                if (((localVars.varLcIndex != (-1))))
                {
                    // SetValue
                    // tmp = Substr
                    localVars.varLctmp = BuiltInFunction.SubstrSC(localVars.inParamHash, ((localVars.varLcIndex + BuiltInFunction.LengthSC(localVars.inParamKey)) + 1), (BuiltInFunction.LengthSC(localVars.inParamHash) - BuiltInFunction.LengthSC(localVars.inParamKey)));
                    // Value = Substr
                    result.outParamValue = BuiltInFunction.SubstrSC(localVars.varLctmp, 0, BuiltInFunction.IndexSC(localVars.varLctmp, ";", 0, false, false));
                }
            }             // try

            finally {
                outParamValue = result.outParamValue;
            }
        }
        /// <summary>
        /// Action <code>ActionAddress_CreateOrUpdate</code> that represents the Service Studio user action
        ///  <code>Address_CreateOrUpdate</code> <p> Description: This action creates or updates the give
        /// n address.</p>
        /// </summary>
        public static void ActionAddress_CreateOrUpdate(HeContext heContext, ENAddressEntityRecord inParamAddressR, out long outParamAddressId)
        {
            lcoAddress_CreateOrUpdate result    = new lcoAddress_CreateOrUpdate();
            lcvAddress_CreateOrUpdate localVars = new lcvAddress_CreateOrUpdate(inParamAddressR);

            try {
                // new address?
                if (((localVars.inParamAddressR.ssId == Convert.ToInt64(BuiltInFunction.NullIdentifier()))))
                {
                    // creation info
                    // AddressR.Active = True
                    localVars.inParamAddressR.ssActive = true;
                    // AddressR.CreatedDate = CurrDateTime
                    localVars.inParamAddressR.ssCreatedDate = BuiltInFunction.CurrDateTime();
                    // AddressR.CreatedBy = GetUserId
                    localVars.inParamAddressR.ssCreatedBy = BuiltInFunction.GetUserId();
                }

                // update info
                // AddressR.LastUpdatedDate = CurrDateTime
                localVars.inParamAddressR.ssLastUpdatedDate = BuiltInFunction.CurrDateTime();
                // AddressR.LastUpdatedBy = GetUserId
                localVars.inParamAddressR.ssLastUpdatedBy = BuiltInFunction.GetUserId();
                // CreateOrUpdateAddress
                ExtendedActions.CreateOrUpdateAddress(heContext, localVars.inParamAddressR.ChangedAttributes, (((RCAddressRecord)localVars.inParamAddressR)), out localVars.resCreateOrUpdateAddress_outParamId);

                // AddressId = CreateOrUpdateAddress.Id
                result.outParamAddressId = localVars.resCreateOrUpdateAddress_outParamId;
            }             // try

            finally {
                outParamAddressId = result.outParamAddressId;
            }
        }
Esempio n. 5
0
        private static byte[] GetDatabaseBinaryAttribute(string id, DbBinaryConfig dbBinaryConfig)
        {
            IDMLIdentifiers         identifiers = null;
            IDatabaseAccessProvider dbAccessProvider;

            if (string.IsNullOrEmpty(dbBinaryConfig.DBConnection))
            {
                dbAccessProvider = DatabaseAccess.ForCurrentDatabase;
                identifiers      = DatabaseAccess.ForCurrentDatabase.DatabaseServices.DMLService.Identifiers;
            }
            else
            {
                dbAccessProvider = DatabaseAccess.ForDBConnection(dbBinaryConfig.DBConnection);
                identifiers      = DatabaseAccess.ForDBConnection(dbBinaryConfig.DBConnection).DatabaseServices.DMLService.Identifiers;
            }

            string selectSQL = "SELECT " + identifiers.EscapeIdentifier(dbBinaryConfig.Attribute.ToUpper()) + " FROM " +
                               dbBinaryConfig.EntityGetter(null, BuiltInFunction.GetCurrentLocale()) +
                               " WHERE " + identifiers.EscapeIdentifier(dbBinaryConfig.Id.ToUpper()) + " = ";

            if (dbBinaryConfig.IsAlphaId)
            {
                selectSQL += "'" + BuiltInFunction.EncodeSql(id) + "'";
            }
            else
            {
                selectSQL += BuiltInFunction.EncodeSql(id);
            }

            return(GetBinaryFromDb(selectSQL, dbBinaryConfig.Attribute, dbAccessProvider));
        }
Esempio n. 6
0
        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>");
        }
        /// <summary>
        /// Action <code>ActionList_Navigation_GetStartIndex</code> that represents the Service Studio user
        ///  action <code>List_Navigation_GetStartIndex</code> <p> Description: Resets the index stored in th
        /// e Session Variable that is used in the 'List_Navigation_GetStartIndex' action.</p>
        /// </summary>
        public static void ActionList_Navigation_GetStartIndex(HeContext heContext, string inParamListWidget, bool inParamRememberStartIndex, int inParamStartIndexOverride, out int outParamStartIndex)
        {
            lcoList_Navigation_GetStartIndex result    = new lcoList_Navigation_GetStartIndex();
            lcvList_Navigation_GetStartIndex localVars = new lcvList_Navigation_GetStartIndex(inParamListWidget, inParamRememberStartIndex, inParamStartIndexOverride);

            if (heContext != null && heContext.RequestTracer != null)
            {
                heContext.RequestTracer.RegisterInternalCall("RXVvq_7n1UK+COrxcmxk4A", "List_Navigation_GetStartIndex", "X0RMeX3yYU+0eg2nFEDfaA", "ContactManager");
            }
            try {
                // StartIndexOverride?
                if (((localVars.inParamStartIndexOverride != (-1))))
                {
                    // SetOverridenStartIndex
                    Actions.ActionPrivate_List_Navigation_SaveStartIndex(heContext, localVars.inParamListWidget, Convert.ToString(localVars.inParamStartIndexOverride));

                    // SetOverridenStartIndex
                    // StartIndex = StartIndexOverride
                    result.outParamStartIndex = localVars.inParamStartIndexOverride;
                }
                else
                {
                    // ResetStartIndex?
                    if ((((localVars.inParamRememberStartIndex == false) && BuiltInFunction.IsLoadingScreen())))
                    {
                        // ResetStartIndex
                        Actions.ActionPrivate_List_Navigation_SaveStartIndex(heContext, localVars.inParamListWidget, Convert.ToString(0));
                    }
                    else
                    {
                        // ListIndex_Text
                        // ListIndex_Text = Private_HashGet(ListNavigation_StartIndices, GetPageName() + ":" + ListWidget)
                        localVars.varLcListIndex_Text = Functions.ActionPrivate_HashGet(heContext, ((string)Global.App.OsContext.Session["ContactManager.ListNavigation_StartIndices"]), ((Functions.rssextensionhttprequesthandler_ActionGetPageName(heContext) + ":") + localVars.inParamListWidget));
                        // Found Key?
                        if (((localVars.varLcListIndex_Text != "")))
                        {
                            // SetStartIndex
                            // StartIndex = TextToInteger
                            result.outParamStartIndex = BuiltInFunction.TextToInteger(localVars.varLcListIndex_Text);
                        }

                        // ResetRememberStartIndex
                        // ListNavigation_RememberStartIndices = Replace
                        Global.App.OsContext.Session["ContactManager.ListNavigation_RememberStartIndices"] = BuiltInFunction.Replace(((string)Global.App.OsContext.Session["ContactManager.ListNavigation_RememberStartIndices"]), (((Functions.rssextensionhttprequesthandler_ActionGetPageName(heContext) + ":") + localVars.inParamListWidget) + ";"), "");
                        // RememberStartIndex?
                        if ((localVars.inParamRememberStartIndex))
                        {
                            // SetRememberStartIndex
                            // ListNavigation_RememberStartIndices = ListNavigation_RememberStartIndices + GetPageName() + ":" + ListWidget + ";"
                            Global.App.OsContext.Session["ContactManager.ListNavigation_RememberStartIndices"] = ((((((string)Global.App.OsContext.Session["ContactManager.ListNavigation_RememberStartIndices"]) + Functions.rssextensionhttprequesthandler_ActionGetPageName(heContext)) + ":") + localVars.inParamListWidget) + ";");
                        }
                    }
                }
            }             // try

            finally {
                outParamStartIndex = result.outParamStartIndex;
            }
        }
        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);
        }
Esempio n. 9
0
        public bool HandleException(ref LocalState flowState)
        {
            Exception ex = Server.GetLastError();

            if (ex is LicensingException)
            {
                return(true);
            }

            HeContext heContext = Global.App.OsContext;
            string    errorKey  = "ContactManager.Private" + ex.GetType().ToString();

            if (heContext.VisitedExceptionHandlerFlows.Contains(errorKey))
            {
                return(false);
            }
            heContext.VisitedExceptionHandlerFlows.Add(errorKey);

            if (heContext.Session.EntryPoint == null)
            {
                heContext.Session.EntryPoint = HeContext.UnknownEntryPoint;
            }
            while (ex != null)
            {
                if (ex is System.Threading.ThreadAbortException)
                {
                    return(true);
                }
                ex = ex.InnerException;
            }
            ex = Server.GetLastError();
            if (ex is System.Reflection.TargetInvocationException)
            {
                ex = ex.InnerException;
            }

            heContext.Session["ExceptionMessage"] = ex.Message;

            heContext.Session[BuiltInFunction.ExceptionURLSessionName] = BuiltInFunction.GetBookmarkableURL();
            Response.Clear();

            if (isEmailScreen)
            {
                ErrorLog.LogApplicationError(ex, heContext, "");
                return(true);
            }

            if (heContext.CanUseCustomErrorHandler(ex))
            {
                return(new ssContactManager.Flows.FlowCommon.ExceptionHandler(page, isEmailScreen).HandleException());
            }
            DatabaseAccess.FreeupResources(false);

            Server.Transfer("_WebErrorPage.aspx");
            return(true);
        }
 public Activity(IDataReader reader)
 {
     Id        = reader.SafeGet <int>("ID");
     Label     = reader.SafeGet <string>("LABEL", String.Empty);
     LabelLang = reader.SafeGet <string>("LABEL_LANG", String.Empty);
     Details   = reader.SafeGet <string>("INBOX_DETAIL", String.Empty);
     DueDate   = reader.SafeGet <DateTime>("DUE_DATE", BuiltInFunction.NullDate());
     IsOpened  = reader.SafeGet <bool>("OPENED");
     IsSeen    = reader.SafeGet <bool>("SEEN");
 }
Esempio n. 11
0
        /// <summary>
        /// Add properties to the validator that will go to the Page_Validators array
        /// </summary>
        /// <param name="properties"></param>
        protected virtual void addValidatorDeclarationProperties(NameValueCollection properties)
        {
            if (controlToValidate != null)
            {
                properties.Add("controltovalidate", controlToValidate.ClientID);
            }

            properties.Add("evaluationfunction", evaluationFunction);
            properties.Add("errormessage", BuiltInFunction.EncodeHtml(Attributes["ErrorMessage"]));
        }
Esempio n. 12
0
 public bool if_wt_If3()
 {
     if (if_wt_If3_hasRun)
     {
         if_wt_If3_hasRun = false;
         return(if_wt_If3_evalResult);
     }
     if_wt_If3_hasRun     = true;
     if_wt_If3_evalResult = (BuiltInFunction.GetPersonalAreaName() == "");
     return(if_wt_If3_evalResult);
 }
Esempio n. 13
0
        public static int GetNextHumanActivity(HeContext heContext, Transaction tran, IEnumerable <Pair <int, ActivityKind> > nextActivities, int userId)
        {
            var humanActivitiesIds = nextActivities.Where(pair => pair.Second == ActivityKind.HumanActivity)
                                     .Select(pair => pair.First);

            if (!humanActivitiesIds.IsEmpty())
            {
                return(BPMRuntime.GetAllowedActivities(heContext, tran, humanActivitiesIds, userId).FirstIfSingleOrDefault());
            }
            return(BuiltInFunction.NullIdentifier());
        }
Esempio n. 14
0
        public static bool IsRunnableActivity(DateTime isRunningSince, ActivityStatus?forInitialStatus, ActivityStatus currentStatus, DateTime previousNextRun, DateTime nextRun)
        {
            //#605602 - Ensure the activity is not already running "isRunningSince"
            //Ensure the conditions that made the scheduler request the activity to run have not changed. "currentStatus" and "nextRun"
            bool runnable = (isRunningSince == BuiltInFunction.NullDate()) &&
                            (!forInitialStatus.HasValue || forInitialStatus.Value == currentStatus) &&
                            (previousNextRun == BuiltInFunction.NullDate() ||
                             //#1188860 - To avoid issues with daylight saving time, use universal time to compare the two date times
                             (Math.Abs((previousNextRun.ToUniversalTime() - nextRun.ToUniversalTime()).TotalMilliseconds) < 1));

            return(runnable);
        }
        public override void OnPostback()
        {
            int index;

            int.TryParse(BuiltInFunction.NotifyWidgetGetMessage(), out index);
            var iterator = (IRepeaterControl)getIterator();

            if (iterator != null)
            {
                iterator.CurrentIndex = index;
            }
        }
Esempio n. 16
0
        public string GetInlineAttributes()
        {
            var attributes = new StringBuilder();

            foreach (string attribute in Attributes.Keys)
            {
                if (!attribute.IsOneOf("anonymous", "style"))
                {
                    // #1019618 #SWAT-125 - escape not only the single quote but also all characters to avoid poorly generated HTML
                    var escapedAttribute = BuiltInFunction.EncodeHtmlAttribute(Attributes[attribute]);
                    attributes.Append(attribute + "='" + escapedAttribute + "' ");
                }
            }
            return(attributes.ToString());
        }
        public int ExecuteProcessDefEvent(string ssKey, int tenantId, string dataId)
        {
            int processId = 0;

            bool res = false;

            res = ExecuteWebService("ProcessImplicitLaunch",
                                    delegate(HeContext heContext) {
                return(ExecuteProcessWebService(heContext, ssKey, tenantId, 0, string.Empty,
                                                delegate(IProcess execObj) {
                    execObj.ProcessImplicitLaunch(heContext, dataId, out processId);
                }));
            }
                                    ,
                                    false);

            return(res ? processId: BuiltInFunction.NullIdentifier());
        }
        private static string _getPropertyGetValue(string property, object key, object value)
        {
            if (value == null)
            {
                return("");
            }

            string           propertyName            = property + "[" + key + "]";
            AbstractCallback valueAsAbstractCallback = value as AbstractCallback;

            if (valueAsAbstractCallback != null)
            {
                return(_getPropertyText(propertyName, valueAsAbstractCallback));
            }

            Type valueAsType = value as Type;

            if (valueAsType != null)
            {
                return(_getPropertyText(propertyName, valueAsType));
            }

            IList valueAsIList = value as IList;

            if (valueAsIList != null)
            {
                return(_getPropertyText(propertyName, valueAsIList));
            }

            // See if value is a dictionary
            Type valueType = value.GetType();
            Type iGenericDictionaryType = typeof(IDictionary <,>);

            if (valueType.IsGenericType && iGenericDictionaryType.IsAssignableFrom(valueType.GetGenericTypeDefinition()))
            {
                MethodInfo getPropertyTextMethod = typeof(CallbackResultStorage).GetMethod("_getPropertyText",
                                                                                           BindingFlags.Static | BindingFlags.NonPublic, null,
                                                                                           new Type[] { typeof(string), iGenericDictionaryType.MakeGenericType(valueType.GetGenericArguments()) }, null);

                getPropertyTextMethod.Invoke(null, new object[] { propertyName, value });
            }

            return(BuiltInFunction.EncodeHtml(value.ToString()));
        }
        /// <summary>
        /// Action <code>Preparation</code> that represents the Service Studio preparation
        ///  <code>Preparation</code> <p> Description: </p>
        /// </summary>
        public void Preparation(HeContext heContext)
        {
            CheckPermissions(heContext);
            RequestTracer perfTracer = heContext.RequestTracer; perfTracer.RegisterAction("1014d26c-abd5-4d61-a920-4895012b921b.#Preparation", "List_Counter.Preparation");

            try {
                if (heContext != null && heContext.RequestTracer != null)
                {
                    heContext.RequestTracer.RegisterInternalCall("bNIUENWrYU2pIEiVASuSGw.#Preparation", "Preparation", "X0RMeX3yYU+0eg2nFEDfaA", "ContactManager");
                }
                // SetValues
                // FirstRecord = StartIndex + 1
                varLcFirstRecord = (inParamStartIndex + 1);
                // LastRecord = TextToInteger
                varLcLastRecord = BuiltInFunction.TextToInteger(Convert.ToString(((((inParamStartIndex + inParamLineCount) < inParamTotalRowCount)) ?((inParamStartIndex + inParamLineCount)):(inParamTotalRowCount))));
            } catch (System.Threading.ThreadAbortException) {
                throw;
            }
        }
Esempio n. 20
0
        protected void AddFunctionHintParameters(FunctionSignature userHint,
                                                 BuiltInFunction builtinHint, Func <Op> opHint)
        {
            if (userHint != null)
            {
                AddDebugParameter("User Function", userHint);
            }

            if (builtinHint != null)
            {
                AddDebugParameter("Builtin Function", builtinHint);
            }

            if (opHint != null)
            {
                Type opType = opHint()?.GetType();
                AddDebugParameter("Op Hint", opType.Name);
            }
        }
Esempio n. 21
0
        private string GetValidatorDeclarationElement()
        {
            NameValueCollection properties = new NameValueCollection();

            addValidatorDeclarationProperties(properties);
            string arrayElement = "";

            foreach (string propertyName in properties.Keys)
            {
                if (arrayElement != String.Empty)
                {
                    arrayElement += ", ";
                }

                arrayElement += propertyName + ": \"" + BuiltInFunction.EncodeJavascript(properties[propertyName])
                                + "\"";
            }
            return("{" + arrayElement + "}");
        }
        /// <summary>
        /// Action <code>ActionPrivate_HashAdd</code> that represents the Service Studio user action
        ///  <code>Private_HashAdd</code> <p> Description: </p>
        /// </summary>
        public static void ActionPrivate_HashAdd(HeContext heContext, string inParamHash, string inParamKey, string inParamValue, out string outParamNewHash)
        {
            lcoPrivate_HashAdd result    = new lcoPrivate_HashAdd();
            lcvPrivate_HashAdd localVars = new lcvPrivate_HashAdd(inParamHash, inParamKey, inParamValue);

            if (heContext != null && heContext.RequestTracer != null)
            {
                heContext.RequestTracer.RegisterInternalCall("wgfzUbyGoU2pz4dHanoeJg", "Private_HashAdd", "X0RMeX3yYU+0eg2nFEDfaA", "ContactManager");
            }
            try {
                // Index
                // Index = Index
                localVars.varLcIndex = BuiltInFunction.IndexSC(localVars.inParamHash, localVars.inParamKey, 0, false, false);
                // Found Key?
                if (((localVars.varLcIndex != (-1))))
                {
                    // Update
                    // Prefix = Substr
                    localVars.varLcPrefix = BuiltInFunction.SubstrSC(localVars.inParamHash, 0, localVars.varLcIndex);
                    // Suffix = Substr
                    localVars.varLcSuffix = BuiltInFunction.SubstrSC(localVars.inParamHash, ((localVars.varLcIndex + BuiltInFunction.LengthSC(localVars.inParamKey)) + 1), ((BuiltInFunction.LengthSC(localVars.inParamHash) - localVars.varLcIndex) - BuiltInFunction.LengthSC(localVars.inParamKey)));
                    // Suffix = Substr
                    localVars.varLcSuffix = BuiltInFunction.SubstrSC(localVars.varLcSuffix, (BuiltInFunction.IndexSC(localVars.varLcSuffix, ";", 0, false, false) + 1), (BuiltInFunction.LengthSC(localVars.varLcSuffix) - BuiltInFunction.IndexSC(localVars.varLcSuffix, ";", 0, false, false)));
                }
                else
                {
                    // Append
                    // Prefix = Hash
                    localVars.varLcPrefix = localVars.inParamHash;
                    // Suffix = ""
                    localVars.varLcSuffix = "";
                }

                // Update Session
                // NewHash = Prefix + Key + "=" + Value + ";" + Suffix
                result.outParamNewHash = (((((localVars.varLcPrefix + localVars.inParamKey) + "=") + localVars.inParamValue) + ";") + localVars.varLcSuffix);
            }             // try

            finally {
                outParamNewHash = result.outParamNewHash;
            }
        }
        protected override string EntityToTablename(string entity, int tenantId)
        {
            string entityLC = entity.ToLowerInvariant();

            switch (entityLC)
            {
            case "addresstype":
                return(ENAddressTypeEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "address":
                return(ENAddressEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "user":
                return(ENUserEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));

            case "country":
                return(ENCountryEntity.LocalViewName(AppInfo.GetAppInfo().Tenant.Id, BuiltInFunction.GetCurrentLocale()));
            }

            throw new DataBaseException("'" + entity + "' found in 'Expand Inline' parameter is an unknown Entity");
        }
Esempio n. 24
0
        private static byte[] GetDatabaseBinaryAttribute(string id, DbBinaryConfig dbBinaryConfig)
        {
            IDMLIdentifiers         identifiers = null;
            IDatabaseAccessProvider dbAccessProvider;

            if (string.IsNullOrEmpty(dbBinaryConfig.DBConnection))
            {
                dbAccessProvider = DatabaseAccess.ForCurrentDatabase;
                identifiers      = dbAccessProvider.DatabaseServices.DMLService.Identifiers;
            }
            else
            {
                dbAccessProvider = DatabaseAccess.ForDBConnection(dbBinaryConfig.DBConnection);
                identifiers      = dbAccessProvider.DatabaseServices.DMLService.Identifiers;
            }

            using (Transaction trans = dbAccessProvider.GetReadOnlyTransaction()) {
                try {
                    using (Command cmd = trans.CreateCommand(
                               "SELECT " + identifiers.EscapeIdentifier(dbBinaryConfig.Attribute.ToUpper()) + " FROM " +
                               dbBinaryConfig.EntityGetter(null, BuiltInFunction.GetCurrentLocale()) +
                               " WHERE " + identifiers.EscapeIdentifier(dbBinaryConfig.Id.ToUpper()) + " = @ID")) {
                        cmd.CreateParameter("@ID", (DbType)dbBinaryConfig.IdDbType, id);

                        using (IDataReader reader = cmd.ExecuteReader()) {
                            if ((reader.IsClosed) || (!reader.Read()))
                            {
                                return(null);
                            }
                            return(ReadBytes(reader, dbBinaryConfig.Attribute));
                        }
                    }
                } catch (Exception) {
                    return(null);
                }
            }
        }
Esempio n. 25
0
        public static IEnumerable <int> GetAllowedActivities(HeContext heContext, Transaction tran, IEnumerable <int> activityIds, int userId)
        {
            foreach (var nextId in activityIds)
            {
                int            assignedUser;
                ActivityStatus statusId;
                bool           needsPermission = DBRuntimePlatform.Instance.NeedsActivityPermissions(tran, nextId, out assignedUser, out statusId);


                if (assignedUser != BuiltInFunction.NullIdentifier())
                {
                    if (assignedUser != userId)
                    {
                        continue;
                    }
                }
                else
                {
                    if (statusId != ActivityStatus.Ready)
                    {
                        continue;
                    }

                    if (needsPermission)
                    {
                        var roles = DBRuntimePlatform.Instance.GetActivityRoles(tran, nextId);
                        if (!roles.Any(role => GenericExtendedActions.Check(heContext, role.First, userId, role.Second)))
                        {
                            continue;
                        }
                    }
                }

                yield return(nextId);
            }
        }
Esempio n. 26
0
 /// <summary>
 /// Encode URL query parameters, escaping prohibited characters.
 /// </summary>
 /// <param name="urlToEncode">Text to encode.</param>
 /// <returns><code>urlToEncode</code>, appropriately encoded.</returns>
 public static string UrlQueryEncode(String urlToEncode)
 {
     return(BuiltInFunction.EncodeUrl(Uri.UnescapeDataString(urlToEncode.Replace('+', ' '))));
 }
        /// <summary>
        /// Returns (currently not used): 1 if scheduler should retry later; 0 otherwise
        /// </summary>
        /// <param name="heContext"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static int Execute(HeContext heContext, int timeout)
        {
            string   schedule;
            int      cyclicJobId;
            bool     isShared;
            DateTime dbNow, newNextRun;

            int eSpaceId = Global.eSpaceId;
            int tenantId = heContext.AppInfo.Tenant.Id;

            string   errorLogId = "";
            DateTime dbStartTime, lastRun, nextRun, previousNextRun, isRunnSince;
            DateTime localStartedDateTime = DateTime.Now;             // used to measure the timer duration
            DateTime newIsRunningSince, currentIsRunningSince;
            int      duration = 0;
            string   isRunningBy;
            int      numberOfTries      = 0;
            int      maxNumberOfRetries = RuntimePlatformSettings.Timers.NumberOfRetries.GetValue();

            // ExceptionLogged signals that this type of exception has been logged
            bool ExceptionLogged = false;

            try {
                try {
                    using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                        dbStartTime = DBRuntimePlatform.Instance.GetDbDatetime(mainTrans);
                        cyclicJobId = DBRuntimePlatform.Instance.GetCyclicJobId(mainTrans, eSpaceId, tenantId, TimerKey, out isShared);
                    }
                    using (Transaction privTrans = DatabaseAccess.ForRuntimeDatabase.GetCommitableTransaction()) {
                        try {
                            bool ok = DBRuntimePlatform.Instance.GetCyclicJobForUpdate(privTrans, cyclicJobId, isShared, out isRunnSince,
                                                                                       out schedule, out lastRun, out previousNextRun, out isRunningBy);
                            if (!ok)
                            {
                                throw new DataBaseException("Unable to get data for Bootstrap Timer (" + cyclicJobId + ") in Execute method.");
                            }

                            // return if not yet time to execute
                            if (dbStartTime.CompareTo(previousNextRun) < 0)
                            {
                                return(0);
                            }

                            // some node is executing it
                            if (isRunnSince != BuiltInFunction.NullDate())
                            {
                                // In normal cases, it will return from execution because
                                // some other node is executing this timer
                                if (dbStartTime.CompareTo(isRunnSince.AddSeconds(1.2 * timeout)) < 0)
                                {
                                    return(0);
                                }

                                // recover mechanism: if it is executing for too long
                                // maybe there was a problem with the node, but the database
                                // was left with data stating it is still executing.

                                TimeSpan ts;
                                string   recoverDetail = "";
                                try {
                                    string isRunnBy = "?";
                                    ts            = (dbStartTime - isRunnSince);
                                    recoverDetail = "Marked as running since " + isRunnSince.ToString() + " (" + ts.TotalMinutes.ToString() + " minutes) by hubnode '" + isRunnBy + "'. Timeout defined is " + (timeout / 60.0).ToString() + " minutes";
                                } catch {}
                                ErrorLog.LogApplicationError("Recovering timer Bootstrap execution. It is marked as running for too long", recoverDetail, heContext, "");
                            }

                            // lets update db, stating that I'm executing the job
                            numberOfTries = DBRuntimePlatform.Instance.GetNumberOfTries(privTrans, cyclicJobId, isShared);
                            if (numberOfTries >= maxNumberOfRetries)
                            {
                                DBRuntimePlatform.Instance.GetTimerScheduleNextRunAndDbDate(privTrans, cyclicJobId, isShared, out schedule, out dbNow, out newNextRun, out currentIsRunningSince);
                                RuntimeScheduler.NextRun(schedule, dbNow, out nextRun);
                                DBRuntimePlatform.Instance.SetTimerNextRun(privTrans, cyclicJobId, isShared, nextRun);
                                errorLogId = ErrorLog.StaticWrite(DateTime.Now, heContext.Session.SessionID, heContext.AppInfo.eSpaceId, heContext.AppInfo.Tenant.Id, heContext.Session.UserId, String.Format("Timer Bootstrap reached maximum number of retries ({0}) [Calculating next run]", maxNumberOfRetries), "", "");
                                duration   = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                                // lets update the rest of the cyclic job stuff...
                                DBRuntimePlatform.Instance.SetTimerLastRun(privTrans, cyclicJobId, isShared, dbStartTime, duration);

                                CyclicJobLog jobLog = new CyclicJobLog();
                                jobLog.Write(dbStartTime,
                                             duration,
                                             TimerKey,
                                             heContext.AppInfo.eSpaceId,
                                             heContext.AppInfo.Tenant.Id,
                                             RuntimeEnvironment.MachineName,
                                             errorLogId,
                                             previousNextRun,
                                             nextRun,
                                             heContext.AppInfo.eSpaceName,
                                             heContext.AppInfo.ApplicationName,
                                             heContext.AppInfo.ApplicationUIDAsKey,
                                             TimerName);
                                return(0);
                            }
                            DBRuntimePlatform.Instance.SetTimerRunningBy(privTrans, cyclicJobId, isShared, RuntimeEnvironment.MachineName, out newIsRunningSince);
                            DBRuntimePlatform.Instance.IncrementNumberOfTries(privTrans, cyclicJobId, isShared);
                        } finally {
                            privTrans.Commit();
                            // NOTE: Must release and reget the session... the timer action might commit or something!
                        }
                    }
                } catch (Exception e) {
                    duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                    errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (before executing action 'BootstrapContacts'). Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                    ExceptionLogged = true;
                    return(1);                    // assume some error in update, so it will retry later...
                }
                // from tests in framework 1.0, it seems this ScriptTimeout is not working as expected...
                // but it seems in framework 1.1 it works fine (if not in debug mode)
                heContext.Context.Server.ScriptTimeout = timeout;

                try {
                    Actions.ActionBootstrapContacts(heContext);
                } catch (Exception e) {
                    // error in timer action: we must rollback all pending transactions
                    DatabaseAccess.RollbackAllTransactions();
                    using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                        if (!ExceptionLogged)                           // if already logged, don't log the same error
                        {
                            duration = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                            currentIsRunningSince = DBRuntimePlatform.Instance.GetTimerRunningSince(mainTrans, cyclicJobId, isShared);
                            if (currentIsRunningSince != newIsRunningSince)
                            {
                                ErrorLog.LogApplicationError("Timer 'Bootstrap' Running Since Date changed unexpectedly. Expected '" + BuiltInFunction.DateTimeToText(newIsRunningSince) + "' but was '" + BuiltInFunction.DateTimeToText(currentIsRunningSince) + "'.", "", heContext, "");
                            }

                            DBRuntimePlatform.Instance.ClearTimerRunningBy(mainTrans, cyclicJobId, isShared);
                            ExceptionLogged = true;
                            errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (inside action 'BootstrapContacts'). Timer duration = " + duration + " secs:" + e.Message + String.Format(" [retry {0} of {1} scheduled]", numberOfTries + 1, maxNumberOfRetries), e.ToString(), heContext, "");
                            CyclicJobLog jobLog = new CyclicJobLog();
                            jobLog.Write(
                                dbStartTime,
                                duration,
                                TimerKey,
                                heContext.AppInfo.eSpaceId,
                                heContext.AppInfo.Tenant.Id,
                                RuntimeEnvironment.MachineName,
                                errorLogId,
                                previousNextRun,
                                previousNextRun,
                                heContext.AppInfo.eSpaceName,
                                heContext.AppInfo.ApplicationName,
                                heContext.AppInfo.ApplicationUIDAsKey,
                                TimerName);
                            return(0);
                        }
                    }
                }

                using (Transaction mainTrans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                    try {
                        // calculate next run based on current date in db server and also
                        // on scheduler (that may have been changed inside the user action
                        // for example)

                        DBRuntimePlatform.Instance.GetTimerScheduleNextRunAndDbDate(mainTrans, cyclicJobId, isShared, out schedule, out dbNow, out newNextRun, out currentIsRunningSince);

                        RuntimeScheduler.NextRun(schedule, dbNow, out nextRun);

                        if (newNextRun == previousNextRun)
                        {
                            DBRuntimePlatform.Instance.SetTimerNextRun(mainTrans, cyclicJobId, isShared, nextRun);
                        }
                        else
                        {
                            nextRun = newNextRun;
                        }

                        duration = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;

                        if (currentIsRunningSince != newIsRunningSince)
                        {
                            ErrorLog.LogApplicationError("Timer 'Bootstrap' Running Since Date changed unexpectedly. Expected '" + BuiltInFunction.DateTimeToText(newIsRunningSince) + "' but was '" + BuiltInFunction.DateTimeToText(currentIsRunningSince) + "'.", "", heContext, "");
                        }
                        // lets update the rest of the cyclic job stuff...
                        DBRuntimePlatform.Instance.SetTimerLastRun(mainTrans, cyclicJobId, isShared, dbStartTime, duration);
                        DBRuntimePlatform.Instance.ResetNumberOfTries(mainTrans, cyclicJobId, isShared);

                        CyclicJobLog jobLog = new CyclicJobLog();
                        jobLog.Write(
                            dbStartTime,
                            duration,
                            TimerKey,
                            heContext.AppInfo.eSpaceId,
                            heContext.AppInfo.Tenant.Id,
                            RuntimeEnvironment.MachineName,
                            errorLogId,
                            previousNextRun,
                            nextRun,
                            heContext.AppInfo.eSpaceName,
                            heContext.AppInfo.ApplicationName,
                            heContext.AppInfo.ApplicationUIDAsKey,
                            TimerName);
                        return(0);
                    } catch (Exception e) {
                        if (!ExceptionLogged)                           // if already logged, don't log the same error
                        {
                            duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                            errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error (after executing action 'BootstrapContacts'). Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                            ExceptionLogged = true;
                        }
                        return(1);                        // assume some error in update, so it will retry later...
                    }
                }
            } catch (Exception e) {
                if (!ExceptionLogged)                   // if already logged, don't log the same error
                {
                    duration        = (int)((TimeSpan)(DateTime.Now - localStartedDateTime)).TotalSeconds;
                    errorLogId      = ErrorLog.LogApplicationError("Timer Bootstrap error. Timer duration = " + duration + " secs: " + e.Message + " [Will retry later]", e.ToString(), heContext, "");
                    ExceptionLogged = true;
                }
                return(1);
            }
        }
 public void add_function(string function_name, BuiltInFunction function)
 {
     function_lookup.Add(function_name, function);
 }
Esempio n. 29
0
        /// <summary>
        /// Action <code>ActionAddressType_GetOrCreateByLabel</code> that represents the Service Studio user
        ///  action <code>AddressType_GetOrCreateByLabel</code> <p> Description: Gets or creates the addres
        /// s type for that label.</p>
        /// </summary>
        public static void ActionAddressType_GetOrCreateByLabel(HeContext heContext, string inParamLabel, out long outParamAddressTypeId)
        {
            lcoAddressType_GetOrCreateByLabel result    = new lcoAddressType_GetOrCreateByLabel();
            lcvAddressType_GetOrCreateByLabel localVars = new lcvAddressType_GetOrCreateByLabel(inParamLabel);

            try {
                // Query datasetGetAddressTypesByLabel
                int datasetGetAddressTypesByLabel_maxRecords = 0;
                localVars.queryResGetAddressTypesByLabel_outParamList = FuncActionAddressType_GetOrCreateByLabel.datasetGetAddressTypesByLabel(heContext, datasetGetAddressTypesByLabel_maxRecords, IterationMultiplicity.Never, out localVars.queryResGetAddressTypesByLabel_outParamCount, localVars.inParamLabel
                                                                                                                                               );

                // exists?
                if (((!localVars.queryResGetAddressTypesByLabel_outParamList.Empty)))
                {
                    // AddressTypeId = GetAddressTypesByLabel.List.Current.AddressType.Id
                    result.outParamAddressTypeId = localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssId;
                }
                else
                {
                    // set AddressType
                    // GetAddressTypesByLabel.List.Current.AddressType.Label = Label
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssLabel = localVars.inParamLabel;
                    // GetAddressTypesByLabel.List.Current.AddressType.Active = True
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssActive = true;
                    // GetAddressTypesByLabel.List.Current.AddressType.CreatedDate = CurrDateTime
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssCreatedDate = BuiltInFunction.CurrDateTime();
                    // GetAddressTypesByLabel.List.Current.AddressType.CreatedBy = GetUserId
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssCreatedBy = BuiltInFunction.GetUserId();
                    // GetAddressTypesByLabel.List.Current.AddressType.LastUpdatedDate = CurrDateTime
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssLastUpdatedDate = BuiltInFunction.CurrDateTime();
                    // GetAddressTypesByLabel.List.Current.AddressType.LastUpdatedBy = GetUserId
                    localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType.ssLastUpdatedBy = BuiltInFunction.GetUserId();
                    // CreateAddressType
                    ExtendedActions.CreateAddressType(heContext, (((RCAddressTypeRecord)localVars.queryResGetAddressTypesByLabel_outParamList.CurrentRec.ssENAddressType)), out localVars.resCreateAddressType_outParamId);

                    // AddressTypeId = CreateAddressType.Id
                    result.outParamAddressTypeId = localVars.resCreateAddressType_outParamId;
                }
            }             // try

            finally {
                outParamAddressTypeId = result.outParamAddressTypeId;
            }
        }
Esempio n. 30
0
 public static Value invokeBuiltInFunction(BuiltInFunction function, params Value[] arguments)
 {
     return(function.Invoke(new List <Value>(arguments)));
 }