public virtual async Task CreateDirectoryAsync(string targetFolder)
        {
            VerifyAccess(targetFolder);
            if (Directory.Exists(targetFolder))
            {
                return;     // avoid exception spam
            }
            int retry = 10; // folder occasionally are in use so we'll just wait a bit

            while (retry > 0)
            {
                try {
                    Directory.CreateDirectory(targetFolder);
                    return;
                } catch (Exception) {
                    if (retry <= 1)
                    {
                        throw;
                    }
                }
                if (YetaWFManager.IsSync())
                {
                    Thread.Sleep(new TimeSpan(0, 0, 0, 0, 50));// wait a while - this is bad, only works because "other" instance has lock
                }
                else
                {
                    await Task.Delay(new TimeSpan(0, 0, 0, 0, 50));// wait a while
                }
                --retry;
            }
        }
Ejemplo n.º 2
0
        public void Register()
        {
            // Get config file
#if MVC6
            string configFile = Startup.GetEnvironmentFile(Path.Combine(YetaWFManager.RootFolderWebProject, Globals.DataFolder), "NLog", "config", Optional: true);
#else
            string configFile = Path.Combine(YetaWFManager.RootFolder, Globals.DataFolder, NLogSettingsFile);
#endif
            if (configFile == null)
            {
                return;
            }

            bool useNlog = YetaWFManager.Syncify <bool>(async() => { // registration is sync by definition (this runs once during startup only)
                return(await FileSystem.FileSystemProvider.FileExistsAsync(configFile));
            });
            if (!useNlog)
            {
                return;
            }

            // register custom target (write to Sql table)
            Target.Register <YetaWFDBTarget>("YetaWFDB");

            LogManager.Configuration = new XmlLoggingConfiguration(configFile);

            MessageFormat = WebConfigHelper.GetValue <string>("YetaWF_Logging", NLogMessageFormat);
            MessageFormat = MessageFormat?.ToLower();
            MessageEvent  = WebConfigHelper.GetValue <bool>("YetaWF_Logging", NLogMessageEvent);

            // get logger
            Logger = NLog.LogManager.GetLogger("YetaWF");
        }
Ejemplo n.º 3
0
            }                                          // File IO

            public LogDataProvider(Dictionary <string, object> options) : base(options)
            {
                LogFile = Path.Combine(BaseFolder, LogfileName);
                YetaWFManager.Syncify(async() =>  // Log is sync by definition
                                      await FileSystem.FileSystemProvider.CreateDirectoryAsync(Path.GetDirectoryName(LogFile))
                                      );
            }
        private async Task <string> GetJSONResponseAsync(string url)
        {
            var http = (HttpWebRequest)WebRequest.Create(new Uri(url));

            http.Accept      = "application/json";
            http.ContentType = "application/json";
            http.Method      = "POST";
            System.Net.WebResponse resp;
            try {
                if (YetaWFManager.IsSync())
                {
                    resp = http.GetResponse();
                }
                else
                {
                    resp = await http.GetResponseAsync();
                }
            } catch (Exception exc) {
                throw new InternalError("An error occurred retrieving exchange rates from openexchangerates.org - {0}", ErrorHandling.FormatExceptionMessage(exc));
            }
            using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) {
                if (YetaWFManager.IsSync())
                {
                    return(sr.ReadToEnd().Trim());
                }
                else
                {
                    return((await sr.ReadToEndAsync()).Trim());
                }
            }
        }
Ejemplo n.º 5
0
 public Model()
 {
     YetaWFManager.Syncify(async() => {  // this is needed during model validation
         ConfigData = await LoginConfigDataProvider.GetConfigAsync();
     });
     TwoStepAuth = new SerializableList <Role>();
 }
Ejemplo n.º 6
0
        public async Task <bool> RemoveItemByIdentityAsync(int id)
        {
            VoiceMailData origData = Auditing.Active ? await GetItemByIdentityAsync(id) : null;

            if (!await DataProvider.RemoveByIdentityAsync(id))
            {
                return(false);
            }

            await SetupClient();

            try {
                if (YetaWFManager.IsSync())
                {
                    RecordingResource.Delete(pathSid: origData.RecordingSid);
                }
                else
                {
                    await RecordingResource.DeleteAsync(pathSid : origData.RecordingSid);
                }
            } catch (Exception) { }

            await Auditing.AddAuditAsync($"{nameof(VoiceMailDataProvider)}.{nameof(RemoveItemByIdentityAsync)}", Dataset, Guid.Empty,
                                         $"Remove Voice Mail Entry {id}",
                                         DataBefore : origData,
                                         DataAfter : null
                                         );

            return(true);
        }
