public ActionResult Redirect() { var catalog = this.Container.Catalog; double lowestOrder = double.MaxValue; Uri redirectUri = null; foreach (var exportInfo in catalog.FindExports<IControllerMetadata>(ContractNames.AdminController)) { ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(exportInfo.Value); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; if (controllerAttr.Order >= lowestOrder) continue; lowestOrder = controllerAttr.Order; Uri defaultTargetUrl = null; foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; string targetUrl = Url.Action(actionAttr.Name, controllerAttr.Name, new { packageId = exportInfo.Metadata.PackageId, packageVersion = exportInfo.Metadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; } if (defaultTargetUrl != null) redirectUri = defaultTargetUrl; } return Redirect(redirectUri.ToString()); }
public override void OnException(ExceptionContext filterContext) { ExceptionHandlerAreaAttribute RegisteredExceptionArea = null; ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(filterContext.Controller.GetType()); ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(filterContext.Controller.ControllerContext, filterContext.RouteData.Values["action"].ToString()); if (controllerDescriptor.IsDefined(typeof(ExceptionHandlerAreaAttribute), true)) RegisteredExceptionArea = controllerDescriptor.GetCustomAttributes(typeof(ExceptionHandlerAreaAttribute), true).First() as ExceptionHandlerAreaAttribute; else if (actionDescriptor != null && actionDescriptor.IsDefined(typeof(ExceptionHandlerAreaAttribute), true)) RegisteredExceptionArea = actionDescriptor.GetCustomAttributes(typeof(ExceptionHandlerAreaAttribute), true).First() as ExceptionHandlerAreaAttribute; if (RegisteredExceptionArea != null) Debug.WriteLine(RegisteredExceptionArea.RegisteredAreaName); base.OnException(filterContext); }
/// <summary> /// Saúl H. Sánchez. /// /// Metodo utilizado para inicializar la configuración del /// plugin WebSecurity, y la inicialización de la conexión /// de la base de datos, tomando en cuenta la tabla de la /// base de datos que almacenará los datos de los usuarios /// de la aplicación. También en este método se insertan los /// datos por defecto requeridos para el mínimo funcionamiento /// de la aplicación, tales como roles y un usuario por defecto. /// </summary> public static void Register() { try { WebSecurity.InitializeDatabaseConnection ( "SigeretContext", "UserProfile", "UserId", "username", autoCreateTables: true ); //verificacion y creacion de roles de la aplicacion var roles = (SimpleRoleProvider)Roles.Provider; if (roles.GetAllRoles().Count() == 0) { roles.CreateRole("Administrador"); roles.CreateRole("Profesor"); roles.CreateRole("Estudiante"); } //Creacion y gestion de parametros para cuenta administrador if (!WebSecurity.UserExists("SigeretAdmin")) { WebSecurity.CreateUserAndAccount( "SigeretAdmin", "000000", propertyValues: new { Nombre = "Administrador", Apellido = "Sigeret", Cedula = "00000000000", Matricula = "7777777777" }); } if (!roles.GetRolesForUser("SigeretAdmin").Contains("Administrador")) { roles.AddUsersToRoles(new[] { "SigeretAdmin" }, new[] { "Administrador" }); } using (SigeretContext db = new SigeretContext()) { //Almacenando datos de los controladores y la acciones en la bd, para el modulo de permisos. var types = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (var ctrlType in types) { ReflectedControllerDescriptor ctrlDescriptor = new ReflectedControllerDescriptor(ctrlType); if (ctrlDescriptor.GetCustomAttributes(typeof(EsControllerAttribute), false).Any()) { var attribute = ctrlDescriptor.GetCustomAttributes(typeof(EsControllerAttribute), false).FirstOrDefault() as EsControllerAttribute; Controlador ctrl = db.Controladors.FirstOrDefault(c => c.Descriptor == attribute.Descriptor); if (ctrl == null) { ctrl = new Controlador(); ctrl.Name = attribute.ControllerName; ctrl.Descriptor = attribute.Descriptor; db.Controladors.Add(ctrl); } else { if (ctrl.Name != attribute.ControllerName) { ctrl.Name = attribute.ControllerName; } db.Entry(ctrl).State = System.Data.EntityState.Modified; } foreach (ActionDescriptor ad in ctrlDescriptor.GetCanonicalActions()) { if (ad.GetCustomAttributes(typeof(VistaAttribute), false).Any()) { var ActionAttribute = ad.GetCustomAttributes(typeof(VistaAttribute), false).FirstOrDefault() as VistaAttribute; Accion acc = db.Accions.FirstOrDefault(a => a.Descriptor == ActionAttribute.Descriptor); if (acc == null) { acc = new Accion(); acc.Name = ActionAttribute.ViewName; acc.Descriptor = ActionAttribute.Descriptor; ctrl.Accions.Add(acc); db.Accions.Add(acc); } else { if (acc.Name != ActionAttribute.ViewName) { acc.Name = ActionAttribute.ViewName; } db.Entry(acc).State = System.Data.EntityState.Modified; } } } db.SaveChanges(); } } //Asignando permisos sobre todas las acciones a la cuenta de Administrador por defecto. var adminRole = db.webpages_Roles.FirstOrDefault(r => r.RoleName == "Administrador"); foreach (Accion a in db.Accions) { if (!adminRole.Accions.Contains(a)) adminRole.Accions.Add(a); } db.Entry(adminRole).State = System.Data.EntityState.Modified; db.SaveChanges(); } } catch (Exception ex) { throw new InvalidOperationException("No se pudo inicializar la conexión con la base de datos.", ex); } }
public void OnActionExecuted(ActionExecutedContext filterContext) { ViewResult viewResult = filterContext.Result as ViewResult; if (viewResult != null && viewResult.Model != null) { IAdminModel model = viewResult.Model as IAdminModel; if (model == null) throw new InvalidOperationException(string.Format("Model ({0}) does not implement IAdminModel", viewResult.GetType().Name)); model.Notifications = App.Instance.Notifications.Get(filterContext.HttpContext.User); // this was populated by the AddInControllerFactory IControllerMetadata metadata = (IControllerMetadata) filterContext.RequestContext.HttpContext.Items[AddInControllerFactory.MetadataKey]; string actionText = string.Empty; // TODO FIX THIS SOMEHOW, this is pretty crappy var allControllerExports = App.Instance.Container.GetExports( new ContractBasedImportDefinition( ContractNames.AdminController, AttributedModelServices.GetTypeIdentity(typeof(IController)), Enumerable.Empty<KeyValuePair<string, Type>>(), ImportCardinality.ZeroOrMore, false, false, CreationPolicy.NonShared)); List<Navigation> menu = new List<Navigation>(); foreach (Export export in allControllerExports) { IControllerMetadata controllerMetadata = AttributedModelServices.GetMetadataView<IControllerMetadata>(export.Metadata); ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(export.Value.GetType()); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); Uri defaultTargetUrl = null; List<Navigation> children = new List<Navigation>(); foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; // TODO replace anon class with concrete type? string targetUrl = urlHelper.Action(actionAttr.Name, controllerAttr.Name, new { packageId = controllerMetadata.PackageId, packageVersion = controllerMetadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; bool isActive = filterContext.ActionDescriptor.ActionName == actionDescriptor.ActionName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == descriptor.ControllerType; if (isActive) actionText = actionAttr.Text; Navigation navigation = new Navigation(null, actionAttr.Order, actionAttr.Text, target, isActive, Enumerable.Empty<Navigation>()); children.Add(navigation); } bool isAnyChildActive = children.Any(n => n.IsActive); // if there's only one child, ignore it if (children.Count == 1) children.Clear(); menu.Add(new Navigation(controllerAttr.Group, controllerAttr.Order, controllerAttr.Text, defaultTargetUrl, isAnyChildActive, children)); } model.Navigation = menu.OrderBy(n => n.Order).ToArray(); model.PageTitle = "LostDoc Administration " + metadata.Text; if (!string.IsNullOrWhiteSpace(actionText)) model.PageTitle += string.Format(" - {0}", actionText); } }
private static Navigation[] BuildMenu(ActionExecutedContext filterContext, ComposablePartCatalog catalog, out Navigation active) { active = null; List<Navigation> menu = new List<Navigation>(); foreach (var exportInfo in catalog.FindExports<IControllerMetadata>(ContractNames.AdminController)) { ReflectedControllerDescriptor descriptor = new ReflectedControllerDescriptor(exportInfo.Value); var controllerAttr = descriptor.GetCustomAttributes(typeof(AdminControllerAttribute), true).FirstOrDefault() as AdminControllerAttribute; if (controllerAttr == null) continue; UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext); Uri defaultTargetUrl = null; List<Navigation> children = new List<Navigation>(); foreach (var actionDescriptor in descriptor.GetCanonicalActions()) { var actionAttr = actionDescriptor.GetCustomAttributes(typeof(AdminActionAttribute), true).FirstOrDefault() as AdminActionAttribute; if (actionAttr == null) continue; // TODO replace anon class with concrete type? string targetUrl = urlHelper.Action(actionAttr.Name, controllerAttr.Name, new { packageId = exportInfo.Metadata.PackageId, packageVersion = exportInfo.Metadata.PackageVersion }); Uri target = new Uri(targetUrl, UriKind.RelativeOrAbsolute); if (defaultTargetUrl == null || actionAttr.IsDefault) defaultTargetUrl = target; bool isActive = filterContext.ActionDescriptor.ActionName == actionDescriptor.ActionName && filterContext.ActionDescriptor.ControllerDescriptor.ControllerType == descriptor.ControllerType; Navigation navigation = new Navigation(null, actionAttr.Order, actionAttr.Text, target, isActive, Enumerable.Empty<Navigation>()); if (isActive) active = navigation; children.Add(navigation); } bool isAnyChildActive = children.Any(n => n.IsActive); // if there's only one child, ignore it if (children.Count == 1) children.Clear(); menu.Add(new Navigation(controllerAttr.Group, controllerAttr.Order, controllerAttr.Text, defaultTargetUrl, isAnyChildActive, children)); } var navigations = menu.OrderBy(n => n.Order).ToArray(); return navigations; }