Ejemplo n.º 1
0
        /// <summary>
        /// Creates and caches a Regex object for later use and retrieves it in a later call if it is cacehd
        /// </summary>
        public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexOptions.None, int timeoutSeconds = 2)
        {
            Requires.NotNull("pattern", pattern);
            var key = pattern;

            if ((options & RegexOptions.IgnoreCase) != 0)
            {
                key = (options & RegexOptions.CultureInvariant) != 0
                    ? pattern.ToUpperInvariant()
                    : pattern.ToUpper();
            }

            // // should not allow for compiled dynamic regex object
            options &= ~RegexOptions.Compiled;
            key      = string.Join(":", "REGEX_ITEM", options.ToString("X"), key.GetHashCode().ToString("X"));

            // limit timeout between 1 and 10 seconds
            if (timeoutSeconds < 1)
            {
                timeoutSeconds = 1;
            }
            else if (timeoutSeconds > 10)
            {
                timeoutSeconds = 10;
            }

            var cache = CachingProvider.Instance();
            var regex = cache.GetItem(key) as Regex;

            if (regex == null)
            {
                regex = new Regex(pattern, options & ~RegexOptions.Compiled, TimeSpan.FromSeconds(timeoutSeconds));
                cache.Insert(key, regex, (CORECacheDependency)null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10), CacheItemPriority.BelowNormal, null);
            }

            return(regex);
        }
Ejemplo n.º 2
0
 public void SetEntryInHash <TKey, T>(string hashId, TKey key, T value, ProviderLevel level)
 {
     CachingProvider.Instance(level).SetEntryInHash <TKey, T>(hashId, key, value);
 }
Ejemplo n.º 3
0
 private static void AddJobToCache(ExportImportJob job)
 {
     CachingProvider.Instance().Insert(Util.GetExpImpJobCacheKey(job), job);
 }
Ejemplo n.º 4
0
 public static void RemoveCache(string CacheKey)
 {
     CachingProvider.Instance().Remove(GetDnnCacheKey(CacheKey));
 }
Ejemplo n.º 5
0
 public static void ClearPortalUserCountCache(int portalID)
 {
     CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalID));
 }
Ejemplo n.º 6
0
 public static void ClearPortalCache(int PortalId, bool Cascade)
 {
     CachingProvider.Instance().Clear(Cascade ? "PortalCascade" : "Portal", PortalId.ToString());
 }
Ejemplo n.º 7
0
 public static void ClearFolderCache(int PortalId)
 {
     CachingProvider.Instance().Clear("Folder", PortalId.ToString());
 }
Ejemplo n.º 8
0
 public static object GetPersistentCacheItem(string CacheKey, Type objType)
 {
     return(CachingProvider.Instance().GetPersistentCacheItem(CacheKey, objType));
 }
