Rectangle 27 5

I would copy over the Devise Controllers and add a before filter like so:

class Users::SessionsController < Devise::SessionsController

  before_filter :logout_admin, :only => "create"

  def create
    super
  end

  private

  def logout_admin
    # change :admin to :user in the admin's session controller
    # the sign_out is a devise controller helper that forces sign out
    sign_out :admin
  end

end

Then for the testing you can access the current user in functional(controller) specs by calling subject.current_user or subject.current_admin, go here: https://github.com/plataformatec/devise to make sure to include the test helpers then try something like this:

require 'spec_helper'

describe Users::SessionsController do
  login_admin

  describe "POST create" do
    it "should logout admin" do
      post :create, {:user => {:email => "tester@email.com", :password => "secret"} }
      subject.current_user.should_not be_nil
      subject.current_admin.should be_nil
    end
  end
end

I think this will work. How would you test something like this in capybara? are there specific helpers for that as well?

ahh, good question, as far as i know you can't access current_user from a request spec (and thats probably not best practice either), is there some part of your app's view that is different when a user is logged in vs an admin, or some kind of flash[:notice] to help differentiate?

so for the above example code, i wouldn't be able to do subject.current_user either then, correct? I was thinking of using flash[:notice] to notify the user/admin they have been signed out adn the new user/admin has been signed in. I could capture that in capybara.

no, you can in the functional controller specs, just not in the integration request specs

and yes the flash[:notice] would be great to test, just run through the normal procedure and then simply say page.should have_content "User has been signed out and Admin has been signed in"

ruby on rails 3 - User and Admin Logout with Devise and Testing it via...

ruby-on-rails-3 devise capybara rspec2
Rectangle 27 11

There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore) The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events

I wrote this looking with reflector at the ErrorHandler inside elmah.mvc

public class ElmahMVCErrorFilter : IExceptionFilter
{
   private static ErrorFilterConfiguration _config;

   public void OnException(ExceptionContext context)
   {
       if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
       {
           var e = context.Exception;
           var context2 = context.HttpContext.ApplicationInstance.Context;
           //TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
           if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
           {
            _LogException(e, context2);
           }
       }
   }

   private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
   {
       if (_config == null)
       {
           _config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
       }
       var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
       return _config.Assertion.Test(context2);
   }

   private static void _LogException(System.Exception e, System.Web.HttpContext context)
   {
       ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
   }


   private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
   {
       var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
       if (signal == null)
       {
           return false;
       }
       signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
       return true;
   }
}

Now, in your filter config you want to do something like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //These filters should go at the end of the pipeline, add all error handlers before
        filters.Add(new ElmahMVCErrorFilter());
    }

Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.

Now, make sure the appsettings for elmah in your webconfig look something like this:

<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->

The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings

This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.

logging - How to get ELMAH to work with ASP.NET MVC [HandleError] attr...

asp.net-mvc logging elmah
Rectangle 27 11

There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore) The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events

I wrote this looking with reflector at the ErrorHandler inside elmah.mvc

public class ElmahMVCErrorFilter : IExceptionFilter
{
   private static ErrorFilterConfiguration _config;

   public void OnException(ExceptionContext context)
   {
       if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
       {
           var e = context.Exception;
           var context2 = context.HttpContext.ApplicationInstance.Context;
           //TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
           if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
           {
            _LogException(e, context2);
           }
       }
   }

   private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
   {
       if (_config == null)
       {
           _config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
       }
       var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
       return _config.Assertion.Test(context2);
   }

   private static void _LogException(System.Exception e, System.Web.HttpContext context)
   {
       ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
   }


   private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
   {
       var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
       if (signal == null)
       {
           return false;
       }
       signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
       return true;
   }
}

Now, in your filter config you want to do something like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //These filters should go at the end of the pipeline, add all error handlers before
        filters.Add(new ElmahMVCErrorFilter());
    }

Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.

Now, make sure the appsettings for elmah in your webconfig look something like this:

<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->

The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings

This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.

logging - How to get ELMAH to work with ASP.NET MVC [HandleError] attr...

asp.net-mvc logging elmah
Rectangle 27 11

There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore) The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events