Ejemplo n.º 7
0
            public async Task UnlockAsync()
            {
                for (; Locked;)
                {
                    if (YetaWFManager.IsSync())
                    {
                        if (localLock.Wait(10))
                        {
                            LocalLocked = true;
                        }
                    }
                    else
                    {
                        await localLock.WaitAsync();

                        LocalLocked = true;
                    }
                    if (LocalLocked)
                    {
                        LockKeys.Remove(Key);
                        localLock.Release();
                        LocalLocked = false;
                        Locked      = false;
                        break;
                    }
                    if (YetaWFManager.IsSync())
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 0, 0, 25));// wait a while - this is bad, only works because "other" instance has lock
                    }
                    else
                    {
                        await Task.Delay(new TimeSpan(0, 0, 0, 0, 25));// wait a while
                    }
                }
            }
Ejemplo n.º 8
0
        /// <summary>
        /// Called when the first node of a multi-instance site is starting up.
        /// </summary>
        public async Task InitializeFirstNodeStartupAsync()
        {
            if (YetaWF.Modules.Caching.Startup.Application.LockProvider != YetaWF.Modules.Caching.Startup.Application.RedisCacheProvider)
            {
                return;
            }
            // this is the first node, so clear all data
            IDatabase db = Redis.GetDatabase();

            string keyPrefix = WebConfigHelper.GetValue(YetaWF.Modules.Caching.Controllers.AreaRegistration.CurrentPackage.AreaName, "RedisKeyPrefix", Application.DefaultRedisKeyPrefix);

            System.Net.EndPoint endPoint = Redis.GetEndPoints().First();
            RedisKey[]          keys     = Redis.GetServer(endPoint).Keys(pattern: $"{keyPrefix}*").ToArray();
            //await db.ExecuteAsync("FLUSHALL");
            foreach (RedisKey key in keys)
            {
                if (!key.ToString().EndsWith(YetaWF.Core.Support.Startup.FirstNodeIndicator))  // don't remove the current first-time startup lock
                {
                    if (YetaWFManager.IsSync())
                    {
                        db.KeyDelete(key);
                    }
                    else
                    {
                        await db.KeyDeleteAsync(key);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            return(Task.CompletedTask);
        }
Ejemplo n.º 10
0
 public async Task UpdateAsync(YetaWFManager manager, ModuleDefinition module)
 {
     FlashImageName_Info = new FlashSelectionInfo(module, FolderGuid, SubFolder)
     {
         AllowUpload = true,
     };
     await FlashImageName_Info.InitAsync();
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Used from site template to add a site admin role
 /// </summary>
 public void AddAdministratorRole()
 {
     YetaWFManager.Syncify(async() => {  // super-rare so sync is OK
         using (RoleDefinitionDataProvider dataProvider = new RoleDefinitionDataProvider()) {
             await dataProvider.AddAdministratorRoleAsync();
         }
     });
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Add a user - used from site template to add a site user
 /// </summary>
 public void AddUser(string name, string pswd)
 {
     YetaWFManager.Syncify(async() => {  // super rare, so sync is OK
         using (UserDefinitionDataProvider dataProvider = new UserDefinitionDataProvider()) {
             await dataProvider.AddUserAsync(name);
         }
         await ChangePasswordAsync(name, pswd);
     });
 }
Ejemplo n.º 13
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddConfigOption(areaName, "UrlArg", UrlArg);

            return(Task.CompletedTask);
        }
Ejemplo n.º 14
0
        public static readonly int MAX_USERS_IN_RESOURCE = 10;// maximum allowed users in a resource definition

        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            //scripts.AddConfigOption(areaName, "MaxUsersInResource", MAX_USERS_IN_RESOURCE);

            return(Task.CompletedTask);
        }
Ejemplo n.º 15
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddVolatileOption(areaName, "DateFormat", UserSettings.GetProperty <Formatting.DateFormatEnum>("DateFormat"));

            return(Task.CompletedTask);
        }
Ejemplo n.º 16
0
            private void AddSearchTerms(string culture, string value, bool allowAnonymous, bool allowAnyUser, int weight)
            {
                YetaWFManager manager      = YetaWFManager.Manager;
                int           siteIdentity = manager.CurrentSite.Identity;

                // remove html tags
                value = reTags.Replace(value, " ");
                value = reWords.Replace(value, " ");
                value = reChars.Replace(value, new MatchEvaluator(substDecimal));
                value = reHex.Replace(value, new MatchEvaluator(substHexadecimal));

                Match m = preRe.Match(value);

                while (m.Success)
                {
                    string token = m.Value.Trim().ToLower();
                    // remove non-word characters from start and end of token
                    for (int len = token.Length; len > 0; --len)
                    {
                        char c = token[0];
                        if (char.IsLetterOrDigit(c))
                        {
                            break;
                        }
                        token = token.Substring(1);
                    }
                    for (int len = token.Length; len > 0; --len)
                    {
                        char c = token[len - 1];
                        if (char.IsLetterOrDigit(c))
                        {
                            break;
                        }
                        token = token.Truncate(len - 1);
                    }
                    if (token.Length > 0 && token.Length < SearchData.MaxSearchTerm && (token.Length >= SmallestMixedToken || (token.Length >= SmallestUpperCaseToken && token.ToUpper() == token)))
                    {
                        SearchData data = (from cd in CurrentSearchData
                                           where cd.SearchTerm == token &&
                                           cd.Language == culture && cd.AllowAnyUser == allowAnyUser && cd.AllowAnonymous == allowAnonymous
                                           select cd).FirstOrDefault();
                        if (data == null)
                        {
                            data = new SearchData()
                            {
                                Language       = culture,
                                SearchTerm     = token,
                                AllowAnyUser   = allowAnyUser,
                                AllowAnonymous = allowAnonymous,
                            };
                            CurrentSearchData.Add(data);
                        }
                        data.Count = data.Count + weight;
                    }
                    m = m.NextMatch();
                }
            }
Ejemplo n.º 17
0
        /// <summary>
        /// Called by the framework so the component can add component specific client-side configuration options and localizations to the page.
        /// </summary>
        /// <param name="manager">The YetaWF.Core.Support.Manager instance of current HTTP request.</param>
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts = manager.ScriptManager;
            string        area    = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddVolatileOption(area, "TimeFormat", YetaWF.Core.Localize.Formatting.GetFormatTimeFormat());

            return(Task.CompletedTask);
        }
Ejemplo n.º 18
0
        public async Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager          scripts  = manager.ScriptManager;
            string                 areaName = AreaRegistration.CurrentPackage.AreaName;
            ControlPanelConfigData config   = await ControlPanelConfigDataProvider.GetConfigAsync();

            scripts.AddConfigOption(areaName, "PageControlMod", PageControlMod);
            scripts.AddConfigOption(areaName, "W3CUrl", config.W3CUrl);
        }