Ejemplo n.º 9
0
        public override bool IsDuplicate(string mobile1, string mobile2, string tel, string email, string email2, out int contactId, out string info)
        {
            int retVal;

            contactId = 0;
            info      = string.Empty;
            if (!string.IsNullOrEmpty(mobile1))
            {
                retVal = ConvertHelper.ToInt32(CachingProvider.Instance().Get(Constant.NameSystem + mobile1));
                if (retVal != 0)
                {
                    info      = mobile1;
                    contactId = retVal;
                    return(true);
                }
            }
            if (!string.IsNullOrEmpty(mobile2))
            {
                retVal = ConvertHelper.ToInt32(CachingProvider.Instance().Get(Constant.NameSystem + mobile2));
                if (retVal != 0)
                {
                    info      = mobile2;
                    contactId = retVal;
                    return(true);
                }
            }
            if (!string.IsNullOrEmpty(tel))
            {
                retVal = ConvertHelper.ToInt32(CachingProvider.Instance().Get(Constant.NameSystem + tel));
                if (retVal != 0)
                {
                    info      = tel;
                    contactId = retVal;
                    return(true);
                }
            }
            if (!string.IsNullOrEmpty(email))
            {
                retVal = ConvertHelper.ToInt32(CachingProvider.Instance().Get(Constant.NameSystem + email));
                if (retVal != 0)
                {
                    info      = email;
                    contactId = retVal;

                    //Trường hợp trùng email và số đt khác với số đã đăng ký từ trước thì thêm số mới này vào số thứ 2
                    List <PhoneInfo> phone_info = new List <PhoneInfo>();
                    phone_info = PhoneRepository.GetByContact(retVal);
                    if (phone_info.Count == 1)
                    {
                        PhoneInfo phone_info_update = new PhoneInfo();
                        phone_info_update.ContactId   = retVal;
                        phone_info_update.PhoneType   = "2";
                        phone_info_update.IsPrimary   = 1;
                        phone_info_update.PhoneNumber = mobile1;
                        PhoneRepository.Create(phone_info_update);

                        //CachingProvider.Instance().Set(Constant.NameSystem + mobile1, retVal.ToString()); // Them sdt 2 do vào redis
                    }
                    return(true);
                }
            }
            if (!string.IsNullOrEmpty(email2))
            {
                retVal = ConvertHelper.ToInt32(CachingProvider.Instance().Get(Constant.NameSystem + email2));
                if (retVal != 0)
                {
                    info      = email2;
                    contactId = retVal;
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 10
0
 public void RemoveCache(string CacheKey, ProviderLevel level, string Scope = null)
 {
     CachingProvider.Instance(level).Remove(CacheKey, Scope);
 }
Ejemplo n.º 11
0
        public TObject GetCache <TObject>(string CacheKey, string scope = null, ProviderLevel level = ProviderLevel.Normal)
        {
            TObject objObject = CachingProvider.Instance(level).GetItem <TObject>(CacheKey, scope);

            return(objObject);
        }
Ejemplo n.º 12
0
 public bool ExpireItem(string cacheKey, DateTime?expireTime, ProviderLevel level)
 {
     return(CachingProvider.Instance(level).ExpireItem(cacheKey, expireTime));
 }
Ejemplo n.º 13
0
 public List <T> Sort <T>(string collectionKey, string byField, bool fieldIsNumber, int skip, int take, bool isAscending, ProviderLevel level)
 {
     return(CachingProvider.Instance(level).Sort <T>(collectionKey, byField, fieldIsNumber, skip, take, isAscending));
 }
Ejemplo n.º 14
0
 public bool RemoveEntryFromHash <TKey>(string hashId, TKey key, ProviderLevel level)
 {
     return(CachingProvider.Instance(level).RemoveEntryFromHash <TKey>(hashId, key));
 }
Ejemplo n.º 15
0
 public T GetValueFromHash <TKey, T>(string hashId, TKey key, ProviderLevel level)
 {
     return(CachingProvider.Instance(level).GetValueFromHash <TKey, T>(hashId, key));
 }
Ejemplo n.º 16
0
 public static void SetCache(string CacheKey, object objObject, CacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority, CacheItemRemovedCallback OnRemoveCallback, bool PersistAppRestart)
 {
     CachingProvider.Instance().Insert(CacheKey, objObject, null, Cache.NoAbsoluteExpiration, SlidingExpiration, PersistAppRestart);
 }
Ejemplo n.º 17
0
 public static void SetCache(string CacheKey, object objObject, DateTime AbsoluteExpiration, bool PersistAppRestart)
 {
     CachingProvider.Instance().Insert(CacheKey, objObject, null, AbsoluteExpiration, Cache.NoSlidingExpiration, PersistAppRestart);
 }
        public void ProcessRequest(HttpContext context)
        {
            // Validate the request for required inputs, return if no action possible
            if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"]))
            {
                return; // No command we cannot process
            }

            if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"]))
            {
                return; // No action we cannot return
            }

            // Only continue if our provider is current
            if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider))
            {
                return;
            }

            // Get the values, noting that if in debug we are not encrypted
            var command = Host.DebugMode
                ? context.Request.QueryString["command"]
                : UrlUtils.DecryptParameter(context.Request.QueryString["command"], Host.GUID);

            var detail = Host.DebugMode
                ? context.Request.QueryString["detail"]
                : UrlUtils.DecryptParameter(context.Request.QueryString["detail"], Host.GUID);

            // Pass the action on, if the current caching provider is ours
            var provider = (Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)CachingProvider.Instance();

            provider.ProcessSynchronizationRequest(command, detail);
        }
Ejemplo n.º 19
0
 public static void ClearCache(string cachePrefix)
 {
     CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix));
 }
