Ejemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            StaticTest test = new StaticTest();

            test.FileName = txtFileName.Text;
            test.MaxScores = txtMaxScores.Text;
            Variable[] vars = new Variable[dgVars.Rows.Count];
            int cnt = 0;
            foreach (DataGridViewRow dgvr in dgVars.Rows)
            {
                string name = dgvr.Cells[0].Value + "";
                if (!name.Equals(""))
                {
                    vars[cnt] = new Variable();
                    vars[cnt].Name = name;
                    vars[cnt].DataType = dgvr.Cells[1].Value + "";
                    vars[cnt].Score = Int32.Parse(dgvr.Cells[2].Value + "");
                    vars[cnt].ErrMsg = dgvr.Cells[3].Value + "";
                    cnt++;
                }
            }
            test.Vars = vars;
            cnt = 0;
            Statement[] stmts = new Statement[dgStmts.Rows.Count];
            foreach (DataGridViewRow dgvr in dgStmts.Rows)
            {
                string type = dgvr.Cells[0].Value + "";
                if (!type.Equals(""))
                {
                    stmts[cnt] = new Statement();
                    stmts[cnt].Type = type;
                    stmts[cnt].Score = dgvr.Cells[1].Value + "";
                    stmts[cnt].ErrMsg = dgvr.Cells[2].Value + "";
                    cnt++;
                }
            }
            test.Stmts = stmts;
            Exceptions ex = new Exceptions();
            Check []checks = new Check[dgExceptions.Rows.Count];
            cnt = 0;
            foreach (DataGridViewRow dgvr in dgExceptions.Rows)
            {
                string type = dgvr.Cells[0].Value + "";
                if (!type.Equals(""))
                {
                    checks[cnt] = new Check();
                    checks[cnt].Type = type;
                    checks[cnt].Count = dgvr.Cells[1].Value + "";
                    checks[cnt].Statement = dgvr.Cells[2].Value + "";
                    checks[cnt].Score = dgvr.Cells[3].Value + "";
                    checks[cnt].ErrMsg = dgvr.Cells[4].Value + "";
                }
            }
            ex.Checks = checks;
            test.Ex = new Exceptions[] { ex };
            TestSuiteDB.saveStaticTest(test);
            MessageBox.Show("Static Check Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Hide();
        }
Ejemplo n.º 2
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// LoadModuleControl loads the ModuleControl (PortalModuelBase).
        /// </summary>
        private void LoadModuleControl()
        {
            try
            {
                if (this.DisplayContent())
                {
                    // if the module supports caching and caching is enabled for the instance and the user does not have Edit rights or is currently in View mode
                    if (this.SupportsCaching() && IsViewMode(this._moduleConfiguration, this.PortalSettings) && !this.IsVersionRequest())
                    {
                        // attempt to load the cached content
                        this._isCached = this.TryLoadCached();
                    }

                    if (!this._isCached)
                    {
                        // load the control dynamically
                        this._control = this._moduleControlPipeline.LoadModuleControl(this.Page, this._moduleConfiguration);
                    }
                }
                else // content placeholder
                {
                    this._control = this._moduleControlPipeline.CreateModuleControl(this._moduleConfiguration);
                }

                if (this.Skin != null)
                {
                    // check for IMC
                    this.Skin.Communicator.LoadCommunicator(this._control);
                }

                // add module settings
                this.ModuleControl.ModuleContext.Configuration = this._moduleConfiguration;
            }
            catch (ThreadAbortException exc)
            {
                Logger.Debug(exc);

                Thread.ResetAbort();
            }
            catch (Exception exc)
            {
                Logger.Error(exc);

                // add module settings
                this._control = this._moduleControlPipeline.CreateModuleControl(this._moduleConfiguration);
                this.ModuleControl.ModuleContext.Configuration = this._moduleConfiguration;
                if (TabPermissionController.CanAdminPage())
                {
                    // only display the error to page administrators
                    Exceptions.ProcessModuleLoadException(this._control, exc);
                }
                else
                {
                    // Otherwise just log the fact that an exception occurred
                    new ExceptionLogController().AddLog(exc);
                }
            }

            // Enable ViewState
            this._control.ViewStateMode = ViewStateMode.Enabled;
        }
Ejemplo n.º 3
0
 public void Ctor_throws_on_invalid_key_size()
 {
     Exceptions.AssertThrowsInternalError(() => new XChaCha20(new byte[1337], new byte[24]),
                                          "Key must be 32 bytes");
 }
Ejemplo n.º 4
0
        public MemberDocumentation(XElement element)
        {
            List <string> seeAlso = new List <string>();

            this.element = element;
            foreach (XElement node in element.Descendants())
            {
                string    paramName;
                XmlReader reader = node.CreateReader();
                reader.MoveToContent();
                switch (node.Name.ToString())
                {
                case "summary":
                    Check(Summary, "summary");
                    Summary = reader.ReadInnerXml();
                    break;

                case "remarks":
                    Check(Remarks, "remarks");
                    Remarks = reader.ReadInnerXml();
                    break;

                case "returns":
                    Check(Returns, "returns");
                    Returns = reader.ReadInnerXml();
                    break;

                case "value":
                    Check(Value, "value");
                    Value = reader.ReadInnerXml();
                    break;

                case "example":
                    Check(Example, "example");
                    Example = reader.ReadInnerXml();
                    break;

                case "param":
                    paramName = node.GetMemberName();
                    if (Params.ContainsKey(paramName))
                    {
                        Console.WriteLine("found more than one param description for " + paramName + " in " + element.GetMemberName());
                        break;
                    }
                    Params.Add(paramName, reader.ReadInnerXml());
                    break;

                case "typeparam":
                    paramName = node.GetMemberName();
                    if (TypeParams.ContainsKey(paramName))
                    {
                        Console.WriteLine("found more than one typeparam description for " + paramName + " in " + element.GetMemberName());
                        break;
                    }
                    TypeParams.Add(paramName, reader.ReadInnerXml());
                    break;

                case "exception":
                    paramName = node.Find("cref").Value;
                    if (paramName.StartsWith("T:"))
                    {
                        paramName = paramName.Substring(2);
                    }
                    if (Exceptions.ContainsKey(paramName))
                    {
                        Console.WriteLine("found more than one exception description for " + paramName + " in " + element.GetMemberName());
                        break;
                    }
                    Exceptions.Add(paramName, reader.ReadInnerXml());
                    break;

                case "seealso":
                    paramName = node.Find("cref").Value;
                    seeAlso.Add(paramName);
                    break;
                }
            }
            SeeAlso = seeAlso.ToArray();
        }
Ejemplo n.º 5
0
 public CSSimpleType(string name, bool isArray)
 {
     Name = Exceptions.ThrowOnNull(name, "name") + (isArray ? "[]" : "");
 }
        private static void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align)
        {
            try
            {
                DesktopModuleInfo desktopModule;
                if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule))
                {
                    throw new ArgumentException("desktopModuleId");
                }
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
            }

            foreach (ModuleDefinitionInfo objModuleDefinition in
                     ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values)
            {
                var objModule = new ModuleInfo();
                objModule.Initialize(PortalSettings.Current.ActiveTab.PortalID);

                objModule.PortalID    = PortalSettings.Current.ActiveTab.PortalID;
                objModule.TabID       = PortalSettings.Current.ActiveTab.TabID;
                objModule.ModuleOrder = position;
                objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title;
                objModule.PaneName    = paneName;
                objModule.ModuleDefID = objModuleDefinition.ModuleDefID;
                if (objModuleDefinition.DefaultCacheTime > 0)
                {
                    objModule.CacheTime = objModuleDefinition.DefaultCacheTime;
                    if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger)
                    {
                        ModuleInfo defaultModule = ModuleController.Instance.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true);
                        if ((defaultModule != null))
                        {
                            objModule.CacheTime = defaultModule.CacheTime;
                        }
                    }
                }

                ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType);

                if (PortalSettings.Current.ContentLocalizationEnabled)
                {
                    Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId);
                    //check whether original tab is exists, if true then set culture code to default language,
                    //otherwise set culture code to current.
                    if (TabController.Instance.GetTabByCulture(objModule.TabID, PortalSettings.Current.PortalId, defaultLocale) != null)
                    {
                        objModule.CultureCode = defaultLocale.Code;
                    }
                    else
                    {
                        objModule.CultureCode = PortalSettings.Current.CultureCode;
                    }
                }
                else
                {
                    objModule.CultureCode = Null.NullString;
                }
                objModule.AllTabs   = false;
                objModule.Alignment = align;

                ModuleController.Instance.AddModule(objModule);
            }
        }
Ejemplo n.º 7
0
 /// <exclude />
 public override void SetLength(long value)
 {
     throw Exceptions.NotSupported();
 }
 private static DreamMessage Map(Exceptions.BanEmptyException e) {
     return DreamMessage.BadRequest(DekiResources.BANNING_EMPTY_BAN);
 }