I wrote this looking with reflector at the ErrorHandler inside elmah.mvc

public class ElmahMVCErrorFilter : IExceptionFilter
{
   private static ErrorFilterConfiguration _config;

   public void OnException(ExceptionContext context)
   {
       if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
       {
           var e = context.Exception;
           var context2 = context.HttpContext.ApplicationInstance.Context;
           //TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
           if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
           {
            _LogException(e, context2);
           }
       }
   }

   private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
   {
       if (_config == null)
       {
           _config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
       }
       var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
       return _config.Assertion.Test(context2);
   }

   private static void _LogException(System.Exception e, System.Web.HttpContext context)
   {
       ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
   }


   private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
   {
       var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
       if (signal == null)
       {
           return false;
       }
       signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
       return true;
   }
}

Now, in your filter config you want to do something like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //These filters should go at the end of the pipeline, add all error handlers before
        filters.Add(new ElmahMVCErrorFilter());
    }

Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.

Now, make sure the appsettings for elmah in your webconfig look something like this:

<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->

The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings

This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.

logging - How to get ELMAH to work with ASP.NET MVC [HandleError] attr...

asp.net-mvc logging elmah
Rectangle 27 8

Yes, this sounds like a good application of an action filter, as you can apply it at the controller level to operate on all actions. You could also make it part of a controller base class, if you didn't want to add it to all controllers manually, or write your own controller factory which automatically applies this action filter to each controller.

+1 and thank you for the link in your second paragraph - took me right to what I needed for a similar problem.

ASP.NET MVC: Action Filter to set up controller variables? - Stack Ove...

asp.net asp.net-mvc action-filter
Rectangle 27 49

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

In what file this lines should be added ?

@Oleg in your applicationContext.xml. Make sure the namespace definition for the context prefix is included as explained here

I have Maven project and haven't applicationContext.xml.

spring - Injection of autowired dependencies failed; - Stack Overflow

spring autowired
Rectangle 27 3

This is a simple and straight-forward approach. Go with this, if all you are going to do is filter out refunded orders and cancelled orders from Order and display them on their independent views. Also, you don't wish to clutter the index action as well as index view. This is also a better approach if you are not planning on adding any more reports in future and clutter the OrdersController.

As per the details given in question, the view for Refunded Orders and Cancelled Orders is going to be primarily based on Order model. So, adding new controllers for each report doesn't seem feasible. What are these controllers going to do anyway, just have a single action for refunds or cancellations each? I would not recommend going with this approach.

This is a better approach than both Approach #1 and Approach #2, provided in near future you are planning to add more reports on Order model. With this approach you would be separating the concerns by keeping OrdersController just for the CRUD activities on your Order model and OrderReportsController for all the reports that can be generated on the data retrieved from Order.

When should I create a separate controller instead of a custom action ...

ruby-on-rails controllers
Rectangle 27 4

Create an action filter that will add the ID to the route data in the OnActionExecuting method? You can access the controller through the filter context (and the viewbag). As long as your viewbag contains the customId, you should be able to add it to the route data. At least this way you only need to remember to add the attribute on the controller.

Create a base class that inherits from System.Web.Mvc.Controller and implement your own RedirectToAction. Then have all your controllers inherit form MyControllerBase. Something like this.

public class MyControllerBase : Controller
{
    public RedirectToRouteResult RedirectToAction<TController>(Expression<Func<TController, object>> actionExpression)
    {
        var custId = ControllerContext.Controller.ViewBag["customId"];
        string controllerName = typeof(TController).GetControllerName();
        string actionName = actionExpression.GetActionName();

        return RedirectToAction(actionName, controllerName, new {cId = custId});
    }
}

PART 2: Another way I've modified a URL (I knew I had the code somewhere!) on every view, I needed the URL to link from a mobile site to a full browser site and read the mappings from the database. So in my footer, I have the following:

<a id="fullSiteLink" href="<%= ViewData[AppConstants.MainSiteUrl] %>">Visit our Full Browser site</a><br />

I then added a filter to the base controller class and onactionexecuting (before the action),

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    var mainSiteUrl = _mobileToMainRedirect.GetMainSiteUrl(filterContext.HttpContext.Request.Url);
    filterContext.Controller.ViewData.Add(AppConstants.MainSiteUrl, string.IsNullOrEmpty(mainSiteUrl) ? UrlHelperExtensions.FullBrowserSite(filterContext.HttpContext.Request.Url) : mainSiteUrl);
}