Ejemplo n.º 20
0
        public async Task <PowerBICalendarView> GetScheduleInGroup(string mode)
        {
            var model = (PowerBICalendarView)CachingProvider.Instance().GetItem($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{Thread.CurrentThread.CurrentUICulture.Name}_CalendarDataSet_{mode}");

            if (model != null)
            {
                return(model);
            }

            model = new PowerBICalendarView();
            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                return(null);
            }

            var random  = new Random();
            var colours = new List <string>();

            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = new PowerBIClient(new Uri(Settings.ApiUrl), tokenCredentials))
            {
                if (mode == "-1")
                {
                    //Mode = 0 schedule for all workspaces
                    var pbiSettings = SharedSettingsRepository.Instance.GetSettings(Settings.PortalId);
                    foreach (var s in pbiSettings)
                    {
                        model.Workspaces.Add(s.WorkspaceId);
                    }
                }
                else
                {
                    //Schedule for currect workspace
                    model.Workspaces = new List <string> {
                        Settings.WorkspaceId
                    };
                }

                var groups     = client.Groups.GetGroupsAsync().GetAwaiter().GetResult().Value;
                var capacities = client.Capacities.GetCapacitiesAsync().GetAwaiter().GetResult().Value;


                foreach (var workspace in model.Workspaces)
                {
                    IList <Dataset> datasets;
                    //Get Schedule datasets
                    try
                    {
                        datasets = client.Datasets.GetDatasetsInGroupAsync(Guid.Parse(workspace)).GetAwaiter().GetResult().Value;
                        datasets = CleanUsageDatasets(datasets.ToList());
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn($"Error getting datasets in workspace {workspace}", ex);
                        continue;
                    }


                    var group    = groups.FirstOrDefault(g => g.Id.ToString() == workspace.ToLowerInvariant());
                    var capacity = capacities.FirstOrDefault(c => c.Id == group.CapacityId);


                    for (var x = 0; x < datasets.Count; x++)
                    {
                        var dataset = datasets[x];
                        var color   = String.Format("#{0:X6}", random.Next(0x1000000)); // = "#A197B9"
                        colours.Add(color);

                        try
                        {
                            //Get refreshes history
                            var history = client.Datasets.GetRefreshHistoryAsync(Guid.Parse(Settings.WorkspaceId), dataset.Id, 100).GetAwaiter().GetResult().Value.ToList();

                            foreach (var refresh in history)
                            {
                                model.History.Add(new RefreshedDataset
                                {
                                    Dataset              = dataset.Name,
                                    WorkSpaceName        = group.Name,
                                    CapacityName         = capacity.DisplayName,
                                    StartTime            = refresh.StartTime,
                                    EndTime              = refresh.EndTime,
                                    RefreshType          = refresh.RefreshType,
                                    RequestId            = refresh.RequestId,
                                    ServiceExceptionJson = refresh.ServiceExceptionJson,
                                    Status = refresh.Status
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            // TODO: Getting "UnsupportedMediaType"
                        }
                        try
                        {
                            //Get refresh Schedule by dataset and Workspace
                            var schedule = client.Datasets.GetRefreshScheduleInGroupAsync(Guid.Parse(Settings.WorkspaceId), dataset.Id)
                                           .GetAwaiter().GetResult();
                            var    timeRange = new List <Schedule>();
                            string startHour = schedule.Times[0];
                            string endHour   = schedule.Times[0];

                            //Grouping of consecutive hours
                            for (int i = 0; i < schedule.Times.Count; i++)
                            {
                                if (schedule.Times[i] != schedule.Times.Last())
                                {
                                    DateTime hour = DateTime.ParseExact(schedule.Times[i], "HH:mm",
                                                                        CultureInfo.InvariantCulture);
                                    DateTime nextHour = DateTime.ParseExact(schedule.Times[i + 1], "HH:mm",
                                                                            CultureInfo.InvariantCulture);
                                    if (nextHour.Hour == hour.Hour + 1)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        endHour = hour.AddHours(1).ToString("HH:mm");
                                        timeRange.Add(new Schedule
                                        {
                                            start = startHour,
                                            end   = endHour
                                        });
                                        startHour = schedule.Times[i + 1];
                                        endHour   = schedule.Times[i + 1];
                                    }
                                }
                                else
                                {
                                    endHour = DateTime.ParseExact(schedule.Times[i], "HH:mm",
                                                                  CultureInfo.InvariantCulture).AddHours(1).ToString("HH:mm");
                                    timeRange.Add(new Schedule
                                    {
                                        start = startHour,
                                        end   = endHour
                                    });
                                }
                            }
                            //Create calendar event by each date and hour group
                            for (var index = 0; index < schedule.Days.Count; index++)
                            {
                                var day       = schedule.Days[index];
                                var dayOfWeek = day.GetValueOrDefault().ToInteger();
                                for (var i = 0; i < timeRange.Count; i++)
                                {
                                    var time = timeRange[i];
                                    var id   = Guid.NewGuid().ToString("N");
                                    var item = new CalendarItem
                                    {
                                        id    = id,
                                        color = colours[x < datasets.Count ? x : 0],
                                        start = getCalendarDateTime(dayOfWeek, time.start),
                                        end   = getCalendarDateTime(dayOfWeek, time.end),
                                        title = dataset.Name,
                                    };
                                    item.description = $"Workspace: {group.Name}; Capacity: {capacity.DisplayName}; Dataset: {dataset.Name}; Start: {time.start}";
                                    model.RefreshSchedules.Add(item);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Warn("Error getting refresh schedule by dataset and workspace", e);
                            continue;
                        }
                    }
                }
                //Order history
                model.History = model.History.OrderByDescending(dataset => dataset.StartTime).ToList();

                CachingProvider.Instance().Insert($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{Thread.CurrentThread.CurrentUICulture.Name}_CalendarDataSet_{mode}", model, null, DateTime.Now.AddMinutes(15), TimeSpan.Zero);
            }
            return(model);
        }
Ejemplo n.º 21
0
 public static void ClearModulePermissionsCachesByPortal(int PortalId)
 {
     CachingProvider.Instance().Clear("ModulePermissionsByPortal", PortalId.ToString());
 }
Ejemplo n.º 22
0
        public async Task <EmbedConfig> GetReportEmbedConfigAsync(int userId, string username, string roles, string reportId)
        {
            var model = (EmbedConfig)CachingProvider.Instance().GetItem($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Report_{reportId}");

            if (model != null)
            {
                return(model);
            }

            model = new EmbedConfig();

            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                model.ErrorMessage = "Authentication failed.";
                return(model);
            }

            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = new PowerBIClient(new Uri(Settings.ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var reports = await client.Reports.GetReportsInGroupAsync(Guid.Parse(Settings.WorkspaceId)).ConfigureAwait(false);

                // No reports retrieved for the given workspace.
                if (reports.Value.Count() == 0)
                {
                    model.ErrorMessage = "No reports were found in the workspace";
                }
                var report = reports.Value.FirstOrDefault(r => r.Id.ToString().Equals(reportId, StringComparison.InvariantCultureIgnoreCase));
                if (report == null)
                {
                    model.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid.";
                }

                //Delete bookmarks is report is modified
                CheckBookmarks(report, Settings.PortalId);

                // Generate Embed Token for reports without effective identities.
                GenerateTokenRequest generateTokenRequestParameters;
                // This is how you create embed token with effective identities
                if (!string.IsNullOrWhiteSpace(username))
                {
                    // Check if the dataset has effective identity required
                    // var dataset = await client.Datasets.GetDatasetAsync(report.DatasetId).ConfigureAwait(false);
                    // The line above returns an unauthorization exception when using "Service Principal" credentials. Seems a bug in the PowerBI API.
                    var dataset = client.Datasets.GetDatasets(Guid.Parse(Settings.WorkspaceId)).Value.FirstOrDefault(x => x.Id == report.DatasetId);
                    if (dataset != null &&
                        (dataset.IsEffectiveIdentityRequired.GetValueOrDefault(false) || dataset.IsEffectiveIdentityRolesRequired.GetValueOrDefault(false)) &&
                        !dataset.IsOnPremGatewayRequired.GetValueOrDefault(false))
                    {
                        var rls = new EffectiveIdentity(username, new List <string> {
                            report.DatasetId
                        });
                        if (!string.IsNullOrWhiteSpace(roles) && dataset.IsEffectiveIdentityRolesRequired.GetValueOrDefault(false))
                        {
                            var rolesList = new List <string>();
                            rolesList.AddRange(roles.Split(','));
                            rls.Roles = rolesList;
                        }
                        // Generate Embed Token with effective identities.
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> {
                            rls
                        });
                    }
                    else
                    {
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                    }
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                }
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(Guid.Parse(Settings.WorkspaceId), report.Id, generateTokenRequestParameters).ConfigureAwait(false);

                if (tokenResponse == null)
                {
                    model.ErrorMessage = "Failed to generate embed token.";
                }
                // Generate Embed Configuration.
                model.EmbedToken  = tokenResponse;
                model.EmbedUrl    = report.EmbedUrl;
                model.Id          = report.Id.ToString();
                model.ContentType = "report";

                CachingProvider.Instance().Insert($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Report_{reportId}", model, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero);
            }
            return(model);
        }
Ejemplo n.º 23
0
 public static void ClearTabsCache(int PortalId)
 {
     CachingProvider.Instance().Clear("Tab", PortalId.ToString());
 }
Ejemplo n.º 24
0
        public async Task <EmbedConfig> GetDashboardEmbedConfigAsync(int userId, string username, string roles, string dashboardId)
        {
            var model = (EmbedConfig)CachingProvider.Instance().GetItem($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Dashboard_{dashboardId}");

            if (model != null)
            {
                return(model);
            }

            model = new EmbedConfig();
            // Get token credentials for user
            var getCredentialsResult = await GetTokenCredentials();

            if (!getCredentialsResult)
            {
                // The error message set in GetTokenCredentials
                model.ErrorMessage = "Authentication failed.";
                return(model);
            }

            // Create a Power BI Client object. It will be used to call Power BI APIs.
            using (var client = new PowerBIClient(new Uri(Settings.ApiUrl), tokenCredentials))
            {
                // Get a list of reports.
                var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(Guid.Parse(Settings.WorkspaceId)).ConfigureAwait(false);

                // No dashboards retrieved for the given workspace.
                if (dashboards.Value.Count() == 0)
                {
                    model.ErrorMessage = "No dashboards were found in the workspace";
                }
                var dashboard = dashboards.Value.FirstOrDefault(r => r.Id.ToString().Equals(dashboardId, StringComparison.InvariantCultureIgnoreCase));
                if (dashboard == null)
                {
                    model.ErrorMessage = "No dashboard with the given ID was found in the workspace. Make sure ReportId is valid.";
                }
                // Generate Embed Token for reports without effective identities.
                GenerateTokenRequest generateTokenRequestParameters;
                // This is how you create embed token with effective identities
                if (!string.IsNullOrWhiteSpace(username))
                {
                    var rls = new EffectiveIdentity(username, new List <string> {
                        dashboardId
                    });
                    if (!string.IsNullOrWhiteSpace(roles))
                    {
                        var rolesList = new List <string>();
                        rolesList.AddRange(roles.Split(','));
                        rls.Roles = rolesList;
                    }
                    // Generate Embed Token with effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> {
                        rls
                    });
                }
                else
                {
                    // Generate Embed Token for reports without effective identities.
                    generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                }
                EmbedToken tokenResponse;
                try
                {
                    tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(Guid.Parse(Settings.WorkspaceId), dashboard.Id, generateTokenRequestParameters).ConfigureAwait(false);
                }
                catch (HttpOperationException ex)
                {
                    if (ex.Response.Content.Contains("shouldn't have effective identity"))
                    {
                        // HACK: Creating embed token for accessing dataset shouldn't have effective identity"
                        // See https://community.powerbi.com/t5/Developer/quot-shouldn-t-have-effective-identity-quot-error-when-passing/m-p/437177
                        generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
                        tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(Guid.Parse(Settings.WorkspaceId), dashboard.Id, generateTokenRequestParameters).ConfigureAwait(false);
                    }
                    else
                    {
                        throw;
                    }
                }
                if (tokenResponse == null)
                {
                    model.ErrorMessage = "Failed to generate embed token.";
                }
                // Generate Embed Configuration.
                model.EmbedToken  = tokenResponse;
                model.EmbedUrl    = dashboard.EmbedUrl;
                model.Id          = dashboard.Id.ToString();
                model.ContentType = "dashboard";

                CachingProvider.Instance().Insert($"PBI_{Settings.PortalId}_{Settings.SettingsId}_{userId}_{Thread.CurrentThread.CurrentUICulture.Name}_Dashboard_{dashboardId}", model, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero);
            }
            return(model);
        }
Ejemplo n.º 25
0
 public static object GetCache(string CacheKey)
 {
     return(CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)));
 }
Ejemplo n.º 26
0
 public static void RemovePersistentCacheItem(string CacheKey)
 {
     CachingProvider.Instance().RemovePersistentCacheItem(CacheKey);
 }
Ejemplo n.º 27
0
        //NOTE - While making modifications in this method, developer must refer to call tree in Register.ascx.cs.
        //Especially Validate and CreateUser methods. Register class inherits from UserModuleBase, which also contains bunch of logic.
        //This method can easily be modified to pass passowrd, display name, etc.
        //It is recommended to write unit tests.
        public UserBasicDto Register(RegisterationDetails registerationDetails)
        {
            var portalSettings = registerationDetails.PortalSettings;
            var username       = registerationDetails.UserName;
            var email          = registerationDetails.Email;

            Requires.NotNullOrEmpty("email", email);

            var disallowRegistration = !registerationDetails.IgnoreRegistrationMode &&
                                       ((portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) ||
                                        (portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration));

            if (disallowRegistration)
            {
                throw new Exception(Localization.GetString("RegistrationNotAllowed", Library.Constants.SharedResources));
            }

            //initial creation of the new User object
            var newUser = new UserInfo
            {
                PortalID = portalSettings.PortalId,
                Email    = email
            };

            var cleanUsername = PortalSecurity.Instance.InputFilter(username,
                                                                    PortalSecurity.FilterFlag.NoScripting |
                                                                    PortalSecurity.FilterFlag.NoAngleBrackets |
                                                                    PortalSecurity.FilterFlag.NoMarkup);

            if (!cleanUsername.Equals(username))
            {
                throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
            }

            var valid = UserController.Instance.IsValidUserName(username);

            if (!valid)
            {
                throw new ArgumentException(Localization.GetExceptionMessage("InvalidUserName", "The username specified is invalid."));
            }

            //ensure this user doesn't exist
            if (!string.IsNullOrEmpty(username) && UserController.GetUserByName(portalSettings.PortalId, username) != null)
            {
                throw new Exception(Localization.GetString("RegistrationUsernameAlreadyPresent",
                                                           Library.Constants.SharedResources));
            }

            //set username as email if not specified
            newUser.Username = string.IsNullOrEmpty(username) ? email : username;

            if (!string.IsNullOrEmpty(registerationDetails.Password) && !registerationDetails.RandomPassword)
            {
                newUser.Membership.Password = registerationDetails.Password;
            }
            else
            {
                //Generate a random password for the user
                newUser.Membership.Password = UserController.GeneratePassword();
            }

            newUser.Membership.PasswordConfirm = newUser.Membership.Password;

            //set other profile properties
            newUser.Profile.InitialiseProfile(portalSettings.PortalId);
            newUser.Profile.PreferredLocale   = new Localization().CurrentUICulture;
            newUser.Profile.PreferredTimeZone = portalSettings.TimeZone;

            //derive display name from supplied firstname, lastname or from email
            if (!string.IsNullOrEmpty(registerationDetails.FirstName) &&
                !string.IsNullOrEmpty(registerationDetails.LastName))
            {
                newUser.DisplayName = registerationDetails.FirstName + " " + registerationDetails.LastName;
                newUser.FirstName   = registerationDetails.FirstName;
                newUser.LastName    = registerationDetails.LastName;
            }
            else
            {
                newUser.DisplayName = newUser.Email.Substring(0, newUser.Email.IndexOf("@", StringComparison.Ordinal));
            }

            //read all the user account settings
            var settings = UserController.GetUserSettings(portalSettings.PortalId);

            //Verify Profanity filter
            if (this.GetBoolSetting(settings, "Registration_UseProfanityFilter"))
            {
                var portalSecurity = PortalSecurity.Instance;
                if (!portalSecurity.ValidateInput(newUser.Username, PortalSecurity.FilterFlag.NoProfanity) || !portalSecurity.ValidateInput(newUser.DisplayName, PortalSecurity.FilterFlag.NoProfanity))
                {
                    throw new Exception(Localization.GetString("RegistrationProfanityNotAllowed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Email Address Validation
            var emailValidator = this.GetStringSetting(settings, "Security_EmailValidation");

            if (!string.IsNullOrEmpty(emailValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(emailValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Email);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidEmailUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //Excluded Terms Verification
            var excludeRegex = this.GetExcludeTermsRegex(settings);

            if (!string.IsNullOrEmpty(excludeRegex))
            {
                var regExp  = RegexUtils.GetCachedRegex(excludeRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count > 0)
                {
                    throw new Exception(Localization.GetString("RegistrationExcludedTermsUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //User Name Validation
            var userNameValidator = this.GetStringSetting(settings, "Security_UserNameValidation");

            if (!string.IsNullOrEmpty(userNameValidator))
            {
                var regExp  = RegexUtils.GetCachedRegex(userNameValidator, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                var matches = regExp.Matches(newUser.Username);
                if (matches.Count == 0)
                {
                    throw new Exception(Localization.GetString("RegistrationInvalidUserNameUsed",
                                                               Library.Constants.SharedResources));
                }
            }

            //ensure unique username
            var user = UserController.GetUserByName(portalSettings.PortalId, newUser.Username);

            if (user != null)
            {
                if (this.GetBoolSetting(settings, "Registration_UseEmailAsUserName"))
                {
                    throw new Exception(UserController.GetUserCreateStatus(UserCreateStatus.DuplicateEmail));
                }

                var    i        = 1;
                string userName = null;
                while (user != null)
                {
                    userName = newUser.Username + "0" + i.ToString(CultureInfo.InvariantCulture);
                    user     = UserController.GetUserByName(portalSettings.PortalId, userName);
                    i++;
                }
                newUser.Username = userName;
            }

            //ensure unique display name
            if (this.GetBoolSetting(settings, "Registration_RequireUniqueDisplayName"))
            {
                user = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, newUser.DisplayName);
                if (user != null)
                {
                    var    i           = 1;
                    string displayName = null;
                    while (user != null)
                    {
                        displayName = newUser.DisplayName + " 0" + i.ToString(CultureInfo.InvariantCulture);
                        user        = UserController.Instance.GetUserByDisplayname(portalSettings.PortalId, displayName);
                        i++;
                    }
                    newUser.DisplayName = displayName;
                }
            }

            //Update display name format
            var displaynameFormat = this.GetStringSetting(settings, "Security_DisplayNameFormat");

            if (!string.IsNullOrEmpty(displaynameFormat))
            {
                newUser.UpdateDisplayName(displaynameFormat);
            }

            //membership is approved only for public registration
            newUser.Membership.Approved =
                (registerationDetails.IgnoreRegistrationMode ||
                 portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PublicRegistration) && registerationDetails.Authorize;
            newUser.Membership.PasswordQuestion = registerationDetails.Question;
            newUser.Membership.PasswordAnswer   = registerationDetails.Answer;
            //final creation of user
            var createStatus = UserController.CreateUser(ref newUser, registerationDetails.Notify);

            //clear cache
            if (createStatus == UserCreateStatus.Success)
            {
                CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalSettings.PortalId));
            }

            if (createStatus != UserCreateStatus.Success)
            {
                throw new Exception(UserController.GetUserCreateStatus(createStatus));
            }

            //            if (registerationDetails.IgnoreRegistrationMode)
            //            {
            //                Mail.SendMail(newUser, MessageType.UserRegistrationPublic, portalSettings);
            //                return UserBasicDto.FromUserInfo(newUser);
            //            }

            //send notification to portal administrator of new user registration
            //check the receive notification setting first, but if register type is Private, we will always send the notification email.
            //because the user need administrators to do the approve action so that he can continue use the website.
            if (!registerationDetails.IgnoreRegistrationMode &&
                (portalSettings.EnableRegisterNotification || portalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration))
            {
                Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, portalSettings);
                SendAdminNotification(newUser, portalSettings);
            }

            return(UserBasicDto.FromUserInfo(newUser));
        }
Ejemplo n.º 28
0
 public static void SetCache(string CacheKey, object objObject, CacheDependency objDependency, bool PersistAppRestart)
 {
     CachingProvider.Instance().Insert(CacheKey, objObject, objDependency, PersistAppRestart);
 }
Ejemplo n.º 29
0
 private static void RemoveTokenFromCache(ExportImportJob job)
 {
     CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job));
 }
Ejemplo n.º 30
0
 public static void SetCache(string CacheKey, object objObject, CacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, bool PersistAppRestart)
 {
     CachingProvider.Instance().Insert(CacheKey, objObject, objDependency, AbsoluteExpiration, SlidingExpiration, PersistAppRestart);
 }