Ejemplo n.º 19
0
 public void WriteToLogFile(string category, Logging.LevelEnum level, int relStack, string text)
 {
     YetaWFManager.Syncify(async() => {  // Logging is sync by definition (this is only used for startup logging)
         using (ILockObject lockObject = await YetaWF.Core.IO.Caching.LockProvider.LockResourceAsync(LogFile)) {
             await FileSystem.FileSystemProvider.AppendAllTextAsync(LogFile, text + "\r\n");
             await lockObject.UnlockAsync();
         }
     });
 }
Ejemplo n.º 20
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddLocalization(areaName, "FmtResult", this.__ResStr("FmtResult", "{0} {1}"));

            return(Task.CompletedTask);
        }
Ejemplo n.º 21
0
        private static async Task AddVisitEntryAsync(string url, string error = null)
        {
            if (!InCallback)
            {
                InCallback = true;

                try {
                    if (!YetaWFManager.HaveManager || !YetaWFManager.Manager.HaveCurrentSite || !YetaWFManager.Manager.HaveCurrentContext)
                    {
                        return;
                    }
                    YetaWFManager manager = YetaWFManager.Manager;

                    using (VisitorEntryDataProvider visitorDP = new VisitorEntryDataProvider()) {
                        if (!visitorDP.Usable)
                        {
                            return;
                        }

                        string userAgent;
                        string sessionId = manager.CurrentSessionId;
                        if (url == null)
                        {
                            url = manager.CurrentRequestUrl;
                        }
#if MVC6
                        userAgent = manager.CurrentRequest.Headers["User-Agent"].ToString();
#else
                        userAgent = manager.CurrentRequest.UserAgent;
#endif
                        string referrer = manager.ReferrerUrl;

                        VisitorEntry visitorEntry = new VisitorEntry {
                            SessionId                         = sessionId,
                            AccessDateTime                    = DateTime.UtcNow,
                            UserId                            = manager.UserId,
                            IPAddress                         = manager.UserHostAddress.Truncate(Globals.MaxIP),
                            Url                               = url != null?url.Truncate(Globals.MaxUrl) : "",
                                                     Referrer = referrer != null?referrer.Truncate(Globals.MaxUrl) : "",
                                                                    UserAgent = userAgent != null?userAgent.Truncate(VisitorEntry.MaxUserAgent) : "",
                                                                                    Longitude     = 0.0f,
                                                                                    Latitude      = 0.0f,
                                                                                    ContinentCode = VisitorEntry.Unknown,
                                                                                    CountryCode   = VisitorEntry.Unknown,
                                                                                    RegionCode    = VisitorEntry.Unknown,
                                                                                    City          = VisitorEntry.Unknown,
                                                                                    Error         = error.Truncate(VisitorEntry.MaxError),
                        };
                        await visitorDP.AddItemAsync(visitorEntry);
                    }
                } catch (Exception) {
                } finally {
                    InCallback = false;
                }
            }
        }