Ejemplo n.º 9
0
        protected override void OnLoad(EventArgs e)
        {
            try
            {
                base.OnLoad(e);

                if (IsPostBack)
                {
                    return;
                }

                switch (SettingsRepository.GetMode(ModuleId))
                {
                case DigitalAssestsMode.Group:
                    int groupId;
                    if (string.IsNullOrEmpty(Request["groupId"]) || !int.TryParse(Request["groupId"], out groupId))
                    {
                        Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    var groupFolder = controller.GetGroupFolder(groupId, PortalSettings);
                    if (groupFolder == null)
                    {
                        Skin.AddModuleMessage(this, Localization.GetString("InvalidGroup.Error", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    this.RootFolderViewModel = groupFolder;
                    break;

                case DigitalAssestsMode.User:
                    if (PortalSettings.UserId == Null.NullInteger)
                    {
                        Skin.AddModuleMessage(this, Localization.GetString("InvalidUser.Error", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                        return;
                    }

                    this.RootFolderViewModel = this.controller.GetUserFolder(this.PortalSettings.UserInfo);
                    break;

                default:
                    //handle upgrades where FilterCondition didn't exist
                    SettingsRepository.SetDefaultFilterCondition(ModuleId);
                    this.RootFolderViewModel = this.controller.GetRootFolder(ModuleId);
                    break;
                }

                var initialPath = "";
                int folderId;
                if (int.TryParse(Request["folderId"] ?? DAMState["folderId"], out folderId))
                {
                    var folder = FolderManager.Instance.GetFolder(folderId);
                    if (folder != null && folder.FolderPath.StartsWith(RootFolderViewModel.FolderPath))
                    {
                        initialPath = PathUtils.Instance.RemoveTrailingSlash(folder.FolderPath.Substring(RootFolderViewModel.FolderPath.Length));
                    }
                }

                PageSize   = Request["pageSize"] ?? DAMState["pageSize"] ?? "10";
                ActiveView = Request["view"] ?? DAMState["view"] ?? "gridview";

                Page.DataBind();
                InitializeTreeViews(initialPath);
                InitializeSearchBox();
                InitializeFolderType();
                InitializeGridContextMenu();
                InitializeEmptySpaceContextMenu();

                FolderNameRegExValidator.ErrorMessage         = controller.GetInvalidCharsErrorText();
                FolderNameRegExValidator.ValidationExpression = "^([^" + Regex.Escape(controller.GetInvalidChars()) + "]+)$";
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 10
0
        private void cmdUpdate_Click(object sender, EventArgs e)
        {
            this.Page.Validate("vgEditFolderMapping");

            if (!this.Page.IsValid)
            {
                return;
            }

            try
            {
                var folderMapping = new FolderMappingInfo();

                if (this.FolderMappingID != Null.NullInteger)
                {
                    folderMapping = this._folderMappingController.GetFolderMapping(this.FolderMappingID) ?? new FolderMappingInfo();
                }

                folderMapping.FolderMappingID    = this.FolderMappingID;
                folderMapping.MappingName        = this.NameTextbox.Text;
                folderMapping.FolderProviderType = this.FolderProvidersComboBox.SelectedValue;
                folderMapping.PortalID           = this.FolderPortalID;

                var originalSettings = folderMapping.FolderMappingSettings;

                try
                {
                    var folderMappingID = this.FolderMappingID;

                    if (folderMappingID == Null.NullInteger)
                    {
                        folderMappingID = this._folderMappingController.AddFolderMapping(folderMapping);
                    }
                    else
                    {
                        this._folderMappingController.UpdateFolderMapping(folderMapping);
                    }

                    if (this.ProviderSettingsPlaceHolder.Controls.Count > 0 && this.ProviderSettingsPlaceHolder.Controls[0] is FolderMappingSettingsControlBase)
                    {
                        var settingsControl = (FolderMappingSettingsControlBase)this.ProviderSettingsPlaceHolder.Controls[0];

                        try
                        {
                            settingsControl.UpdateSettings(folderMappingID);
                        }
                        catch
                        {
                            if (this.FolderMappingID == Null.NullInteger)
                            {
                                this._folderMappingController.DeleteFolderMapping(this.FolderPortalID, folderMappingID);
                            }

                            return;
                        }
                    }

                    if (this.FolderMappingID != Null.NullInteger)
                    {
                        // Check if some setting has changed
                        var updatedSettings = this._folderMappingController.GetFolderMappingSettings(this.FolderMappingID);

                        if (originalSettings.Keys.Cast <object>().Any(key => updatedSettings.ContainsKey(key) && !originalSettings[key].ToString().Equals(updatedSettings[key].ToString())))
                        {
                            // Re-synchronize folders using the existing mapping. It's important to synchronize them in descending order
                            var folders = FolderManager.Instance.GetFolders(this.FolderPortalID).Where(f => f.FolderMappingID == this.FolderMappingID).OrderByDescending(f => f.FolderPath);

                            foreach (var folder in folders)
                            {
                                FolderManager.Instance.Synchronize(this.FolderPortalID, folder.FolderPath, false, true);
                            }
                        }
                    }
                }
                catch
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("DuplicateMappingName", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    return;
                }

                if (!this.Response.IsRequestBeingRedirected)
                {
                    this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "FolderMappings", "mid=" + this.ModuleId, "popUp=true"));
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 11
0
        public override void Save(int revisingUserId)
        {
            IDbConnection  newConnection = DataProvider.Instance().GetConnection();
            IDbTransaction trans         = newConnection.BeginTransaction();

            try
            {
                this.SaveInfo(trans, revisingUserId);
                UpdateItem(trans, this.ItemId, this.ModuleId);
                this.UpdateApprovalStatus(trans);

                // update article version now
                // replace <br> with <br />
                AddArticleVersion(
                    trans,
                    this.ItemVersionId,
                    this.ItemId,
                    this.VersionNumber,
                    this.VersionDescription,
                    this.ArticleText.Replace("<br>", "<br />"),
                    this.ReferenceNumber);

                // Save the Relationships
                this.SaveRelationships(trans);

                // Save the ItemVersionSettings
                // SaveItemVersionSettings(trans);
                trans.Commit();
            }
            catch
            {
                trans.Rollback();

                // Rolling back to the original version, exception thrown.
                this.ItemVersionId = this.OriginalItemVersionId;
                throw;
            }
            finally
            {
                // clean up connection stuff
                newConnection.Close();
            }

            this.SaveItemVersionSettings();

            Utility.ClearPublishCache(this.PortalId);

            if (HostController.Instance.GetBoolean(Utility.PublishEnableTags + this.PortalId.ToString(CultureInfo.InvariantCulture), false))
            {
                // Save Tags
                this.SaveTags();
            }

            try
            {
                if (Utility.IsPingEnabledForPortal(this.PortalId))
                {
                    if (this.ApprovalStatusId == ApprovalStatus.Approved.GetId())
                    {
                        string surl = HostController.Instance.GetString(
                            Utility.PublishPingChangedUrl + this.PortalId.ToString(CultureInfo.InvariantCulture));
                        string         changedUrl = Engage.Utility.HasValue(surl) ? surl : Globals.NavigateURL(this.DisplayTabId);
                        PortalSettings ps         = Utility.GetPortalSettings(this.PortalId);

                        // ping
                        Ping.SendPing(ps.PortalName, ps.PortalAlias.ToString(), changedUrl, this.PortalId);
                    }
                }
            }
            catch (Exception exc)
            {
                // WHAT IS THIS? Why try/catch and gooble up errors???
                // this was added because some exceptions occur for ping servers that we don't need to let the users know about.
                // catch the ping exception but let everything else proceed.
                // TODO: localize this error

                Exceptions.LogException(exc);

                // Exceptions.ProcessModuleLoadException(Localize.GetString("PingError", LocalResourceFile), exc);
            }
        }
Ejemplo n.º 12
0
        // Use selected skin's webcontrol skin if one exists
        // or use _default skin's webcontrol skin if one exists
        // or use embedded skin
        public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkinName, string controlName, string webControlSkinSubFolderName)
        {
            PropertyInfo skinProperty = null;
            PropertyInfo enableEmbeddedSkinsProperty = null;
            bool         skinApplied = false;

            try
            {
                skinProperty = telerikControl.GetType().GetProperty("Skin");
                enableEmbeddedSkinsProperty = telerikControl.GetType().GetProperty("EnableEmbeddedSkins");

                if (string.IsNullOrEmpty(controlName))
                {
                    controlName = telerikControl.GetType().BaseType.Name;
                    if (controlName.StartsWith("Rad") || controlName.StartsWith("Dnn"))
                    {
                        controlName = controlName.Substring(3);
                    }
                }

                string skinVirtualFolder = string.Empty;
                if (PortalSettings.Current != null)
                {
                    skinVirtualFolder = PortalSettings.Current.ActiveTab.SkinPath.Replace('\\', '/').Replace("//", "/");
                }
                else
                {
                    skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/skins/_default/Aphelia"); // developer skin Aphelia
                }

                string skinName           = string.Empty;
                string webControlSkinName = string.Empty;
                if (skinProperty != null)
                {
                    var v = skinProperty.GetValue(telerikControl, null);
                    if (v != null)
                    {
                        webControlSkinName = v.ToString();
                    }
                }

                if (string.IsNullOrEmpty(webControlSkinName))
                {
                    webControlSkinName = "default";
                }

                if (skinVirtualFolder.EndsWith("/"))
                {
                    skinVirtualFolder = skinVirtualFolder.Substring(0, skinVirtualFolder.Length - 1);
                }

                int lastIndex = skinVirtualFolder.LastIndexOf("/");
                if (lastIndex > -1 && skinVirtualFolder.Length > lastIndex)
                {
                    skinName = skinVirtualFolder.Substring(skinVirtualFolder.LastIndexOf("/") + 1);
                }

                string systemWebControlSkin = string.Empty;
                if (!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder))
                {
                    systemWebControlSkin = HttpContext.Current.Server.MapPath(skinVirtualFolder);
                    systemWebControlSkin = Path.Combine(systemWebControlSkin, "WebControlSkin");
                    systemWebControlSkin = Path.Combine(systemWebControlSkin, skinName);
                    systemWebControlSkin = Path.Combine(systemWebControlSkin, webControlSkinSubFolderName);
                    systemWebControlSkin = Path.Combine(systemWebControlSkin, string.Format("{0}.{1}.css", controlName, webControlSkinName));

                    // Check if the selected skin has the webcontrol skin
                    if (!File.Exists(systemWebControlSkin))
                    {
                        systemWebControlSkin = string.Empty;
                    }

                    // No skin, try default folder
                    if (string.IsNullOrEmpty(systemWebControlSkin))
                    {
                        skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/Skins/_default");
                        skinName          = "Default";

                        if (skinVirtualFolder.EndsWith("/"))
                        {
                            skinVirtualFolder = skinVirtualFolder.Substring(0, skinVirtualFolder.Length - 1);
                        }

                        if (!string.IsNullOrEmpty(skinName) && !string.IsNullOrEmpty(skinVirtualFolder))
                        {
                            systemWebControlSkin = HttpContext.Current.Server.MapPath(skinVirtualFolder);
                            systemWebControlSkin = Path.Combine(systemWebControlSkin, "WebControlSkin");
                            systemWebControlSkin = Path.Combine(systemWebControlSkin, skinName);
                            systemWebControlSkin = Path.Combine(systemWebControlSkin, webControlSkinSubFolderName);
                            systemWebControlSkin = Path.Combine(systemWebControlSkin, string.Format("{0}.{1}.css", controlName, webControlSkinName));

                            if (!File.Exists(systemWebControlSkin))
                            {
                                systemWebControlSkin = string.Empty;
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(systemWebControlSkin))
                {
                    string filePath = Path.Combine(skinVirtualFolder, "WebControlSkin");
                    filePath = Path.Combine(filePath, skinName);
                    filePath = Path.Combine(filePath, webControlSkinSubFolderName);
                    filePath = Path.Combine(filePath, string.Format("{0}.{1}.css", controlName, webControlSkinName));
                    filePath = filePath.Replace('\\', '/').Replace("//", "/").TrimEnd('/');

                    if (HttpContext.Current != null && HttpContext.Current.Handler is Page)
                    {
                        ClientResourceManager.RegisterStyleSheet(HttpContext.Current.Handler as Page, filePath, FileOrder.Css.ResourceCss);
                    }

                    if ((skinProperty != null) && (enableEmbeddedSkinsProperty != null))
                    {
                        skinApplied = true;
                        skinProperty.SetValue(telerikControl, webControlSkinName, null);
                        enableEmbeddedSkinsProperty.SetValue(telerikControl, false, null);
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
            }

            if (skinProperty != null && enableEmbeddedSkinsProperty != null && !skinApplied)
            {
                if (string.IsNullOrEmpty(fallBackEmbeddedSkinName))
                {
                    fallBackEmbeddedSkinName = "Simple";
                }

                // Set fall back skin Embedded Skin
                skinProperty.SetValue(telerikControl, fallBackEmbeddedSkinName, null);
                enableEmbeddedSkinsProperty.SetValue(telerikControl, true, null);
            }
        }
Ejemplo n.º 13
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Page_Load runs when the page loads
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]   01/31/2008    Created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            chkUseManifest.CheckedChanged += chkUseManifest_CheckedChanged;
            cmdGetFiles.Click             += cmdGetFiles_Click;
            wizPackage.ActiveStepChanged  += wizPackage_ActiveStepChanged;
            wizPackage.CancelButtonClick  += wizPackage_CancelButtonClick;
            wizPackage.FinishButtonClick  += wizPackage_FinishButtonClick;
            wizPackage.NextButtonClick    += wizPackage_NextButtonClick;

            try
            {
                CheckSecurity();

                ctlPackage.EditMode = PropertyEditorMode.View;

                switch (Package.PackageType)
                {
                case "CoreLanguagePack":
                    Package.IconFile = "N\\A";
                    break;

                default:
                    Package.IconFile = Util.ParsePackageIconFileName(Package);
                    break;
                }

                ctlPackage.DataSource = Package;
                ctlPackage.DataBind();

                _Writer = PackageWriterFactory.GetWriter(Package);

                if (Page.IsPostBack)
                {
                    _Writer.BasePath = txtBasePath.Text;
                }
                else
                {
                    txtBasePath.Text = _Writer.BasePath;

                    //Load Manifests
                    if (!string.IsNullOrEmpty(Package.Manifest))
                    {
                        cboManifests.Items.Add(new ListItem("Database version", ""));
                    }
                    string filePath = Server.MapPath(_Writer.BasePath);
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        if (Directory.Exists(filePath))
                        {
                            foreach (string file in Directory.GetFiles(filePath, "*.dnn"))
                            {
                                string fileName = file.Replace(filePath + "\\", "");
                                cboManifests.Items.Add(new ListItem(fileName, fileName));
                            }
                            foreach (string file in Directory.GetFiles(filePath, "*.dnn.resources"))
                            {
                                string fileName = file.Replace(filePath + "\\", "");
                                cboManifests.Items.Add(new ListItem(fileName, fileName));
                            }
                        }
                    }
                    if (cboManifests.Items.Count > 0)
                    {
                        trUseManifest.Visible = true;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 14
0
 /// <exclude />
 public override void Write(byte[] buffer, int offset, int count)
 {
     throw Exceptions.NotSupported();
 }
Ejemplo n.º 15
0
        public virtual bool TryDisplayErrorView(Exception ex, Exceptions.ErrorPage errorPage, int httpStatusCode, bool throwErrorIfAny)
        {
            try
            {
                if (this.ControllerContext == null)
                {
                    throw new ApplicationException("Controller context not set. Be sure to call InitContext on base controller before displaying an error view.");
                }
                string areaName = (RouteData != null && RouteData.DataTokens.ContainsKey("area") ? RouteData.DataTokens["area"].ToString() : null);
                string controllerName = (RouteData != null && RouteData.Values.ContainsKey("controller") ? RouteData.Values["controller"].ToString() : null);
                string actionName = (RouteData != null && RouteData.Values.ContainsKey("action") ? RouteData.Values["action"].ToString() : null);

                if (string.IsNullOrEmpty(areaName))
                {
                    actionName = "(unknown area)";
                }
                if (string.IsNullOrEmpty(controllerName))
                {
                    controllerName = "(unknown controller)";
                }
                if (string.IsNullOrEmpty(actionName))
                {
                    actionName = "(unknown action)";
                }

                string ipAddress = this.Request.UserHostAddress;
                StoreFront currentStoreFrontOrNull = null;
                StoreFrontConfiguration currentStoreFrontConfigOrNull = null;
                _throwErrorIfAnonymous = false;
                _throwErrorIfStoreFrontNotFound = false;
                _throwErrorIfUserProfileNotFound = false;
                _useInactiveStoreFrontAsActive = true;
                _useInactiveStoreFrontConfigAsActive = true;
                try
                {
                    currentStoreFrontOrNull = CurrentStoreFrontOrNull;
                    currentStoreFrontConfigOrNull = CurrentStoreFrontConfigOrNull;
                }
                catch (Exception)
                {
                }

                Response.Clear();
                Response.StatusCode = httpStatusCode;
                string errorPageFileName = errorPage.ErrorPageFileName();
                if (!Enum.IsDefined(typeof(Exceptions.ErrorPage), errorPage))
                {
                    return false;
                }

                string errorViewName = Enum.GetName(typeof(Exceptions.ErrorPage), errorPage);

                if (string.IsNullOrEmpty(Request["NotFound"]) && errorPage == ErrorPage.Error_NotFound && CurrentStoreFrontIdOrNull != null && currentStoreFrontConfigOrNull.NotFoundErrorPage != null && currentStoreFrontConfigOrNull.NotFoundErrorPage.IsActiveBubble())
                {
                    string urlRedirect = currentStoreFrontConfigOrNull.NotFoundErrorPage.UrlResolved(Url) + "?NotFound=1";
                    AddUserMessage("Page Not Found", "Sorry, the URL you were looking for was not found. '" + Request.Url.ToString().ToHtml() + "'", UserMessageType.Danger);
                    new RedirectResult(urlRedirect, false).ExecuteResult(this.ControllerContext);
                    return true;
                }

                if (string.IsNullOrEmpty(Request["StoreError"]) && (errorPage == ErrorPage.Error_AppError || errorPage == ErrorPage.Error_BadRequest || errorPage == ErrorPage.Error_HttpError || errorPage == ErrorPage.Error_InvalidOperation || errorPage == ErrorPage.Error_UnknownError) && CurrentStoreFrontIdOrNull != null && currentStoreFrontConfigOrNull.StoreErrorPage != null && currentStoreFrontConfigOrNull.StoreErrorPage.IsActiveBubble())
                {
                    string urlRedirect = currentStoreFrontConfigOrNull.StoreErrorPage.UrlResolved(Url) + "?StoreError=1";
                    AddUserMessage("Server Error", "Sorry, there was a server error processing your request for URL '" + Request.Url.ToString().ToHtml() + "'", UserMessageType.Danger);
                    new RedirectResult(urlRedirect, false).ExecuteResult(this.ControllerContext);
                    return true;
                }

                GStoreErrorInfo model = new GStoreErrorInfo(errorPage, ex, RouteData, controllerName, actionName, ipAddress, currentStoreFrontOrNull, Request.RawUrl, Request.Url.ToString());
                View(errorViewName, model).ExecuteResult(this.ControllerContext);

                return true;
            }
            catch (Exception exDisplay)
            {
                string message = "Error in Controller Error View."
                    + " \n --Controller: " + this.GetType().FullName
                    + " \n --Url: " + Request.Url.ToString()
                    + " \n --RawUrl: " + Request.RawUrl
                    + " \n --ErrorPage: " + "[" + ((int)errorPage).ToString() + "] " + errorPage.ToString()
                    + " \n --Exception: " + exDisplay.ToString()
                    + " \n --Source: " + exDisplay.Source
                    + " \n --TargetSiteName: " + exDisplay.TargetSite.Name
                    + " \n --StackTrace: " + exDisplay.StackTrace
                    + " \n --Original Exception: " + ex.Message.ToString()
                    + " \n --Original Source: " + ex.Source
                    + " \n --Original TargetSiteName: " + ex.TargetSite.Name
                    + " \n --Original StackTrace: " + ex.StackTrace;

                System.Diagnostics.Trace.WriteLine("--" + message);
                string exceptionMessage = exDisplay.Message;
                string baseExceptionMessage = ex.GetBaseException().Message;
                string baseExceptionToString = ex.GetBaseException().ToString();
                GStoreDb.LogSystemEvent(HttpContext, RouteData, RouteData.ToSourceString(), SystemEventLevel.ApplicationException, message, exceptionMessage, baseExceptionMessage, baseExceptionToString, this);
                if (throwErrorIfAny)
                {
                    throw new ApplicationException(message, exDisplay);
                }
                return false;
            }
        }
 private static DreamMessage Map(Exceptions.ImagePreviewOversizedException e) {
     return DreamMessage.BadRequest(DekiResources.IMAGE_REQUEST_TOO_LARGE);
 }
Ejemplo n.º 17
0
        private void Save()
        {
            try
            {
                // AUM_UrlFormat
                //if (cbURLFormat.Checked)
                //{
                //    DotNetNuke.Entities.Portals.PortalController.UpdatePortalSetting(PortalId, FriendlyUrlSettings.UrlFormatSetting, UrlFormatType.Advanced.ToString().ToLower());
                //}
                //else
                //{
                //    DotNetNuke.Entities.Portals.PortalController.DeletePortalSetting(PortalId, FriendlyUrlSettings.UrlFormatSetting);
                //}

                // AUM_DeletedTabHandlingType
                HostController.Instance.Update(FriendlyUrlSettings.DeletedTabHandlingTypeSetting, rblDeletedTabHandlingType.SelectedValue);

                // AUM_ForceLowerCase
                HostController.Instance.Update(FriendlyUrlSettings.ForceLowerCaseSetting, cbForceLowerCase.Checked.ToString());

                // AUM_PageExtension
                DotNetNuke.Entities.Portals.PortalController.UpdatePortalSetting(PortalId, FriendlyUrlSettings.PageExtensionSetting, txtPageExtension.Text);
                HostController.Instance.Update(FriendlyUrlSettings.PageExtensionSetting, txtPageExtension.Text);

                // AUM_PageExtensionUsage
                if (!cbPageExtensionHandling.Checked)
                {
                    HostController.Instance.Update(FriendlyUrlSettings.PageExtensionUsageSetting, DotNetNuke.Entities.Urls.PageExtensionUsageType.AlwaysUse.ToString());
                }
                else
                {
                    HostController.Instance.Update(FriendlyUrlSettings.PageExtensionUsageSetting, DotNetNuke.Entities.Urls.PageExtensionUsageType.Never.ToString());
                }

                // AUM_RedirectOldProfileUrl
                // AUM_RedirectUnfriendly
                HostController.Instance.Update(FriendlyUrlSettings.RedirectUnfriendlySetting, cbRedirectUnfriendly.Checked.ToString());

                // AUM_ReplaceSpaceWith, // AUM_ReplaceChars, // AUM_ReplaceCharWithChar
                if (cbCharacterReplacement.Checked)
                {
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceSpaceWithSetting, ddlReplaceSpaceWith.SelectedValue);
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceCharsSetting, txtReplaceChars.Text);
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceCharWithCharSetting, txtFindReplaceTheseCharacters.Text);
                }
                else
                {
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceSpaceWithSetting, string.Empty);
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceCharsSetting, string.Empty);
                    HostController.Instance.Update(FriendlyUrlSettings.ReplaceCharWithCharSetting, string.Empty);
                }

                // AUM_RedirectMixedCase
                HostController.Instance.Update(FriendlyUrlSettings.RedirectMixedCaseSetting, cbRedirectMixedCase.Checked.ToString());

                // AUM_SpaceEncodingValue
                HostController.Instance.Update(FriendlyUrlSettings.SpaceEncodingValueSetting, rblSpaceEncodingValue.SelectedValue);

                // AUM_AutoAsciiConvert
                HostController.Instance.Update(FriendlyUrlSettings.AutoAsciiConvertSetting, cbAutoAsciiConvert.Checked.ToString());

                // AUM_CheckForDuplicatedUrls
                HostController.Instance.Update(FriendlyUrlSettings.CheckForDuplicatedUrlsSetting, cbCheckForDuplicatedUrls.Checked.ToString());

                // AUM_FriendlyAdminHostUrls - skip

                // AUM_EnableCustomProviders
                HostController.Instance.Update(FriendlyUrlSettings.EnableCustomProvidersSetting, cbEnableCustomProviders.Checked.ToString());

                // AUM_IgnoreUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.IgnoreRegexSetting, txtIgnoreUrlRegex.Text);

                // AUM_DoNotRewriteRegEx
                HostController.Instance.Update(FriendlyUrlSettings.DoNotRewriteRegExSetting, txtDoNotRewriteRegEx.Text);

                // AUM_SiteUrlsOnlyRegex
                HostController.Instance.Update(FriendlyUrlSettings.SiteUrlsOnlyRegexSetting, txtSiteUrlsOnlyRegex.Text);

                // AUM_DoNotRedirectUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.DoNotRedirectUrlRegexSetting, txtDoNotRedirectUrlRegex.Text);

                // AUM_DoNotRedirectHttpsUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.DoNotRedirectHttpsUrlRegexSetting, txtDoNotRedirectHttpsUrlRegex.Text);

                // AUM_PreventLowerCaseUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.PreventLowerCaseUrlRegexSetting, txtPreventLowerCaseUrlRegex.Text);

                // AUM_DoNotUseFriendlyUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.DoNotUseFriendlyUrlRegexSetting, txtDoNotUseFriendlyUrlRegex.Text);

                // AUM_KeepInQueryStringRegex
                HostController.Instance.Update(FriendlyUrlSettings.KeepInQueryStringRegexSetting, txtKeepInQueryStringRegex.Text);

                // AUM_UrlsWithNoExtensionRegex
                HostController.Instance.Update(FriendlyUrlSettings.UrlsWithNoExtensionRegexSetting, txtUrlsWithNoExtensionRegex.Text);

                // AUM_ValidFriendlyUrlRegex
                HostController.Instance.Update(FriendlyUrlSettings.ValidFriendlyUrlRegexSetting, txtValidFriendlyUrlRegex.Text);

                // AUM_UsePortalDefaultLanguage
                // AUM_AllowDebugCode
                // AUM_LogCacheMessages

                CacheController.FlushFriendlyUrlSettingsFromCache();
                CacheController.FlushPageIndexFromCache();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 18
0
 public CrakenException(Exceptions _id)
 {
     id = (int)_id;
 }
Ejemplo n.º 19
0
        private void LoadSettings()
        {
            try
            {
                var portalController = new PortalController();
                var portal           = portalController.GetPortal(PortalId, SelectedCultureCode);

                //Set up special page lists
                List <TabInfo> listTabs = TabController.GetPortalTabs(TabController.GetTabsBySortOrder(portal.PortalID, SelectedCultureCode, true),
                                                                      Null.NullInteger,
                                                                      true,
                                                                      "<" + Localization.GetString("None_Specified") + ">",
                                                                      true,
                                                                      false,
                                                                      false,
                                                                      false,
                                                                      false);

                var tabs = listTabs.Where(t => t.DisableLink == false).ToList();

                FriendlyUrlSettings fs = new DotNetNuke.Entities.Urls.FriendlyUrlSettings(-1);


                // AUM_UrlFormat
                //cbURLFormat.Checked = (fs.UrlFormat == UrlFormatType.Advanced.ToString().ToLower());

                // AUM_DeletedTabHandlingType
                ListItem liDeletedTabHandling = rblDeletedTabHandlingType.Items.FindByValue(fs.DeletedTabHandlingType.ToString());
                if (liDeletedTabHandling != null)
                {
                    rblDeletedTabHandlingType.ClearSelection();
                    liDeletedTabHandling.Selected = true;
                }

                // AUM_ForceLowerCase
                cbForceLowerCase.Checked = fs.ForceLowerCase;

                // AUM_PageExtension
                txtPageExtension.Text = fs.PageExtension;

                // AUM_PageExtensionUsage - reverse boolean because label is 'hide'
                if (fs.PageExtensionUsageType == DotNetNuke.Entities.Urls.PageExtensionUsageType.AlwaysUse)
                {
                    cbPageExtensionHandling.Checked = false;
                }
                else
                {
                    cbPageExtensionHandling.Checked = true;
                }

                // AUM_RedirectOldProfileUrl - skip

                // AUM_RedirectUnfriendly
                cbRedirectUnfriendly.Checked = fs.RedirectUnfriendly;


                // AUM_ReplaceSpaceWith, // AUM_ReplaceChars , // AUM_ReplaceCharWithChar
                if (fs.ReplaceSpaceWith == FriendlyUrlSettings.ReplaceSpaceWithNothing)
                {
                    cbCharacterReplacement.Checked = false;
                    txtReplaceChars.Text           = fs.ReplaceChars;
                }
                else
                {
                    cbCharacterReplacement.Checked = true;

                    ListItem liReplaceSpaceWith = ddlReplaceSpaceWith.Items.FindByValue(fs.ReplaceSpaceWith);
                    if (liReplaceSpaceWith != null)
                    {
                        liReplaceSpaceWith.Selected = true;
                    }

                    txtReplaceChars.Text = fs.ReplaceChars;
                }
                txtFindReplaceTheseCharacters.Text = DotNetNuke.Entities.Portals.PortalController.GetPortalSetting(FriendlyUrlSettings.ReplaceCharWithCharSetting, PortalId, string.Empty);

                // AUM_RedirectMixedCase
                cbRedirectMixedCase.Checked = fs.RedirectWrongCase;

                // AUM_SpaceEncodingValue
                ListItem liSpaceEncodingValue = rblSpaceEncodingValue.Items.FindByValue(fs.SpaceEncodingValue);
                if (liSpaceEncodingValue != null)
                {
                    rblSpaceEncodingValue.ClearSelection();
                    liSpaceEncodingValue.Selected = true;
                }

                // AUM_AutoAsciiConvert
                cbAutoAsciiConvert.Checked = fs.AutoAsciiConvert;

                // AUM_CheckForDuplicatedUrls
                cbCheckForDuplicatedUrls.Checked = fs.CheckForDuplicateUrls;

                // AUM_FriendlyAdminHostUrls - skip

                // AUM_EnableCustomProviders
                cbEnableCustomProviders.Checked = fs.EnableCustomProviders;


                // AUM_IgnoreUrlRegex
                txtIgnoreUrlRegex.Text = fs.IgnoreRegex;

                // AUM_DoNotRewriteRegEx
                txtDoNotRewriteRegEx.Text = fs.DoNotRewriteRegex;

                // AUM_SiteUrlsOnlyRegex
                txtSiteUrlsOnlyRegex.Text = fs.UseSiteUrlsRegex;

                // AUM_DoNotRedirectUrlRegex
                txtDoNotRedirectUrlRegex.Text = fs.DoNotRedirectRegex;

                // AUM_DoNotRedirectHttpsUrlRegex
                txtDoNotRedirectHttpsUrlRegex.Text = fs.DoNotRedirectSecureRegex;

                // AUM_PreventLowerCaseUrlRegex
                txtPreventLowerCaseUrlRegex.Text = fs.ForceLowerCaseRegex;

                // AUM_DoNotUseFriendlyUrlRegex
                txtDoNotUseFriendlyUrlRegex.Text = fs.NoFriendlyUrlRegex;

                // AUM_KeepInQueryStringRegex
                txtKeepInQueryStringRegex.Text = fs.DoNotIncludeInPathRegex;

                // AUM_UrlsWithNoExtensionRegex
                txtUrlsWithNoExtensionRegex.Text = fs.ValidExtensionlessUrlsRegex;

                // AUM_ValidFriendlyUrlRegex
                txtValidFriendlyUrlRegex.Text = fs.RegexMatch;



                // AUM_UsePortalDefaultLanguage
                // AUM_AllowDebugCode
                // AUM_LogCacheMessages

                CheckPageExtension();
                CheckCharacterReplacement();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Is there more than one site in this group?
            var multipleSites = GetCurrentPortalsGroup().Count() > 1;

            ClientAPI.RegisterClientVariable(Page, "moduleSharing", multipleSites.ToString().ToLowerInvariant(), true);

            ServicesFramework.Instance.RequestAjaxAntiForgerySupport();

            cmdAddModule.Click                += CmdAddModuleClick;
            AddNewModule.CheckedChanged       += AddNewOrExisting_OnClick;
            AddExistingModule.CheckedChanged  += AddNewOrExisting_OnClick;
            SiteList.SelectedIndexChanged     += SiteList_SelectedIndexChanged;
            CategoryList.SelectedIndexChanged += CategoryListSelectedIndexChanged;
            PageLst.SelectedIndexChanged      += PageLstSelectedIndexChanged;
            PaneLst.SelectedIndexChanged      += PaneLstSelectedIndexChanged;
            PositionLst.SelectedIndexChanged  += PositionLstSelectedIndexChanged;

            try
            {
                if ((Visible))
                {
                    cmdAddModule.Enabled      = Enabled;
                    AddExistingModule.Enabled = Enabled;
                    AddNewModule.Enabled      = Enabled;
                    Title.Enabled             = Enabled;
                    PageLst.Enabled           = Enabled;
                    ModuleLst.Enabled         = Enabled;
                    VisibilityLst.Enabled     = Enabled;
                    PaneLst.Enabled           = Enabled;
                    PositionLst.Enabled       = Enabled;
                    PaneModulesLst.Enabled    = Enabled;

                    UserInfo objUser = UserController.Instance.GetCurrentUserInfo();
                    if ((objUser != null))
                    {
                        if (objUser.IsSuperUser)
                        {
                            var objModule = ModuleController.Instance.GetModuleByDefinition(-1, "Extensions");
                            if (objModule != null)
                            {
                                var strURL = Globals.NavigateURL(objModule.TabID, true);
                                hlMoreExtensions.NavigateUrl = strURL + "#moreExtensions";
                            }
                            else
                            {
                                hlMoreExtensions.Enabled = false;
                            }
                            hlMoreExtensions.Text    = GetString("hlMoreExtensions");
                            hlMoreExtensions.Visible = true;
                        }
                    }
                }

                if ((!IsPostBack && Visible && Enabled))
                {
                    AddNewModule.Checked = true;
                    LoadAllLists();
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 21
0
        protected void bSave_Click(object sender, EventArgs e)
        {
            try
            {
                ModuleController mc = new ModuleController();
                if (rblDataSource.SelectedIndex == 0) // this module
                {
                    mc.DeleteModuleSetting(ModuleContext.ModuleId, "tabid");
                    mc.DeleteModuleSetting(ModuleContext.ModuleId, "moduleid");
                }
                else // other module
                {
                    var dsModule = (new ModuleController()).GetTabModule(int.Parse(ddlDataSource.SelectedValue));
                    mc.UpdateModuleSetting(ModuleContext.ModuleId, "tabid", dsModule.TabID.ToString());
                    mc.UpdateModuleSetting(ModuleContext.ModuleId, "moduleid", dsModule.ModuleID.ToString());
                }
                if (rblUseTemplate.SelectedIndex == 0) // existing
                {
                    mc.UpdateModuleSetting(ModuleContext.ModuleId, "template", ddlTemplate.SelectedValue);
                    ModuleContext.Settings["template"] = ddlTemplate.SelectedValue;
                }
                else if (rblUseTemplate.SelectedIndex == 1) // new
                {
                    if (rblFrom.SelectedIndex == 0)         // site
                    {
                        string oldFolder = Server.MapPath(ddlTemplate.SelectedValue);
                        string template  = OpenContentUtils.CopyTemplate(ModuleContext.PortalId, oldFolder, tbTemplateName.Text);
                        mc.UpdateModuleSetting(ModuleContext.ModuleId, "template", template);
                        ModuleContext.Settings["template"] = template;
                    }
                    else if (rblFrom.SelectedIndex == 1) // web
                    {
                        string fileName = ddlTemplate.SelectedValue;
                        string template = OpenContentUtils.ImportFromWeb(ModuleContext.PortalId, fileName, tbTemplateName.Text);
                        mc.UpdateModuleSetting(ModuleContext.ModuleId, "template", template);
                        ModuleContext.Settings["template"] = template;
                    }
                }
                mc.UpdateModuleSetting(ModuleContext.ModuleId, "detailtabid", ddlDetailPage.SelectedValue);


                //don't reset settings. Sure they might be invalid, but maybe not. And you can't ever revert.
                //mc.DeleteModuleSetting(ModuleContext.ModuleId, "data");

                Settings = ModuleContext.OpenContentSettings();
                if (PageRefresh || !Settings.Template.DataNeeded())
                {
                    Response.Redirect(Globals.NavigateURL(), true);
                }
                else
                {
                    rblUseTemplate.SelectedIndex = 0;
                    phTemplateName.Visible       = rblUseTemplate.SelectedIndex == 1;
                    phFrom.Visible        = rblUseTemplate.SelectedIndex == 1;
                    rblFrom.SelectedIndex = 0;
                    BindTemplates(Settings.Template, null);
                    Renderinfo.Template = Settings.Template;
                    BindButtons(Settings, Renderinfo);
                    ActivateDetailPage();
                }
            }
            catch (Exception exc)
            {
                //Module failed to load
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Exceptions ex = (Exceptions)Session["Exception"];

            exception.InnerText = ex.ExceptionMessage;
        }
Ejemplo n.º 23
0
        private void cmdUpdate_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                PortalController.PortalTemplateInfo template = LoadPortalTemplateInfoForSelectedItem();

                try
                {
                    bool   blnChild;
                    string strPortalAlias;
                    string strChildPath  = string.Empty;
                    var    closePopUpStr = string.Empty;

                    //check template validity
                    var    messages       = new ArrayList();
                    string schemaFilename = Server.MapPath(string.Concat(AppRelativeTemplateSourceDirectory, "portal.template.xsd"));
                    string xmlFilename    = template.TemplateFilePath;
                    var    xval           = new PortalTemplateValidator();
                    if (!xval.Validate(xmlFilename, schemaFilename))
                    {
                        UI.Skins.Skin.AddModuleMessage(this, "", String.Format(Localization.GetString("InvalidTemplate", LocalResourceFile), Path.GetFileName(template.TemplateFilePath)), ModuleMessage.ModuleMessageType.RedError);
                        messages.AddRange(xval.Errors);
                        lstResults.Visible    = true;
                        lstResults.DataSource = messages;
                        lstResults.DataBind();
                        validationPanel.Visible = true;
                        return;
                    }

                    //Set Portal Name
                    txtPortalAlias.Text = txtPortalAlias.Text.ToLowerInvariant();
                    txtPortalAlias.Text = txtPortalAlias.Text.Replace("http://", "");

                    //Validate Portal Name
                    if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                    {
                        blnChild       = true;
                        strPortalAlias = txtPortalAlias.Text;
                    }
                    else
                    {
                        blnChild = (optType.SelectedValue == "C");

                        strPortalAlias = blnChild ? PortalController.GetPortalFolder(txtPortalAlias.Text) : txtPortalAlias.Text;
                    }

                    string message = String.Empty;
                    ModuleMessage.ModuleMessageType messageType = ModuleMessage.ModuleMessageType.RedError;
                    if (!PortalAliasController.ValidateAlias(strPortalAlias, blnChild))
                    {
                        message = Localization.GetString("InvalidName", LocalResourceFile);
                    }

                    //check whether have conflict between tab path and portal alias.
                    var checkTabPath = string.Format("//{0}", strPortalAlias);
                    if (TabController.GetTabByTabPath(PortalSettings.PortalId, checkTabPath, string.Empty) != Null.NullInteger ||
                        TabController.GetTabByTabPath(Null.NullInteger, checkTabPath, string.Empty) != Null.NullInteger)
                    {
                        message = Localization.GetString("DuplicateWithTab", LocalResourceFile);
                    }

                    //Validate Password
                    if (txtPassword.Text != txtConfirm.Text)
                    {
                        if (!String.IsNullOrEmpty(message))
                        {
                            message += "<br/>";
                        }
                        message += Localization.GetString("InvalidPassword", LocalResourceFile);
                    }
                    string strServerPath = Globals.GetAbsoluteServerPath(Request);

                    //Set Portal Alias for Child Portals
                    if (String.IsNullOrEmpty(message))
                    {
                        if (blnChild)
                        {
                            strChildPath = strServerPath + strPortalAlias;

                            if (Directory.Exists(strChildPath))
                            {
                                message = Localization.GetString("ChildExists", LocalResourceFile);
                            }
                            else
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    strPortalAlias = Globals.GetDomainName(Request, true) + "/" + strPortalAlias;
                                }
                                else
                                {
                                    strPortalAlias = txtPortalAlias.Text;
                                }
                            }
                        }
                    }

                    //Get Home Directory
                    string homeDir = txtHomeDirectory.Text != @"Portals/[PortalID]" ? txtHomeDirectory.Text : "";

                    //Validate Home Folder
                    if (!string.IsNullOrEmpty(homeDir))
                    {
                        if (string.IsNullOrEmpty(String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, homeDir).Replace("/", "\\")))
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                        if (homeDir.Contains("admin") || homeDir.Contains("DesktopModules") || homeDir.ToLowerInvariant() == "portals/")
                        {
                            message = Localization.GetString("InvalidHomeFolder", LocalResourceFile);
                        }
                    }

                    //Validate Portal Alias
                    if (!string.IsNullOrEmpty(strPortalAlias))
                    {
                        PortalAliasInfo portalAlias = null;
                        foreach (PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values)
                        {
                            if (String.Equals(alias.HTTPAlias, strPortalAlias, StringComparison.InvariantCultureIgnoreCase))
                            {
                                portalAlias = alias;
                                break;
                            }
                        }

                        if (portalAlias != null)
                        {
                            message = Localization.GetString("DuplicatePortalAlias", LocalResourceFile);
                        }
                    }

                    //Create Portal
                    if (String.IsNullOrEmpty(message))
                    {
                        //Attempt to create the portal
                        UserInfo adminUser = new UserInfo();
                        int      intPortalId;
                        try
                        {
                            if (useCurrent.Checked)
                            {
                                adminUser   = UserInfo;
                                intPortalId = PortalController.Instance.CreatePortal(txtPortalName.Text,
                                                                                     adminUser.UserID,
                                                                                     txtDescription.Text,
                                                                                     txtKeyWords.Text,
                                                                                     template,
                                                                                     homeDir,
                                                                                     strPortalAlias,
                                                                                     strServerPath,
                                                                                     strChildPath,
                                                                                     blnChild);
                            }
                            else
                            {
                                adminUser = new UserInfo
                                {
                                    FirstName   = txtFirstName.Text,
                                    LastName    = txtLastName.Text,
                                    Username    = txtUsername.Text,
                                    DisplayName = txtFirstName.Text + " " + txtLastName.Text,
                                    Email       = txtEmail.Text,
                                    IsSuperUser = false,
                                    Membership  =
                                    {
                                        Approved         = true,
                                        Password         = txtPassword.Text,
                                        PasswordQuestion = txtQuestion.Text,
                                        PasswordAnswer   = txtAnswer.Text
                                    },
                                    Profile =
                                    {
                                        FirstName = txtFirstName.Text,
                                        LastName  = txtLastName.Text
                                    }
                                };

                                intPortalId = PortalController.Instance.CreatePortal(txtPortalName.Text,
                                                                                     adminUser,
                                                                                     txtDescription.Text,
                                                                                     txtKeyWords.Text,
                                                                                     template,
                                                                                     homeDir,
                                                                                     strPortalAlias,
                                                                                     strServerPath,
                                                                                     strChildPath,
                                                                                     blnChild);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);

                            intPortalId = Null.NullInteger;
                            message     = ex.Message;

                            TryDeleteCreatingPortal(blnChild ? strChildPath : string.Empty);
                        }

                        if (intPortalId != -1)
                        {
                            //Add new portal to Site Group
                            if (cboSiteGroups.SelectedValue != "-1")
                            {
                                var portal      = PortalController.Instance.GetPortal(intPortalId);
                                var portalGroup = PortalGroupController.Instance.GetPortalGroups().SingleOrDefault(g => g.PortalGroupId == Int32.Parse(cboSiteGroups.SelectedValue));
                                if (portalGroup != null)
                                {
                                    PortalGroupController.Instance.AddPortalToGroup(portal, portalGroup, args => { });
                                }
                            }

                            //Create a Portal Settings object for the new Portal
                            PortalInfo objPortal   = PortalController.Instance.GetPortal(intPortalId);
                            var        newSettings = new PortalSettings {
                                PortalAlias = new PortalAliasInfo {
                                    HTTPAlias = strPortalAlias
                                }, PortalId = intPortalId, DefaultLanguage = objPortal.DefaultLanguage
                            };
                            string webUrl = Globals.AddHTTP(strPortalAlias);
                            try
                            {
                                if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID))
                                {
                                    message = (String.IsNullOrEmpty(PortalSettings.Email) &&
                                               String.IsNullOrEmpty(Host.HostEmail)) ?
                                              string.Format(Localization.GetString("UnknownEmailAddress.Error", LocalResourceFile), message, webUrl, closePopUpStr):
                                              Mail.SendMail(PortalSettings.Email,
                                                            txtEmail.Text,
                                                            string.IsNullOrEmpty(PortalSettings.Email)? Host.HostEmail : string.IsNullOrEmpty(Host.HostEmail)? PortalSettings.Email : PortalSettings.Email + ";" + Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                                else
                                {
                                    message = String.IsNullOrEmpty(Host.HostEmail)?
                                              string.Format(Localization.GetString("UnknownEmailAddress.Error", LocalResourceFile), message, webUrl, closePopUpStr) :
                                              Mail.SendMail(Host.HostEmail,
                                                            txtEmail.Text,
                                                            Host.HostEmail,
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser),
                                                            Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser),
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "",
                                                            "");
                                }
                            }
                            catch (Exception exc)
                            {
                                Logger.Error(exc);

                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("UnknownSendMail.Error", LocalResourceFile), webUrl, closePopUpStr);
                            }
                            EventLogController.Instance.AddLog(PortalController.Instance.GetPortal(intPortalId), PortalSettings, UserId, "", EventLogController.EventLogType.PORTAL_CREATED);

                            // mark default language as published if content localization is enabled
                            bool ContentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", PortalId, false);
                            if (ContentLocalizationEnabled)
                            {
                                LocaleController lc = new LocaleController();
                                lc.PublishLanguage(intPortalId, objPortal.DefaultLanguage, true);
                            }

                            //Redirect to this new site
                            if (message == Null.NullString)
                            {
                                webUrl = (PortalSettings.EnablePopUps) ? UrlUtils.ClosePopUp(true, webUrl, false) : webUrl;
                                Response.Redirect(webUrl, true);
                            }
                            else
                            {
                                closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : "";
                                message       = string.Format(Localization.GetString("SendMail.Error", LocalResourceFile), message, webUrl, closePopUpStr);
                                messageType   = ModuleMessage.ModuleMessageType.YellowWarning;
                            }
                        }
                    }
                    UI.Skins.Skin.AddModuleMessage(this, "", message, messageType);
                }
                catch (Exception exc) //Module failed to load
                {
                    Exceptions.ProcessModuleLoadException(this, exc);
                }
            }
        }
Ejemplo n.º 24
0
 protected override void SetName(string value)
 {
     throw Exceptions.ThrowEFail();
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <remarks>
        /// </remarks>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                //ensure portal signup is allowed
                if ((!IsHostMenu || UserInfo.IsSuperUser == false) && !Host.DemoSignup)
                {
                    Response.Redirect(Globals.NavigateURL("Access Denied"), true);
                }
                valEmail2.ValidationExpression = Globals.glbEmailRegEx;

                //set the async timeout same with script time out
                AJAX.GetScriptManager(Page).AsyncPostBackTimeout = 900;

                if (!Page.IsPostBack)
                {
                    BindTemplates();
                    BindSiteGroups();
                    // load template description
                    cboTemplate_SelectedIndexChanged(null, null);

                    if (UserInfo.IsSuperUser)
                    {
                        rowType.Visible         = true;
                        useCurrentPanel.Visible = true;
                        useCurrent.Checked      = true;
                        adminUserPanel.Visible  = false;

                        optType.SelectedValue = "P";
                    }
                    else
                    {
                        useCurrentPanel.Visible = false;
                        useCurrent.Checked      = false;
                        adminUserPanel.Visible  = true;

                        optType.SelectedValue = "C";

                        txtPortalAlias.Text = Globals.GetDomainName(Request) + @"/";
                        rowType.Visible     = false;
                        string strMessage = string.Format(Localization.GetString("DemoMessage", LocalResourceFile),
                                                          Host.DemoPeriod != Null.NullInteger ? " for " + Host.DemoPeriod + " days" : "",
                                                          Globals.GetDomainName(Request));
                        lblInstructions.Text        = strMessage;
                        lblInstructions.Visible     = true;
                        btnCustomizeHomeDir.Visible = false;
                    }

                    txtHomeDirectory.Text    = @"Portals/[PortalID]";
                    txtHomeDirectory.Enabled = false;
                    if (MembershipProviderConfig.RequiresQuestionAndAnswer)
                    {
                        questionRow.Visible = true;
                        answerRow.Visible   = true;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 26
0
        private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired)
        {
            object objObject = GetCache(cacheItemArgs.CacheKey);

            // if item is not cached
            if (objObject == null)
            {
                //Get Unique Lock for cacheKey
                object @lock = GetUniqueLockObject(cacheItemArgs.CacheKey);

                // prevent other threads from entering this block while we regenerate the cache
                lock (@lock)
                {
                    // try to retrieve object from the cache again (in case another thread loaded the object since we first checked)
                    objObject = GetCache(cacheItemArgs.CacheKey);

                    // if object was still not retrieved

                    if (objObject == null)
                    {
                        // get object from data source using delegate
                        try
                        {
                            objObject = cacheItemExpired(cacheItemArgs);
                        }
                        catch (Exception ex)
                        {
                            objObject = null;
                            Exceptions.LogException(ex);
                        }

                        // set cache timeout
                        int timeOut = cacheItemArgs.CacheTimeOut * Convert.ToInt32(Host.PerformanceSetting);

                        // if we retrieved a valid object and we are using caching
                        if (objObject != null && timeOut > 0)
                        {
                            // save the object in the cache
                            SetCache(cacheItemArgs.CacheKey,
                                     objObject,
                                     cacheItemArgs.CacheDependency,
                                     Cache.NoAbsoluteExpiration,
                                     TimeSpan.FromMinutes(timeOut),
                                     cacheItemArgs.CachePriority,
                                     cacheItemArgs.CacheCallback);

                            // check if the item was actually saved in the cache

                            if (GetCache(cacheItemArgs.CacheKey) == null)
                            {
                                // log the event if the item was not saved in the cache ( likely because we are out of memory )
                                var log = new LogInfo {
                                    LogTypeKey = EventLogController.EventLogType.CACHE_OVERFLOW.ToString()
                                };
                                log.LogProperties.Add(new LogDetailInfo(cacheItemArgs.CacheKey, "Overflow - Item Not Cached"));
                                LogController.Instance.AddLog(log);
                            }
                        }

                        //This thread won so remove unique Lock from collection
                        RemoveUniqueLockObject(cacheItemArgs.CacheKey);
                    }
                }
            }

            return(objObject);
        }
Ejemplo n.º 27
0
        private void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.btnMonth.Visible = false;
                if (this.Settings.MonthAllowed && this.Parent.ID.ToLower() != "eventmonth")
                {
                    this.btnMonth.Visible       = true;
                    this.btnMonth.AlternateText = Localization.GetString("MenuMonth", this.LocalResourceFile);
                    this.btnMonth.ToolTip       = Localization.GetString("MenuMonth", this.LocalResourceFile);
                }
                this.btnWeek.Visible = false;
                if (this.Settings.WeekAllowed && this.Parent.ID.ToLower() != "eventweek")
                {
                    this.btnWeek.Visible       = true;
                    this.btnWeek.AlternateText = Localization.GetString("MenuWeek", this.LocalResourceFile);
                    this.btnWeek.ToolTip       = Localization.GetString("MenuWeek", this.LocalResourceFile);
                }
                this.btnList.Visible = false;
                if (this.Settings.ListAllowed && this.Parent.ID.ToLower() != "eventlist" &&
                    this.Parent.ID.ToLower() != "eventrpt")
                {
                    this.btnList.Visible       = true;
                    this.btnList.AlternateText = Localization.GetString("MenuList", this.LocalResourceFile);
                    this.btnList.ToolTip       = Localization.GetString("MenuList", this.LocalResourceFile);
                }
                this.btnEnroll.Visible = false;
                if (this.Settings.Eventsignup && this.Parent.ID.ToLower() != "eventmyenrollments")
                {
                    this.btnEnroll.Visible       = true;
                    this.btnEnroll.AlternateText = Localization.GetString("MenuMyEnrollments", this.LocalResourceFile);
                    this.btnEnroll.ToolTip       = Localization.GetString("MenuMyEnrollments", this.LocalResourceFile);
                }

                var socialGroupId = this.GetUrlGroupId();
                var groupStr      = "";
                if (socialGroupId > 0)
                {
                    groupStr = "&GroupId=" + socialGroupId;
                }
                var socialUserId = this.GetUrlUserId();

                this.hypiCal.Visible     = this.Settings.IcalOnIconBar;
                this.hypiCal.ToolTip     = Localization.GetString("MenuiCal", this.LocalResourceFile);
                this.hypiCal.NavigateUrl = "~/DesktopModules/Events/EventVCal.aspx?ItemID=0&Mid=" +
                                           Convert.ToString(this.ModuleId) + "&tabid=" + Convert.ToString(this.TabId) +
                                           groupStr;

                this.btnRSS.Visible     = this.Settings.RSSEnable;
                this.btnRSS.ToolTip     = Localization.GetString("MenuRSS", this.LocalResourceFile);
                this.btnRSS.NavigateUrl = "~/DesktopModules/Events/EventRSS.aspx?mid=" +
                                          Convert.ToString(this.ModuleId) + "&tabid=" + Convert.ToString(this.TabId) +
                                          groupStr;
                this.btnRSS.Target = "_blank";

                this.btnAdd.Visible        = false;
                this.btnModerate.Visible   = false;
                this.btnSettings.Visible   = false;
                this.btnCategories.Visible = false;
                this.btnLocations.Visible  = false;
                this.btnSubscribe.Visible  = false;
                this.lblSubscribe.Visible  = false;
                this.imgBar.Visible        = false;

                if (this.Request.IsAuthenticated)
                {
                    var objEventInfoHelper =
                        new EventInfoHelper(this.ModuleId, this.TabId, this.PortalId, this.Settings);

                    //Module Editor.
                    if (this.IsModuleEditor())
                    {
                        this.btnAdd.ToolTip = Localization.GetString("MenuAddEvents", this.LocalResourceFile);
                        if (socialGroupId > 0)
                        {
                            this.btnAdd.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("groupid", socialGroupId.ToString(), "Edit"), "?");
                            this.btnAdd.Visible = true;
                        }
                        else if (socialUserId > 0)
                        {
                            if (socialUserId == this.UserId || this.IsModerator())
                            {
                                this.btnAdd.NavigateUrl =
                                    objEventInfoHelper.AddSkinContainerControls(
                                        this.EditUrl("Userid", socialUserId.ToString(), "Edit"), "?");
                                this.btnAdd.Visible = true;
                            }
                        }
                        else
                        {
                            this.btnAdd.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(this.EditUrl("Edit"), "?");
                            this.btnAdd.Visible = true;
                        }
                    }
                    if (this.Settings.Moderateall &&
                        (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) || this.IsModerator()))
                    {
                        this.btnModerate.Visible       = true;
                        this.btnModerate.AlternateText = Localization.GetString("MenuModerate", this.LocalResourceFile);
                        this.btnModerate.ToolTip       = Localization.GetString("MenuModerate", this.LocalResourceFile);
                    }
                    // Settings Editor.
                    if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) || this.IsSettingsEditor())
                    {
                        this.btnSettings.Visible = true;
                        this.btnSettings.ToolTip = Localization.GetString("MenuSettings", this.LocalResourceFile);
                        if (socialGroupId > 0)
                        {
                            this.btnSettings.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("groupid", socialGroupId.ToString(), "EventSettings"), "?");
                        }
                        else if (socialUserId > 0)
                        {
                            this.btnSettings.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("userid", socialUserId.ToString(), "EventSettings"), "?");
                        }
                        else
                        {
                            this.btnSettings.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(this.EditUrl("EventSettings"), "?");
                        }
                    }
                    // Categories Editor.
                    if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) || this.IsCategoryEditor())
                    {
                        this.btnCategories.Visible = true;
                        this.btnCategories.ToolTip = Localization.GetString("MenuCategories", this.LocalResourceFile);
                        if (socialGroupId > 0)
                        {
                            this.btnCategories.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("groupid", socialGroupId.ToString(), "Categories"), "?");
                        }
                        else if (socialUserId > 0)
                        {
                            this.btnCategories.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("userid", socialUserId.ToString(), "Categories"), "?");
                        }
                        else
                        {
                            this.btnCategories.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(this.EditUrl("Categories"), "?");
                        }
                    }
                    // Locations Editor.
                    if (PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName) || this.IsLocationEditor())
                    {
                        this.btnLocations.Visible = true;
                        this.btnLocations.ToolTip = Localization.GetString("MenuLocations", this.LocalResourceFile);
                        if (socialGroupId > 0)
                        {
                            this.btnLocations.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("groupid", socialGroupId.ToString(), "Locations"), "?");
                        }
                        else if (socialUserId > 0)
                        {
                            this.btnLocations.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(
                                    this.EditUrl("userid", socialUserId.ToString(), "Locations"), "?");
                        }
                        else
                        {
                            this.btnLocations.NavigateUrl =
                                objEventInfoHelper.AddSkinContainerControls(this.EditUrl("Locations"), "?");
                        }
                    }

                    if (this.Settings.Neweventemails == "Subscribe")
                    {
                        this.btnSubscribe.Visible = true;
                        this.lblSubscribe.Visible = true;
                        this.imgBar.Visible       = true;
                        var objEventSubscriptionController = new EventSubscriptionController();
                        var objEventSubscription           =
                            objEventSubscriptionController.EventsSubscriptionGetUser(this.UserId, this.ModuleId);
                        if (ReferenceEquals(objEventSubscription, null))
                        {
                            this.lblSubscribe.Text          = Localization.GetString("lblSubscribe", this.LocalResourceFile);
                            this.btnSubscribe.AlternateText =
                                Localization.GetString("MenuSubscribe", this.LocalResourceFile);
                            this.btnSubscribe.ToolTip =
                                Localization.GetString("MenuTTSubscribe", this.LocalResourceFile);
                            this.btnSubscribe.ImageUrl = IconController.IconURL("Unchecked");
                        }
                        else
                        {
                            this.lblSubscribe.Text          = Localization.GetString("lblUnsubscribe", this.LocalResourceFile);
                            this.btnSubscribe.AlternateText =
                                Localization.GetString("MenuUnsubscribe", this.LocalResourceFile);
                            this.btnSubscribe.ToolTip =
                                Localization.GetString("MenuTTUnsubscribe", this.LocalResourceFile);
                            this.btnSubscribe.ImageUrl = IconController.IconURL("Checked");
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Ejemplo n.º 28
0
 public void Ctor_throws_on_invalid_nonce_size()
 {
     Exceptions.AssertThrowsInternalError(() => new XChaCha20(new byte[32], new byte[1337]),
                                          "Nonce must be 24 bytes");
 }
        public Assignment Assignment_ReadById(int id)
        {
            Assignment assignment = new Assignment();

            try
            {
                SqlCommand cmd = new SqlCommand("Assignment_ReadById", constr);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@AssignmentId", id);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable      dt = new DataTable();
                constr.Open();
                da.Fill(dt);
                constr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    //if(dr["deletedOn"] != null)
                    //{
                    //    assignment.AssignmentId = id;
                    //    assignment.AssignmentName = Convert.ToString(dr["AssignmentName"]);
                    //    assignment.Path = Convert.ToString(dr["Path"]);
                    //    assignment.Type = Convert.ToString(dr["Type"]);
                    //    assignment.FacultyId = Convert.ToInt32(dr["FacultyId"]);
                    //    assignment.createdOn = Convert.ToDateTime(dr["createdOn"]);
                    //    assignment.modifiedOn = Convert.ToDateTime(dr["modifiedOn"]);
                    //    assignment.deletedOn = Convert.ToDateTime(dr["deletedOn"]);
                    //    assignment.isDeleted = Convert.ToBoolean(dr["isDeleted"]);
                    //}
                    //else
                    //{
                    assignment.AssignmentId   = id;
                    assignment.AssignmentName = Convert.ToString(dr["AssignmentName"]);
                    assignment.Path           = Convert.ToString(dr["Path"]);
                    assignment.Type           = Convert.ToString(dr["Type"]);
                    assignment.FacultyId      = Convert.ToInt32(dr["FacultyId"]);
                    assignment.createdOn      = Convert.ToDateTime(dr["createdOn"]);
                    assignment.modifiedOn     = Convert.ToDateTime(dr["modifiedOn"]);
                    assignment.isDeleted      = Convert.ToBoolean(dr["isDeleted"]);
                    //}
                }
            }
            catch (Exception ex)
            {
                Exceptions exception = new Exceptions
                {
                    ExceptionNumber  = ex.HResult.ToString(),
                    ExceptionMessage = ex.Message,
                    ExceptionMethod  = "Assignment_ReadById",
                    ExceptionUrl     = ""
                };
                int r = exceptionrepo.Exception_Create(exception);
                if (r == 0)
                {
                    exceptionrepo.Exception_InsertInLogFile(exception);
                }
                if (constr.State != ConnectionState.Open)
                {
                    constr.Close();
                    constr.Open();
                }
            }
            return(assignment);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Submits the job to reefClient
        /// </summary>
        /// <typeparam name="TMapInput">The type of the side information provided to the Map function</typeparam>
        /// <typeparam name="TMapOutput">The return type of the Map function</typeparam>
        /// <typeparam name="TResult">The return type of the computation.</typeparam>
        /// <param name="jobDefinition">IMRU job definition given by the user</param>
        /// <returns>Null as results will be later written to some directory</returns>
        IEnumerable <TResult> IIMRUClient.Submit <TMapInput, TMapOutput, TResult>(IMRUJobDefinition jobDefinition)
        {
            string         driverId            = string.Format("IMRU-{0}-Driver", jobDefinition.JobName);
            IConfiguration overallPerMapConfig = null;

            try
            {
                overallPerMapConfig = Configurations.Merge(jobDefinition.PerMapConfigGeneratorConfig.ToArray());
            }
            catch (Exception e)
            {
                Exceptions.Throw(e, "Issues in merging PerMapCOnfigGenerator configurations", Logger);
            }

            // The driver configuration contains all the needed bindings.
            var imruDriverConfiguration = TangFactory.GetTang().NewConfigurationBuilder(new[]
            {
                DriverConfiguration.ConfigurationModule
                .Set(DriverConfiguration.OnEvaluatorAllocated,
                     GenericType <IMRUDriver <TMapInput, TMapOutput, TResult> > .Class)
                .Set(DriverConfiguration.OnDriverStarted,
                     GenericType <IMRUDriver <TMapInput, TMapOutput, TResult> > .Class)
                .Set(DriverConfiguration.OnContextActive,
                     GenericType <IMRUDriver <TMapInput, TMapOutput, TResult> > .Class)
                .Set(DriverConfiguration.OnTaskCompleted,
                     GenericType <IMRUDriver <TMapInput, TMapOutput, TResult> > .Class)
                .Set(DriverConfiguration.OnEvaluatorFailed,
                     GenericType <IMRUDriver <TMapInput, TMapOutput, TResult> > .Class)
                .Set(DriverConfiguration.CustomTraceLevel, TraceLevel.Info.ToString())
                .Build(),
                TangFactory.GetTang().NewConfigurationBuilder()
                .BindStringNamedParam <GroupCommConfigurationOptions.DriverId>(driverId)
                .BindStringNamedParam <GroupCommConfigurationOptions.MasterTaskId>(IMRUConstants.UpdateTaskName)
                .BindStringNamedParam <GroupCommConfigurationOptions.GroupName>(IMRUConstants.CommunicationGroupName)
                .BindIntNamedParam <GroupCommConfigurationOptions.FanOut>(
                    IMRUConstants.TreeFanout.ToString(CultureInfo.InvariantCulture)
                    .ToString(CultureInfo.InvariantCulture))
                .BindIntNamedParam <GroupCommConfigurationOptions.NumberOfTasks>(
                    (jobDefinition.NumberOfMappers + 1).ToString(CultureInfo.InvariantCulture))
                .BindImplementation(GenericType <IGroupCommDriver> .Class, GenericType <GroupCommDriver> .Class)
                .Build(),
                jobDefinition.PartitionedDatasetConfiguration,
                overallPerMapConfig
            })
                                          .BindNamedParameter(typeof(SerializedMapConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.MapFunctionConfiguration))
                                          .BindNamedParameter(typeof(SerializedUpdateConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.UpdateFunctionConfiguration))
                                          .BindNamedParameter(typeof(SerializedMapInputCodecConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.MapInputCodecConfiguration))
                                          .BindNamedParameter(typeof(SerializedMapInputPipelineDataConverterConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.MapInputPipelineDataConverterConfiguration))
                                          .BindNamedParameter(typeof(SerializedUpdateFunctionCodecsConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.UpdateFunctionCodecsConfiguration))
                                          .BindNamedParameter(typeof(SerializedMapOutputPipelineDataConverterConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.MapOutputPipelineDataConverterConfiguration))
                                          .BindNamedParameter(typeof(SerializedReduceConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.ReduceFunctionConfiguration))
                                          .BindNamedParameter(typeof(SerializedResultHandlerConfiguration),
                                                              _configurationSerializer.ToString(jobDefinition.ResultHandlerConfiguration))
                                          .BindNamedParameter(typeof(MemoryPerMapper),
                                                              jobDefinition.MapperMemory.ToString(CultureInfo.InvariantCulture))
                                          .BindNamedParameter(typeof(MemoryForUpdateTask),
                                                              jobDefinition.UpdateTaskMemory.ToString(CultureInfo.InvariantCulture))
                                          .BindNamedParameter(typeof(CoresPerMapper),
                                                              jobDefinition.MapTaskCores.ToString(CultureInfo.InvariantCulture))
                                          .BindNamedParameter(typeof(CoresForUpdateTask),
                                                              jobDefinition.UpdateTaskCores.ToString(CultureInfo.InvariantCulture))
                                          .BindNamedParameter(typeof(InvokeGC),
                                                              jobDefinition.InvokeGarbageCollectorAfterIteration.ToString(CultureInfo.InvariantCulture))
                                          .Build();

            // The JobSubmission contains the Driver configuration as well as the files needed on the Driver.
            var imruJobSubmission = _jobSubmissionBuilderFactory.GetJobSubmissionBuilder()
                                    .AddDriverConfiguration(imruDriverConfiguration)
                                    .AddGlobalAssemblyForType(typeof(IMRUDriver <TMapInput, TMapOutput, TResult>))
                                    .SetJobIdentifier(jobDefinition.JobName)
                                    .Build();

            _jobSubmissionResult = _reefClient.SubmitAndGetJobStatus(imruJobSubmission);

            return(null);
        }
        public List <Assignment> Assignment_Read()
        {
            List <Assignment> assignments = new List <Assignment>();

            try
            {
                SqlCommand cmd = new SqlCommand("Assignment_Read", constr);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable      dt = new DataTable();
                constr.Open();
                da.Fill(dt);
                constr.Close();
                foreach (DataRow dr in dt.Rows)
                {
                    //if (dr["deletedOn"] != null)
                    //{
                    //    assignments.Add(new Assignment
                    //    {
                    //        AssignmentId = Convert.ToInt32(dr["AssignmentId"]),
                    //        AssignmentName = Convert.ToString(dr["AssignmentName"]),
                    //        Path = Convert.ToString(dr["Path"]),
                    //        Type = Convert.ToString(dr["Type"]),
                    //        FacultyId = Convert.ToInt32(dr["FacultyId"]),
                    //        createdOn = Convert.ToDateTime(dr["createdOn"]),
                    //        modifiedOn = Convert.ToDateTime(dr["modifiedOn"]),
                    //        deletedOn = Convert.ToDateTime(dr["deletedOn"]),
                    //        isDeleted = Convert.ToBoolean(dr["isDeleted"])
                    //    }
                    //    );
                    //}
                    //else
                    //{
                    assignments.Add(new Assignment
                    {
                        AssignmentId   = Convert.ToInt32(dr["AssignmentId"]),
                        AssignmentName = Convert.ToString(dr["AssignmentName"]),
                        Path           = Convert.ToString(dr["Path"]),
                        Type           = Convert.ToString(dr["Type"]),
                        FacultyId      = Convert.ToInt32(dr["FacultyId"]),
                        createdOn      = Convert.ToDateTime(dr["createdOn"]),
                        modifiedOn     = Convert.ToDateTime(dr["modifiedOn"]),
                        isDeleted      = Convert.ToBoolean(dr["isDeleted"]),
                    }
                                    );
                    //}
                }
            }
            catch (Exception ex)
            {
                Exceptions exception = new Exceptions
                {
                    ExceptionNumber  = ex.HResult.ToString(),
                    ExceptionMessage = ex.Message,
                    ExceptionMethod  = "Assignment_Read",
                    ExceptionUrl     = ""
                };
                int r = exceptionrepo.Exception_Create(exception);
                if (r == 0)
                {
                    exceptionrepo.Exception_InsertInLogFile(exception);
                }
                if (constr.State != ConnectionState.Open)
                {
                    constr.Close();
                    constr.Open();
                }
            }
            return(assignments);
        }
 private static DreamMessage Map(Exceptions.InvalidRatingScoreException e) {
     return DreamMessage.BadRequest(DekiResources.RATING_INVALID_SCORE);
 }
Ejemplo n.º 33
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	9/21/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmdCancel.Click += OnCancelClick;
            cmdCopy.Click   += OnCopyClick;
            cmdDelete.Click += OnDeleteClick;
            cmdEmail.Click  += OnEmailClick;
            cmdUpdate.Click += OnUpdateClick;
            DNNTxtBannerGroup.PopulateOnDemand += PopulateBannersOnDemand;

            try
            {
                if ((Request.QueryString["VendorId"] != null))
                {
                    VendorId = Int32.Parse(Request.QueryString["VendorId"]);
                }
                if ((Request.QueryString["BannerId"] != null))
                {
                    BannerId = Int32.Parse(Request.QueryString["BannerId"]);
                }

                if (Page.IsPostBack == false)
                {
                    ctlImage.FileFilter = Globals.glbImageFileTypes;

                    var objBannerTypes = new BannerTypeController();
                    //Get the banner types from the database
                    cboBannerType.DataSource = objBannerTypes.GetBannerTypes();
                    cboBannerType.DataBind();

                    var objBanners = new BannerController();
                    if (BannerId != Null.NullInteger)
                    {
                        //Obtain a single row of banner information
                        BannerInfo banner = objBanners.GetBanner(BannerId);
                        if (banner != null)
                        {
                            txtBannerName.Text = banner.BannerName;
                            cboBannerType.Items.FindByValue(banner.BannerTypeId.ToString()).Selected = true;
                            DNNTxtBannerGroup.Text = banner.GroupName;
                            ctlImage.Url           = banner.ImageFile;
                            if (banner.Width != 0)
                            {
                                txtWidth.Text = banner.Width.ToString();
                            }
                            if (banner.Height != 0)
                            {
                                txtHeight.Text = banner.Height.ToString();
                            }
                            txtDescription.Text = banner.Description;
                            if (!String.IsNullOrEmpty(banner.URL))
                            {
                                ctlURL.Url = banner.URL;
                            }
                            txtImpressions.Text = banner.Impressions.ToString();
                            txtCPM.Text         = banner.CPM.ToString();

                            StartDatePicker.SelectedDate = Null.IsNull(banner.StartDate) ? (DateTime?)null : banner.StartDate;
                            EndDatePicker.SelectedDate   = Null.IsNull(banner.EndDate) ? (DateTime?)null : banner.EndDate;

                            optCriteria.Items.FindByValue(banner.Criteria.ToString()).Selected = true;

                            ctlAudit.CreatedByUser = banner.CreatedByUser;
                            ctlAudit.CreatedDate   = banner.CreatedDate.ToString();

                            var arrBanners = new ArrayList();

                            arrBanners.Add(banner);
                            bannersRow.Visible    = true;
                            lstBanners.DataSource = arrBanners;
                            lstBanners.DataBind();
                        }
                        else //security violation attempt to access item not related to this Module
                        {
                            Response.Redirect(EditUrl("VendorId", VendorId.ToString()), true);
                        }
                    }
                    else
                    {
                        txtImpressions.Text = "0";
                        txtCPM.Text         = "0";
                        optCriteria.Items.FindByValue("1").Selected = true;
                        cmdDelete.Visible = false;
                        cmdCopy.Visible   = false;
                        cmdEmail.Visible  = false;
                        ctlAudit.Visible  = false;
                    }
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 private static DreamMessage Map(Exceptions.TalkPageLanguageCannotBeSet e) {
     return DreamMessage.Conflict(DekiResources.LANGUAGE_SET_TALK);
 }
Ejemplo n.º 35
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the Update Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [cnurse]	9/21/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                //Only Update if the Entered Data is val
                if (Page.IsValid)
                {
                    if (!cmdCopy.Visible)
                    {
                        BannerId = -1;
                    }
                    DateTime startDate = Null.NullDate;
                    if (StartDatePicker.SelectedDate.HasValue)
                    {
                        startDate = StartDatePicker.SelectedDate.Value;
                    }
                    DateTime endDate = Null.NullDate;
                    if (EndDatePicker.SelectedDate.HasValue)
                    {
                        endDate = EndDatePicker.SelectedDate.Value;
                    }

                    //Create an instance of the Banner DB component
                    var objBanner = new BannerInfo();
                    objBanner.BannerId     = BannerId;
                    objBanner.VendorId     = VendorId;
                    objBanner.BannerName   = txtBannerName.Text;
                    objBanner.BannerTypeId = Convert.ToInt32(cboBannerType.SelectedItem.Value);
                    objBanner.GroupName    = DNNTxtBannerGroup.Text;
                    objBanner.ImageFile    = ctlImage.Url;
                    if (!String.IsNullOrEmpty(txtWidth.Text))
                    {
                        objBanner.Width = int.Parse(txtWidth.Text);
                    }
                    else
                    {
                        objBanner.Width = 0;
                    }
                    if (!String.IsNullOrEmpty(txtHeight.Text))
                    {
                        objBanner.Height = int.Parse(txtHeight.Text);
                    }
                    else
                    {
                        objBanner.Height = 0;
                    }
                    objBanner.Description   = txtDescription.Text;
                    objBanner.URL           = ctlURL.Url;
                    objBanner.Impressions   = int.Parse(txtImpressions.Text);
                    objBanner.CPM           = double.Parse(txtCPM.Text);
                    objBanner.StartDate     = startDate;
                    objBanner.EndDate       = endDate;
                    objBanner.Criteria      = int.Parse(optCriteria.SelectedItem.Value);
                    objBanner.CreatedByUser = UserInfo.UserID.ToString();

                    var objBanners = new BannerController();
                    if (BannerId == Null.NullInteger)
                    {
                        //Add the banner within the Banners table
                        objBanners.AddBanner(objBanner);
                    }
                    else
                    {
                        //Update the banner within the Banners table
                        objBanners.UpdateBanner(objBanner);
                    }

                    //Redirect back to the portal home page
                    Response.Redirect(EditUrl("VendorId", VendorId.ToString()), true);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
 private static DreamMessage Map(Exceptions.BanNoPermsException e) {
     return DreamMessage.BadRequest(DekiResources.BANNING_NO_PERMS);
 }
Ejemplo n.º 37
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            jQuery.RequestDnnPluginsRegistration();

            ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js");
            ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js");
            ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js");

            if (RegistrationFormType == 0)
            {
                //UserName
                if (!UseEmailAsUserName)
                {
                    AddField("Username", String.Empty, true,
                             String.IsNullOrEmpty(UserNameValidator) ? ExcludeTerms : UserNameValidator,
                             TextBoxMode.SingleLine);
                }

                //Password
                if (!RandomPassword)
                {
                    AddPasswordStrengthField("Password", "Membership", true);

                    if (RequirePasswordConfirm)
                    {
                        AddPasswordConfirmField("PasswordConfirm", "Membership", true);
                    }
                }

                //Password Q&A
                if (MembershipProviderConfig.RequiresQuestionAndAnswer)
                {
                    AddField("PasswordQuestion", "Membership", true, String.Empty, TextBoxMode.SingleLine);
                    AddField("PasswordAnswer", "Membership", true, String.Empty, TextBoxMode.SingleLine);
                }

                //DisplayName
                if (String.IsNullOrEmpty(DisplayNameFormat))
                {
                    AddField("DisplayName", String.Empty, true, String.Empty, TextBoxMode.SingleLine);
                }
                else
                {
                    AddField("FirstName", String.Empty, true, String.Empty, TextBoxMode.SingleLine);
                    AddField("LastName", String.Empty, true, String.Empty, TextBoxMode.SingleLine);
                }

                //Email
                AddField("Email", String.Empty, true, EmailValidator, TextBoxMode.SingleLine);

                if (RequireValidProfile)
                {
                    foreach (ProfilePropertyDefinition property in User.Profile.ProfileProperties)
                    {
                        if (property.Required)
                        {
                            AddProperty(property);
                        }
                    }
                }
            }
            else
            {
                var fields = RegistrationFields.Split(',').ToList();
                //append question/answer field when RequiresQuestionAndAnswer is enabled in config.
                if (MembershipProviderConfig.RequiresQuestionAndAnswer)
                {
                    if (!fields.Contains("PasswordQuestion"))
                    {
                        fields.Add("PasswordQuestion");
                    }
                    if (!fields.Contains("PasswordAnswer"))
                    {
                        fields.Add("PasswordAnswer");
                    }
                }

                foreach (string field in fields)
                {
                    var trimmedField = field.Trim();
                    switch (trimmedField)
                    {
                    case "Username":
                        AddField("Username", String.Empty, true, String.IsNullOrEmpty(UserNameValidator)
                                                                        ? ExcludeTerms : UserNameValidator,
                                 TextBoxMode.SingleLine);
                        break;

                    case "Email":
                        AddField("Email", String.Empty, true, EmailValidator, TextBoxMode.SingleLine);
                        break;

                    case "Password":
                        AddPasswordStrengthField(trimmedField, "Membership", true);
                        break;

                    case "PasswordConfirm":
                        AddPasswordConfirmField(trimmedField, "Membership", true);
                        break;

                    case "PasswordQuestion":
                    case "PasswordAnswer":
                        AddField(trimmedField, "Membership", true, String.Empty, TextBoxMode.SingleLine);
                        break;

                    case "DisplayName":
                        AddField(trimmedField, String.Empty, true, ExcludeTerms, TextBoxMode.SingleLine);
                        break;

                    default:
                        ProfilePropertyDefinition property = User.Profile.GetProperty(trimmedField);
                        if (property != null)
                        {
                            AddProperty(property);
                        }
                        break;
                    }
                }
            }

            //Verify that the current user has access to this page
            if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && Request.IsAuthenticated == false)
            {
                Response.Redirect(Globals.NavigateURL("Access Denied"), true);
            }

            cancelButton.Click   += cancelButton_Click;
            registerButton.Click += registerButton_Click;

            if (UseAuthProviders)
            {
                List <AuthenticationInfo> authSystems = AuthenticationController.GetEnabledAuthenticationServices();
                foreach (AuthenticationInfo authSystem in authSystems)
                {
                    try
                    {
                        var authLoginControl = (AuthenticationLoginBase)LoadControl("~/" + authSystem.LoginControlSrc);
                        if (authSystem.AuthenticationType != "DNN")
                        {
                            BindLoginControl(authLoginControl, authSystem);
                            //Check if AuthSystem is Enabled
                            if (authLoginControl.Enabled && authLoginControl.SupportsRegistration)
                            {
                                authLoginControl.Mode = AuthMode.Register;

                                //Add Login Control to List
                                _loginControls.Add(authLoginControl);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Exceptions.LogException(ex);
                    }
                }
            }
        }
Ejemplo n.º 38
0
 private static Exception ValidateValue(string value)
 {
     return
         (Exceptions.WhenNullOrWhiteSpace(value, nameof(value)) ??
          Exceptions.WhenLengthIsIncorrect(value, MinValueLength, int.MaxValue, nameof(value)));
 }
Ejemplo n.º 39
0
        protected bool ValidateByAttribute(object obj, System.Reflection.PropertyInfo property, Enumerations.Action action, ref Exceptions.ValidationException exception)
        {
            exception = null;
            object[] validationAttributes = property.GetCustomAttributes(typeof(Attributes.ValidationAttribute), true);
            foreach (Validation.Attributes.ValidationAttribute attr in validationAttributes)
            {
                if (attr.Action != Enumerations.Action.All && attr.Action != action )
                    continue;
                Type type = attr.GetType();
                if (type == typeof(Validation.Attributes.IsBetweenAttribute))
                {
                    Validation.Attributes.IsBetweenAttribute attribute = (Validation.Attributes.IsBetweenAttribute)attr;
                    try
                    {
                        AssertIsBetween(attribute.FriendlyName, property.GetValue(obj), attribute.MinimumValue, attribute.MaximumValue);
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.RequiredAttribute) || type == typeof(Validation.Attributes.NotNullAttribute))
                {
                    Validation.Attributes.ValidationAttribute attribute = (Validation.Attributes.ValidationAttribute)attr;
                    try
                    {
                        Type propertyType = property.PropertyType;
                        if (propertyType == typeof(string))
                            AssertIsRequired(attribute.FriendlyName, property.GetValue(obj).ToString());
                        else if (propertyType == typeof(DateTime))
                            AssertIsRequired(attribute.FriendlyName, (DateTime)property.GetValue(obj));
                        else if (propertyType == typeof(Int16))
                            AssertIsRequired(attribute.FriendlyName, (Int16)property.GetValue(obj));
                        else if (propertyType == typeof(Int32))
                            AssertIsRequired(attribute.FriendlyName, (Int32)property.GetValue(obj));
                        else if (propertyType == typeof(Int64))
                            AssertIsRequired(attribute.FriendlyName, (Int64)property.GetValue(obj));
                        else if (propertyType == typeof(Int16))
                            AssertIsRequired(attribute.FriendlyName, (Int16)property.GetValue(obj));
                        else if (propertyType == typeof(Decimal))
                            AssertIsRequired(attribute.FriendlyName, (Decimal)property.GetValue(obj));
                        else if (propertyType == typeof(Single))
                            AssertIsRequired(attribute.FriendlyName, (Single)property.GetValue(obj));
                        else if (propertyType == typeof(UInt16))
                            AssertIsRequired(attribute.FriendlyName, (UInt16)property.GetValue(obj));
                        else if (propertyType == typeof(UInt32))
                            AssertIsRequired(attribute.FriendlyName, (UInt32)property.GetValue(obj));
                        else if (propertyType == typeof(UInt64))
                            AssertIsRequired(attribute.FriendlyName, (UInt64)property.GetValue(obj));
                        else if (propertyType == typeof(Guid))
                            AssertIsRequired(attribute.FriendlyName, (Guid)property.GetValue(obj));
                        else
                            AssertIsRequired(attribute.FriendlyName, property.GetValue(obj));
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.LengthNotGreaterThanAttribute))
                {
                    Validation.Attributes.LengthNotGreaterThanAttribute attribute = (Validation.Attributes.LengthNotGreaterThanAttribute)attr;
                    try
                    {
                        AssertLengthNotGreaterThan(attribute.FriendlyName, property.GetValue(obj), attribute.MaximumLength);
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.LengthNotLessThanAttribute))
                {
                    Validation.Attributes.LengthNotLessThanAttribute attribute = (Validation.Attributes.LengthNotLessThanAttribute)attr;
                    try
                    {
                        AssertLengthNotLessThan(attribute.FriendlyName, property.GetValue(obj), attribute.MinimumLength);

                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.NotGreaterThanAttribute))
                {
                    Validation.Attributes.NotGreaterThanAttribute attribute = (Validation.Attributes.NotGreaterThanAttribute)attr;
                    try
                    {
                        AssertNotGreaterThan(attribute.FriendlyName, property.GetValue(obj), attribute.MaximumValue);
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.NotLessThanAttribute))
                {
                    Validation.Attributes.NotLessThanAttribute attribute = (Validation.Attributes.NotLessThanAttribute)attr;
                    try
                    {
                        AssertNotLessThan(attribute.FriendlyName, property.GetValue(obj), attribute.MinimumValue);
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
                else if (type == typeof(Validation.Attributes.RegularExpressionAttribute))
                {
                    Validation.Attributes.RegularExpressionAttribute attribute = (Validation.Attributes.RegularExpressionAttribute)attr;
                    try
                    {
                        AssertRegularExpressions(attribute.FriendlyName, property.GetValue(obj), attribute.Pattern, attribute.Options);
                    }
                    catch (Exceptions.ValidationException ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
            }
            return true;
        }