Both are good options. I ended up going with a global filter to add the ID in OnActionExecuted (after the action had run, and before the result is executed). This solves the RedirectToAction issue. There's the other part requiring outgoing URL's to be updated. I ended up achieving this by inserting the customId into RouteData.Values in MvcHandler.BeginProcessRequest, to get this working you ALSO need the customId in the routes too. I will post my code and accept this :)

If you could post your code, that would be great! I've added the way I've done it in the past, but would be good to see another solution!

c# - Add parameter to all Incoming/Outgoing URL's - Stack Overflow

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 5

Probably because the component-scan in your spring-servlet.xml is also including your DAO classes in its scanning and therefore creating instances for them in its application context (not the "database" one)... so that when your web accesses these DAOs from web controllers, it is accessing non-transactional versions of them (unless you add that tx:annotation-driven tag).

Therefore, adding that tag is in fact a bad solution because it still creates your DAO instances in the wrong application context: better create a more specific base-packageconfiguration for your web layer component creation.

I had this same problem because I thought a <context:include-filter> in my spring-servlet.xml was taking care of only scanning @Controller classes... but no :-(

java - Declarative transactions (@Transactional) doesn't work with @Re...

java spring repository transactional
Rectangle 27 5

Probably because the component-scan in your spring-servlet.xml is also including your DAO classes in its scanning and therefore creating instances for them in its application context (not the "database" one)... so that when your web accesses these DAOs from web controllers, it is accessing non-transactional versions of them (unless you add that tx:annotation-driven tag).

Therefore, adding that tag is in fact a bad solution because it still creates your DAO instances in the wrong application context: better create a more specific base-packageconfiguration for your web layer component creation.

I had this same problem because I thought a <context:include-filter> in my spring-servlet.xml was taking care of only scanning @Controller classes... but no :-(

java - Declarative transactions (@Transactional) doesn't work with @Re...

java spring repository transactional
Rectangle 27 2

If you want to manage the tokens across all of your actions, you should change the code to use a custom authorization filter. That filter can be added to all Web API requests, all actions for a controller, or an individual action. To do that, derive from the AuthorizeAttribute and issue the GetBearerToken call from the filter. Stick the token into the HTTP context for usage during request processing. Instead of directly calling creating HttpClient instances, you could use a factory to generate them and add the appropriate tokens for authentication.

As for determining if the tokens are expired, you could add an additional filter that checks for specific errors coming back or alternative issue a check in the authorization filter. I don't know all of your requirements so it's difficult to determine the appropriate solution there.

asp.net mvc - MVC .NET cookie authenticated system acessing a Web Api ...

asp.net-mvc asp.net-web-api owin bearer-token
Rectangle 27 4

You can use either Application_Start() or Session_Start() in the Global.asax.cs for storing data only once depending on whether you want the data to be refreshed on application start or per session start. That would be up to what your application needs to do.

Having a base controller like you did is good if you need something to be done for every action. The most common being the [Authorize] filter that you need to do for every action to see if the user is authorized for security reasons. Another way to do this is also writing your own ActionFilterAttribute and doing the caching part you need to do. Then all you need to do is to add this new Action filter to any of the actions that you need to do this caching. Pleas see here for how to do this : https://msdn.microsoft.com/en-us/library/dd410056(v=vs.98).aspx But since you want the data to load only once I think an action filter may NOT be the right place to do caching.

c# - Asp.Net MVC Outputcache in base controller not working - Stack Ov...

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 0

You should filter the grid data in another way. The usage of Html.BeginForm is the wrong way. Look at the answer and use either the filter toolbar or advanced searching. If you do decide to use you custom <input> field you should use postData with the property defined as function (see here) and use .trigger("reloadGrid", [{page: 1}]) to send the searching request to the controller. In the case you should add new parameter which corresponds the property name in the postData to the list of parameters of GridData.

jqgrid - Error When Submitting Asp.Net MVC Form - Stack Overflow

asp.net-mvc jqgrid