Ejemplo n.º 22
0
        public async Task <bool> IsUserOnline(string user)
        {
            YetaWFManager manager = await this.SetupSignalRAsync();

            using (ConnectionDataProvider connDP = new ConnectionDataProvider()) {
                Connection conn = await connDP.GetEntryAsync(user);

                return(conn != null);
            }
        }
Ejemplo n.º 23
0
        public async Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts = manager.ScriptManager;
            string        area    = AreaRegistration.CurrentPackage.AreaName;

            ConfigData config = await ConfigDataProvider.GetConfigAsync();

            scripts.AddConfigOption(area, "ExcludedPagesCss", config.ExcludedPagesCss);
            scripts.AddConfigOption(area, "IncludedPagesCss", config.IncludedPagesCss);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Called by the framework so the package can add package specific client-side configuration options and localizations to the page.
        /// </summary>
        /// <param name="manager">The YetaWF.Core.Support.Manager instance of current HTTP request.</param>
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            Package       package  = AreaRegistration.CurrentPackage;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddConfigOption(areaName, "LoaderGif", manager.GetCDNUrl(manager.AddOnManager.GetAddOnNamedUrl(package.AreaName, "no-margin-for-errors.com.prettyLoader") + "images/prettyLoader/ajax-loader.gif"));

            return(Task.CompletedTask);
        }
Ejemplo n.º 25
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts  = manager.ScriptManager;
            string        areaName = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddLocalization(areaName, "RemoveStepConfirm", this.__ResStr("removeStepConfirm", "Are you sure you want to remove this step?"));
            scripts.AddLocalization(areaName, "RemoveStepTitle", this.__ResStr("removeStepTitle", "Remove Step"));

            return(Task.CompletedTask);
        }
Ejemplo n.º 26
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         DisposableTracker.RemoveObject(this);
         YetaWFManager.Syncify(async() =>  // Only used if caller forgets to Unlock
                               await UnlockAsync()
                               );
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Called by the framework so the component can add component specific client-side configuration options and localizations to the page.
        /// </summary>
        /// <param name="manager">The YetaWF.Core.Support.Manager instance of current HTTP request.</param>
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts = manager.ScriptManager;

            string area = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddLocalization(area, "CopyToClip", this.__ResStr("copyToClip", "Copied to clipboard"));

            return(Task.CompletedTask);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Called by the framework so the component can add component specific client-side configuration options and localizations to the page.
        /// </summary>
        /// <param name="manager">The YetaWF.Core.Support.Manager instance of current HTTP request.</param>
        public Task AddSupportAsync(YetaWFManager manager)
        {
            ScriptManager scripts = manager.ScriptManager;
            string        area    = AreaRegistration.CurrentPackage.AreaName;

            scripts.AddConfigOption(area, "Localization", manager.CurrentSite.Localization);

            scripts.AddLocalization(area, "Languages", YetaWF.Core.Models.MultiString.LanguageIdList);
            return(Task.CompletedTask);
        }
Ejemplo n.º 29
0
        public Task AddSupportAsync(YetaWFManager manager)
        {
            //ScriptManager scripts = manager.ScriptManager;
            //string areaName = AreaRegistration.CurrentPackage.AreaName;

            //scripts.AddConfigOption(areaName, "something", Something);

            //scripts.AddLocalization(areaName, "something", this.__ResStr("something", "something"));

            return(Task.CompletedTask);
        }
 public Task <int> ReadAsync(byte[] btes, int offset, int length)
 {
     if (YetaWFManager.IsSync())
     {
         return(Task.FromResult(Stream.Read(btes, offset, length)));
     }
     else
     {
         return(Stream.ReadAsync(btes, offset, length));
     }
 }