Search Results

Search found 15137 results on 606 pages for 'mean filter'.

Page 1/606 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How-to filter table filter input to only allow numeric input

    - by frank.nimphius
    In a previous ADF Code Corner post, I explained how to change the table filter behavior by intercepting the query condition in a query filter. See sample #30 at http://www.oracle.com/technetwork/developer-tools/adf/learnmore/index-101235.html In this OTN Harvest post I explain how to prevent users from providing invalid character entries as table filter criteria to avoid problems upon re-querying the table. In the example shown next, only numeric values are allowed for a table column filter. To create a table that allows data filtering, drag a View Object – or a data collection of a Web Service or JPA business service – from the DataControls panel and drop it as a table. Choose the Enable Filtering option in the Edit Table Columns dialog so the table renders with the column filter boxes displayed. The table filter fields are created using implicit af:inputText components that need to be customized for you to apply a custom filter input component, or to change the input behavior. To change the input filter, so only a defined set of input keys is allowed, you need to change the default filter field with your own af:inputText field to which you apply an af:clientListener tag that filters user keyboard entries. For this, in the Oracle JDeveloper visual editor, select the column which filter you want to change and expand the column node in the Oracle JDeveloper Structure Window. Part of the column definition is the Column facet node. Expand the facets so you see the filter facet entry. The filter facet is grayed out as there is no custom facet defined. In a next step, open theComponent Palette (ctrl+shift+P) and drag an Input Text component onto the facet. This demarks the first part in the filter customization. To make the custom filter component work, you need to map the af:inputText component value property to the ADF filter criteria that is exposed in the Expression Builder. Open the Expression Builder for the filter input component value property by clicking the arrow icon to its right. In the Expression Builder expand the JSP Objects | vs | filterCriteria node to select the attribute name represented by the table column. The vs entry is the name of a variable that is defined on the table and that grants you access to the table attributes. Now that the filter works as before – though using a custom filter input component – you can add the af:clientListener tag to your custom filter component – af:inputText – to call out to JavaScript when users type in the column filter field Point the client filter method property to a JavaScript function that you reference or add through using the af:resource tag and set the type property value to keyDown. <af:document id="d1">     <af:resource type="javascript" source="/js/filterHandler.js"/> … The filter definition looks as shown below <af:inputText label="Label 1" id="it1"                         value="#{vs.filterCriteria.Employe        <af:clientListener method="suppressCharacterInput"                                     type="keyDown"/> </af:inputText> The JavaScript code that you can use to either filter character inputs or numeric inputs is shown below. Just store this code in an external JavaScript (.js) file and reference it from the af:resource tag. //Allow numbers, cursor control keys and delete keys function suppressCharacterInput(evt) {     var _keyCode = evt.getKeyCode();     var _filterField = evt.getCurrentTarget();     var _oldValue = _filterField.getValue();     if (!((_keyCode < 57) ||(_keyCode > 96 && _keyCode < 105))) {         _filterField.setValue(_oldValue);         evt.cancel();     } } //Allow characters, cursor control keys and delete keys function suppressNumericInput(evt) {  var _keyCode = evt.getKeyCode();  var _filterField = evt.getCurrentTarget();  var _oldValue = _filterField.getValue();  //check for numbers  if ((_keyCode < 57 && _keyCode > 47) ||      (_keyCode > 96 && _keyCode < 105)){     _filterField.setValue(_oldValue);     evt.cancel();   } } But what if browsers don't allow JavaScript ? Don't worry about this. If browsers would not support JavaScript then ADF Faces as a whole would not work and you had a different problem.

    Read the article

  • Capturing and Transforming ASP.NET Output with Response.Filter

    - by Rick Strahl
    During one of my Handlers and Modules session at DevConnections this week one of the attendees asked a question that I didn’t have an immediate answer for. Basically he wanted to capture response output completely and then apply some filtering to the output – effectively injecting some additional content into the page AFTER the page had completely rendered. Specifically the output should be captured from anywhere – not just a page and have this code injected into the page. Some time ago I posted some code that allows you to capture ASP.NET Page output by overriding the Render() method, capturing the HtmlTextWriter() and reading its content, modifying the rendered data as text then writing it back out. I’ve actually used this approach on a few occasions and it works fine for ASP.NET pages. But this obviously won’t work outside of the Page class environment and it’s not really generic – you have to create a custom page class in order to handle the output capture. [updated 11/16/2009 – updated ResponseFilterStream implementation and a few additional notes based on comments] Enter Response.Filter However, ASP.NET includes a Response.Filter which can be used – well to filter output. Basically Response.Filter is a stream through which the OutputStream is piped back to the Web Server (indirectly). As content is written into the Response object, the filter stream receives the appropriate Stream commands like Write, Flush and Close as well as read operations although for a Response.Filter that’s uncommon to be hit. The Response.Filter can be programmatically replaced at runtime which allows you to effectively intercept all output generation that runs through ASP.NET. A common Example: Dynamic GZip Encoding A rather common use of Response.Filter hooking up code based, dynamic  GZip compression for requests which is dead simple by applying a GZipStream (or DeflateStream) to Response.Filter. The following generic routines can be used very easily to detect GZip capability of the client and compress response output with a single line of code and a couple of library helper routines: WebUtils.GZipEncodePage(); which is handled with a few lines of reusable code and a couple of static helper methods: /// <summary> ///Sets up the current page or handler to use GZip through a Response.Filter ///IMPORTANT:  ///You have to call this method before any output is generated! /// </summary> public static void GZipEncodePage() {     HttpResponse Response = HttpContext.Current.Response;     if(IsGZipSupported())     {         stringAcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];         if(AcceptEncoding.Contains("deflate"))         {             Response.Filter = newSystem.IO.Compression.DeflateStream(Response.Filter,                                        System.IO.Compression.CompressionMode.Compress);             Response.AppendHeader("Content-Encoding", "deflate");         }         else        {             Response.Filter = newSystem.IO.Compression.GZipStream(Response.Filter,                                       System.IO.Compression.CompressionMode.Compress);             Response.AppendHeader("Content-Encoding", "gzip");                            }     }     // Allow proxy servers to cache encoded and unencoded versions separately    Response.AppendHeader("Vary", "Content-Encoding"); } /// <summary> /// Determines if GZip is supported /// </summary> /// <returns></returns> public static bool IsGZipSupported() { string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))) return true; return false; } GZipStream and DeflateStream are streams that are assigned to Response.Filter and by doing so apply the appropriate compression on the active Response. Response.Filter content is chunked So to implement a Response.Filter effectively requires only that you implement a custom stream and handle the Write() method to capture Response output as it’s written. At first blush this seems very simple – you capture the output in Write, transform it and write out the transformed content in one pass. And that indeed works for small amounts of content. But you see, the problem is that output is written in small buffer chunks (a little less than 16k it appears) rather than just a single Write() statement into the stream, which makes perfect sense for ASP.NET to stream data back to IIS in smaller chunks to minimize memory usage en route. Unfortunately this also makes it a more difficult to implement any filtering routines since you don’t directly get access to all of the response content which is problematic especially if those filtering routines require you to look at the ENTIRE response in order to transform or capture the output as is needed for the solution the gentleman in my session asked for. So in order to address this a slightly different approach is required that basically captures all the Write() buffers passed into a cached stream and then making the stream available only when it’s complete and ready to be flushed. As I was thinking about the implementation I also started thinking about the few instances when I’ve used Response.Filter implementations. Each time I had to create a new Stream subclass and create my custom functionality but in the end each implementation did the same thing – capturing output and transforming it. I thought there should be an easier way to do this by creating a re-usable Stream class that can handle stream transformations that are common to Response.Filter implementations. Creating a semi-generic Response Filter Stream Class What I ended up with is a ResponseFilterStream class that provides a handful of Events that allow you to capture and/or transform Response content. The class implements a subclass of Stream and then overrides Write() and Flush() to handle capturing and transformation operations. By exposing events it’s easy to hook up capture or transformation operations via single focused methods. ResponseFilterStream exposes the following events: CaptureStream, CaptureString Captures the output only and provides either a MemoryStream or String with the final page output. Capture is hooked to the Flush() operation of the stream. TransformStream, TransformString Allows you to transform the complete response output with events that receive a MemoryStream or String respectively and can you modify the output then return it back as a return value. The transformed output is then written back out in a single chunk to the response output stream. These events capture all output internally first then write the entire buffer into the response. TransformWrite, TransformWriteString Allows you to transform the Response data as it is written in its original chunk size in the Stream’s Write() method. Unlike TransformStream/TransformString which operate on the complete output, these events only see the current chunk of data written. This is more efficient as there’s no caching involved, but can cause problems due to searched content splitting over multiple chunks. Using this implementation, creating a custom Response.Filter transformation becomes as simple as the following code. To hook up the Response.Filter using the MemoryStream version event: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformStream += filter_TransformStream; Response.Filter = filter; and the event handler to do the transformation: MemoryStream filter_TransformStream(MemoryStream ms) { Encoding encoding = HttpContext.Current.Response.ContentEncoding; string output = encoding.GetString(ms.ToArray()); output = FixPaths(output); ms = new MemoryStream(output.Length); byte[] buffer = encoding.GetBytes(output); ms.Write(buffer,0,buffer.Length); return ms; } private string FixPaths(string output) { string path = HttpContext.Current.Request.ApplicationPath; // override root path wonkiness if (path == "/") path = ""; output = output.Replace("\"~/", "\"" + path + "/").Replace("'~/", "'" + path + "/"); return output; } The idea of the event handler is that you can do whatever you want to the stream and return back a stream – either the same one that’s been modified or a brand new one – which is then sent back to as the final response. The above code can be simplified even more by using the string version events which handle the stream to string conversions for you: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; and the event handler to do the transformation calling the same FixPaths method shown above: string filter_TransformString(string output) { return FixPaths(output); } The events for capturing output and capturing and transforming chunks work in a very similar way. By using events to handle the transformations ResponseFilterStream becomes a reusable component and we don’t have to create a new stream class or subclass an existing Stream based classed. By the way, the example used here is kind of a cool trick which transforms “~/” expressions inside of the final generated HTML output – even in plain HTML controls not HTML controls – and transforms them into the appropriate application relative path in the same way that ResolveUrl would do. So you can write plain old HTML like this: <a href=”~/default.aspx”>Home</a>  and have it turned into: <a href=”/myVirtual/default.aspx”>Home</a>  without having to use an ASP.NET control like Hyperlink or Image or having to constantly use: <img src=”<%= ResolveUrl(“~/images/home.gif”) %>” /> in MVC applications (which frankly is one of the most annoying things about MVC especially given the path hell that extension-less and endpoint-less URLs impose). I can’t take credit for this idea. While discussing the Response.Filter issues on Twitter a hint from Dylan Beattie who pointed me at one of his examples which does something similar. I thought the idea was cool enough to use an example for future demos of Response.Filter functionality in ASP.NET next I time I do the Modules and Handlers talk (which was great fun BTW). How practical this is is debatable however since there’s definitely some overhead to using a Response.Filter in general and especially on one that caches the output and the re-writes it later. Make sure to test for performance anytime you use Response.Filter hookup and make sure it' doesn’t end up killing perf on you. You’ve been warned :-}. How does ResponseFilterStream work? The big win of this implementation IMHO is that it’s a reusable  component – so for implementation there’s no new class, no subclassing – you simply attach to an event to implement an event handler method with a straight forward signature to retrieve the stream or string you’re interested in. The implementation is based on a subclass of Stream as is required in order to handle the Response.Filter requirements. What’s different than other implementations I’ve seen in various places is that it supports capturing output as a whole to allow retrieving the full response output for capture or modification. The exception are the TransformWrite and TransformWrite events which operate only active chunk of data written by the Response. For captured output, the Write() method captures output into an internal MemoryStream that is cached until writing is complete. So Write() is called when ASP.NET writes to the Response stream, but the filter doesn’t pass on the Write immediately to the filter’s internal stream. The data is cached and only when the Flush() method is called to finalize the Stream’s output do we actually send the cached stream off for transformation (if the events are hooked up) and THEN finally write out the returned content in one big chunk. Here’s the implementation of ResponseFilterStream: /// <summary> /// A semi-generic Stream implementation for Response.Filter with /// an event interface for handling Content transformations via /// Stream or String. /// <remarks> /// Use with care for large output as this implementation copies /// the output into a memory stream and so increases memory usage. /// </remarks> /// </summary> public class ResponseFilterStream : Stream { /// <summary> /// The original stream /// </summary> Stream _stream; /// <summary> /// Current position in the original stream /// </summary> long _position; /// <summary> /// Stream that original content is read into /// and then passed to TransformStream function /// </summary> MemoryStream _cacheStream = new MemoryStream(5000); /// <summary> /// Internal pointer that that keeps track of the size /// of the cacheStream /// </summary> int _cachePointer = 0; /// <summary> /// /// </summary> /// <param name="responseStream"></param> public ResponseFilterStream(Stream responseStream) { _stream = responseStream; } /// <summary> /// Determines whether the stream is captured /// </summary> private bool IsCaptured { get { if (CaptureStream != null || CaptureString != null || TransformStream != null || TransformString != null) return true; return false; } } /// <summary> /// Determines whether the Write method is outputting data immediately /// or delaying output until Flush() is fired. /// </summary> private bool IsOutputDelayed { get { if (TransformStream != null || TransformString != null) return true; return false; } } /// <summary> /// Event that captures Response output and makes it available /// as a MemoryStream instance. Output is captured but won't /// affect Response output. /// </summary> public event Action<MemoryStream> CaptureStream; /// <summary> /// Event that captures Response output and makes it available /// as a string. Output is captured but won't affect Response output. /// </summary> public event Action<string> CaptureString; /// <summary> /// Event that allows you transform the stream as each chunk of /// the output is written in the Write() operation of the stream. /// This means that that it's possible/likely that the input /// buffer will not contain the full response output but only /// one of potentially many chunks. /// /// This event is called as part of the filter stream's Write() /// operation. /// </summary> public event Func<byte[], byte[]> TransformWrite; /// <summary> /// Event that allows you to transform the response stream as /// each chunk of bytep[] output is written during the stream's write /// operation. This means it's possibly/likely that the string /// passed to the handler only contains a portion of the full /// output. Typical buffer chunks are around 16k a piece. /// /// This event is called as part of the stream's Write operation. /// </summary> public event Func<string, string> TransformWriteString; /// <summary> /// This event allows capturing and transformation of the entire /// output stream by caching all write operations and delaying final /// response output until Flush() is called on the stream. /// </summary> public event Func<MemoryStream, MemoryStream> TransformStream; /// <summary> /// Event that can be hooked up to handle Response.Filter /// Transformation. Passed a string that you can modify and /// return back as a return value. The modified content /// will become the final output. /// </summary> public event Func<string, string> TransformString; protected virtual void OnCaptureStream(MemoryStream ms) { if (CaptureStream != null) CaptureStream(ms); } private void OnCaptureStringInternal(MemoryStream ms) { if (CaptureString != null) { string content = HttpContext.Current.Response.ContentEncoding.GetString(ms.ToArray()); OnCaptureString(content); } } protected virtual void OnCaptureString(string output) { if (CaptureString != null) CaptureString(output); } protected virtual byte[] OnTransformWrite(byte[] buffer) { if (TransformWrite != null) return TransformWrite(buffer); return buffer; } private byte[] OnTransformWriteStringInternal(byte[] buffer) { Encoding encoding = HttpContext.Current.Response.ContentEncoding; string output = OnTransformWriteString(encoding.GetString(buffer)); return encoding.GetBytes(output); } private string OnTransformWriteString(string value) { if (TransformWriteString != null) return TransformWriteString(value); return value; } protected virtual MemoryStream OnTransformCompleteStream(MemoryStream ms) { if (TransformStream != null) return TransformStream(ms); return ms; } /// <summary> /// Allows transforming of strings /// /// Note this handler is internal and not meant to be overridden /// as the TransformString Event has to be hooked up in order /// for this handler to even fire to avoid the overhead of string /// conversion on every pass through. /// </summary> /// <param name="responseText"></param> /// <returns></returns> private string OnTransformCompleteString(string responseText) { if (TransformString != null) TransformString(responseText); return responseText; } /// <summary> /// Wrapper method form OnTransformString that handles /// stream to string and vice versa conversions /// </summary> /// <param name="ms"></param> /// <returns></returns> internal MemoryStream OnTransformCompleteStringInternal(MemoryStream ms) { if (TransformString == null) return ms; //string content = ms.GetAsString(); string content = HttpContext.Current.Response.ContentEncoding.GetString(ms.ToArray()); content = TransformString(content); byte[] buffer = HttpContext.Current.Response.ContentEncoding.GetBytes(content); ms = new MemoryStream(); ms.Write(buffer, 0, buffer.Length); //ms.WriteString(content); return ms; } /// <summary> /// /// </summary> public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } /// <summary> /// /// </summary> public override bool CanWrite { get { return true; } } /// <summary> /// /// </summary> public override long Length { get { return 0; } } /// <summary> /// /// </summary> public override long Position { get { return _position; } set { _position = value; } } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="direction"></param> /// <returns></returns> public override long Seek(long offset, System.IO.SeekOrigin direction) { return _stream.Seek(offset, direction); } /// <summary> /// /// </summary> /// <param name="length"></param> public override void SetLength(long length) { _stream.SetLength(length); } /// <summary> /// /// </summary> public override void Close() { _stream.Close(); } /// <summary> /// Override flush by writing out the cached stream data /// </summary> public override void Flush() { if (IsCaptured && _cacheStream.Length > 0) { // Check for transform implementations _cacheStream = OnTransformCompleteStream(_cacheStream); _cacheStream = OnTransformCompleteStringInternal(_cacheStream); OnCaptureStream(_cacheStream); OnCaptureStringInternal(_cacheStream); // write the stream back out if output was delayed if (IsOutputDelayed) _stream.Write(_cacheStream.ToArray(), 0, (int)_cacheStream.Length); // Clear the cache once we've written it out _cacheStream.SetLength(0); } // default flush behavior _stream.Flush(); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override int Read(byte[] buffer, int offset, int count) { return _stream.Read(buffer, offset, count); } /// <summary> /// Overriden to capture output written by ASP.NET and captured /// into a cached stream that is written out later when Flush() /// is called. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public override void Write(byte[] buffer, int offset, int count) { if ( IsCaptured ) { // copy to holding buffer only - we'll write out later _cacheStream.Write(buffer, 0, count); _cachePointer += count; } // just transform this buffer if (TransformWrite != null) buffer = OnTransformWrite(buffer); if (TransformWriteString != null) buffer = OnTransformWriteStringInternal(buffer); if (!IsOutputDelayed) _stream.Write(buffer, offset, buffer.Length); } } The key features are the events and corresponding OnXXX methods that handle the event hookups, and the Write() and Flush() methods of the stream implementation. All the rest of the members tend to be plain jane passthrough stream implementation code without much consequence. I do love the way Action<t> and Func<T> make it so easy to create the event signatures for the various events – sweet. A few Things to consider Performance Response.Filter is not great for performance in general as it adds another layer of indirection to the ASP.NET output pipeline, and this implementation in particular adds a memory hit as it basically duplicates the response output into the cached memory stream which is necessary since you may have to look at the entire response. If you have large pages in particular this can cause potentially serious memory pressure in your server application. So be careful of wholesale adoption of this (or other) Response.Filters. Make sure to do some performance testing to ensure it’s not killing your app’s performance. Response.Filter works everywhere A few questions came up in comments and discussion as to capturing ALL output hitting the site and – yes you can definitely do that by assigning a Response.Filter inside of a module. If you do this however you’ll want to be very careful and decide which content you actually want to capture especially in IIS 7 which passes ALL content – including static images/CSS etc. through the ASP.NET pipeline. So it is important to filter only on what you’re looking for – like the page extension or maybe more effectively the Response.ContentType. Response.Filter Chaining Originally I thought that filter chaining doesn’t work at all due to a bug in the stream implementation code. But it’s quite possible to assign multiple filters to the Response.Filter property. So the following actually works to both compress the output and apply the transformed content: WebUtils.GZipEncodePage(); ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; However the following does not work resulting in invalid content encoding errors: ResponseFilterStream filter = new ResponseFilterStream(Response.Filter); filter.TransformString += filter_TransformString; Response.Filter = filter; WebUtils.GZipEncodePage(); In other words multiple Response filters can work together but it depends entirely on the implementation whether they can be chained or in which order they can be chained. In this case running the GZip/Deflate stream filters apparently relies on the original content length of the output and chokes when the content is modified. But if attaching the compression first it works fine as unintuitive as that may seem. Resources Download example code Capture Output from ASP.NET Pages © Rick Strahl, West Wind Technologies, 2005-2010Posted in ASP.NET  

    Read the article

  • Subterranean IL: Filter exception handlers

    - by Simon Cooper
    Filter handlers are the second type of exception handler that aren't accessible from C#. Unlike the other handler types, which have defined conditions for when the handlers execute, filter lets you use custom logic to determine whether the handler should be run. However, similar to a catch block, the filter block does not get run if control flow exits the block without throwing an exception. Introducing filter blocks An example of a filter block in IL is the following: .try { // try block } filter { // filter block endfilter }{ // filter handler } or, in v1 syntax, TryStart: // try block TryEnd: FilterStart: // filter block HandlerStart: // filter handler HandlerEnd: .try TryStart to TryEnd filter FilterStart handler HandlerStart to HandlerEnd In the v1 syntax there is no end label specified for the filter block. This is because the filter block must come immediately before the filter handler; the end of the filter block is the start of the filter handler. The filter block indicates to the CLR whether the filter handler should be executed using a boolean value on the stack when the endfilter instruction is run; true/non-zero if it is to be executed, false/zero if it isn't. At the start of the filter block, and the corresponding filter handler, a reference to the exception thrown is pushed onto the stack as a raw object (you have to manually cast to System.Exception). The allowed IL inside a filter block is tightly controlled; you aren't allowed branches outside the block, rethrow instructions, and other exception handling clauses. You can, however, use call and callvirt instructions to call other methods. Filter block logic To demonstrate filter block logic, in this example I'm filtering on whether there's a particular key in the Data dictionary of the thrown exception: .try { // try block } filter { // Filter starts with exception object on stack // C# code: ((Exception)e).Data.Contains("MyExceptionDataKey") // only execute handler if Contains returns true castclass [mscorlib]System.Exception callvirt instance class [mscorlib]System.Collections.IDictionary [mscorlib]System.Exception::get_Data() ldstr "MyExceptionDataKey" callvirt instance bool [mscorlib]System.Collections.IDictionary::Contains(object) endfilter }{ // filter handler // Also starts off with exception object on stack callvirt instance string [mscorlib]System.Object::ToString() call void [mscorlib]System.Console::WriteLine(string) } Conclusion Filter exception handlers are another exception handler type that isn't accessible from C#, however, just like fault handlers, the behaviour can be replicated using a normal catch block: try { // try block } catch (Exception e) { if (!FilterLogic(e)) throw; // handler logic } So, it's not that great a loss, but it's still annoying that this functionality isn't directly accessible. Well, every feature starts off with minus 100 points, so it's understandable why something like this didn't make it into the C# compiler ahead of a different feature.

    Read the article

  • Mean filter in MATLAB without loops or signal processing toolbox

    - by Doresoom
    I need to implement a mean filter on a data set, but I don't have access to the signal processing toolbox. Is there a way to do this without using a for loop? Here's the code I've got working: x=0:.1:10*pi; noise=0.5*(rand(1,length(x))-0.5); y=sin(x)+noise; %generate noisy signal a=10; %specify moving window size my=zeros(1,length(y)-a); for n=a/2+1:length(y)-a/2 my(n-a/2)=mean(y(n-a/2:n+a/2)); %calculate mean for each window end mx=x(a/2+1:end-a/2); %truncate x array to match plot(x,y) hold on plot(mx,my,'r')

    Read the article

  • Modify the filter chain - Or select servlet to respond to request using filter

    - by klonq
    I am trying to use a filter to map requests. I am trying to do this for two reasons, firstly to dynamically generate URI's and have them mapped to the appropriate servlet and secondly to catch URI's which are not registered and handle them appropriately. So I'm using a catch-all filter to process the URI and determine the response. I would like some way of modifying the filter chain, or some way to set the servlet which responds to the request from within the filter. I have been unsuccessful using filterConfig.getServletContext().getRequestDispatcher().forward() to send to jsp, ideally though I would like to map to a servlet but can't figure out how. The reason I am not doing this from within a servlet is that I have some URIs which are fixed within web.xml and if I use a catch-all servlet those URIs do not get mapped. Is this possible, is it clean or it going to get really messy?

    Read the article

  • I have a filter for jquery masonry - but I want to filter moomasonry

    - by Jason
    Hi, I'm using jquery masonry for layout. But I am considering moving to mootools. I have found a masonry port to mootools, called moomasonry - http://www.crionics.com/products/opensource/mooMasonry/Demos/basic.html With help here, I have a filter on the masonry divs by class: $('a.filter').click(function(){ filterBoxes(this.id); }) function filterBoxes(klass){ if (klass == "all") { klass = "box" } $('#holder').find('.' + klass) .hide() .appendTo('#main') .fadeIn('200') $('#main').find('.box:not(.' + klass + ')') .fadeOut( '200', function(){ $(this).appendTo('#holder') ; }); setTimeout(function(){ $('#main').masonry() },500); } But, how would I filter divs by class in mootools? and have it reload masonry after each filter. See my site for example: http://jasondaydesign.com/masonry_demo/

    Read the article

  • How to filter the jqGrid data NOT using the built in search/filter box

    - by Jimbo
    I want users to be able to filter grid data without using the intrinsic search box. I have created two input fields for date (from and to) and now need to tell the grid to adopt this as its filter and then to request new data. Forging a server request for grid data (bypassing the grid) and setting the grid's data to be the response data wont work - because as soon as the user tries to re-order the results or change the page etc. the grid will request new data from the server using a blank filter. I cant seem to find grid API to achieve this - does anyone have any ideas? Thanks.

    Read the article

  • Exclude filter from certain url's

    - by Mads Mobæk
    I'm using a filter in web.xml to check if a user is logged in or not: <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.mycompany.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> And this works like a charm until I have a stylesheet or image I want to exclude from this filter. I know one approach is to put everything that's protected inside /privateor similar, and then set the url-pattern to: <url-pattern>/private/*</url-pattern>. The downside to this is my URLs now looking like: http://www.mycompany.com/private/mypage instead of http://www.mycompany.com/mypage. Is there another solution to this problem, that let me keep my pretty-urls?

    Read the article

  • PHP Filter, how to filter input array

    - by esryl
    I am using PHP filter to perfom basic sanitization and validation of form data. The principle problem I am having is that I mark my form up so that all the data is in one array for the POST input. e.g. form fields, page[name], page[slug], page[body], page[status], etc. Using the following: filter_input(INPUT_POST, 'page[name]', FILTER_SANITIZE_STRING); OR filter_input(INPUT_POST, "page['name']", FILTER_SANITIZE_STRING); I am unable to access the variable. Can someone please tell me the correct name to use to access array data using filter_input()

    Read the article

  • Apply LADSPA filter to only one channel of multichannel output with Alsa and PulseAudio

    - by justinzane
    I want to apply a filter, specifically SWH's glame-bandpass-iir, to only one of several output channels. I want unfiltered output to go to the front, rear and LFE channels with bandpass filtered output for the center channel. I'm assuming that this needs to be done with Alsa's /etc/asound.conf but I cannot understand the documentation well enough to figure out how. If there is a better way, via PulseAudio, Jack or whatever, I'm open to whatever works. Thanks.

    Read the article

  • Where to define a filter function for a form field in my Joomla component's preferences

    - by Herman
    I am creating a component in Joomla 2.5. This component has some options that are defined in its config.xml, so they can be set in the preferences of the component. Now I would like to apply a filter to one of these option fields, using the attribute filter="my_filter". In the source code of JForm I saw the following lines at the very end of the implementation of JForm::filterField(): if (strpos($filter, '::') !== false && is_callable(explode('::', $filter))) { $return = call_user_func(explode('::', $filter), $value); } elseif (function_exists($filter)) { $return = call_user_func($filter, $value); } That's what I needed for using a filter function defined by myself! I managed to do this for form fields used in the views of my component. I defined the filter function as MyComponentHelper::my_filter(), where MyComponentHelper is a helper class which I always load in the very base of my component. And in the form's xml I added filter="MyComponentHelper::my_filter" to the fields that have to be filtered. However... when I am trying to apply the filter function to a form field in my component's preferences, I am not in my own component, but in com_config instead, so my helper class is not available! So, therefore, my question: where to define my own filter function in such a way that it can be found and called by JForm::filterField() in com_config?? Help is very much appreciated.

    Read the article

  • ASP.NET MVC Response Filter + OutputCache Attribute

    - by Shane Andrade
    I'm not sure if this is an ASP.NET MVC specific thing or ASP.NET in general but here's what's happening. I have an action filter that removes whitespace by the use of a response filter: public class StripWhitespaceAttribute : ActionFilterAttribute { public StripWhitespaceAttribute () { } public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response.Filter); } } When used in conjunction with the OutputCache attribute, my calls to Response.WriteSubstitution for "donut hole caching" do not work. The first and second time the page loads the callback passed to WriteSubstitution get called, after that they are not called anymore until the output cache expires. I've noticed this with not just this particular filter but any filter used on Response.Filter... am I missing something? I also forgot to mention I've tried this without the use of an MVC action filter attribute by attaching to the PostReleaseRequestState event in the global.asax and setting the Response.Filter value there... but still no luck.

    Read the article

  • Double Filter in Excel

    - by Joe
    I'm trying to "stack" filters in excel, so to speak. I want to filter column A to show anything greater than 30 and then I want to filter column B to show the top ten items. When I do this, however, it shows me all rows that fit both criteria (only five records). I want to first fit the criteria for column A and then filter these results to show the top ten items in column B (10 records total). I know that I could just copy the rows from my first filter to a new sheet and then filter the new worksheet, but is there any way to apply both filters so that I don't physically have to delete records this way? Thanks for your help!

    Read the article

  • compute mean in python for a generator

    - by nmaxwell
    Hi, I'm doing some statistics work, I have a (large) collection of random numbers to compute the mean of, I'd like to work with generators, because I just need to compute the mean, so I don't need to store the numbers. The problem is that numpy.mean breaks if you pass it a generator. I can write a simple function to do what I want, but I'm wondering if there's a proper, built-in way to do this? It would be nice if I could say "sum(values)/len(values)", but len doesn't work for genetators, and sum already consumed values. here's an example: import numpy def my_mean(values): n = 0 Sum = 0.0 try: while True: Sum += next(values) n += 1 except StopIteration: pass return float(Sum)/n X = [k for k in range(1,7)] Y = (k for k in range(1,7)) print numpy.mean(X) print my_mean(Y) these both give the same, correct, answer, buy my_mean doesn't work for lists, and numpy.mean doesn't work for generators. I really like the idea of working with generators, but details like this seem to spoil things. thanks for any help -nick

    Read the article

  • Create a Search Filter List in Google Chrome

    - by Asian Angel
    Are you tired of unwanted and/or non-relevant results cluttering up the search results at Bing, Yahoo, and Google? With the Search Filter extension for Chrome you can easily remove the unwanted “chaff” from your search results. Note: The extension only works on Bing, Yahoo, and Google at this time. Before For our example we conducted a search for “anime wallpapers” at Yahoo Singapore, Bing Singapore, and Google. In each set of results we decided to focus on results that would display either a yellow or red warning color from WOT. You can see our targeted result for Yahoo Singapore… The one for Bing Singapore… And the targeted result from Google. Search Filter in Action As soon as you install the extension you should take a quick look at the “Options”. At first the “Filters List Area” will be empty but will not remain so for long as you create your own filter list. The second part may or may not be of interest to you…the ability to opt into the filter service. If you opt in your filter list will be connected to your “Google Account” and will be available on any of your Chrome installs with the extension installed (and set to “Opt In”). Keep in mind that if you choose this option the filter list that you create will be aggregated anonymously and have a GUID number attached to it. After installing the extension we refreshed each of our three search pages…notice the small red circle button beside each search result link. Clicking on the red circle button will cause the entire browser window area to “shade out” temporarily while you decide between adding that website to the filter list or cancelling the action. If you add a website to the filter list that result will immediately disappear from the search results list without refreshing the webpage. Looks like we have another website at the bottom that we could add to the filter list… Click, click, click! After adding one website from each of the three search services you can see that our filter list has gotten off to a nice start. If for some reason you accidentally add a website to the list or change your mind about a website simply click on the red circle button to remove that particular listing. Conclusion If you are looking for an easy way to create a search filter list then this is definitely an extension that is worth taking the time to look at. Links Download the Search Filter extension (Google Chrome Extensions) Visit the Search Filter Hub Website to View Lists of Filtered Sites Similar Articles Productive Geek Tips How to Make Google Chrome Your Default BrowserGeek’s Spam Filter – Updated to Version 0.2Access Wolfram Alpha Search in Google ChromeGain Access to a Search Box in Google ChromeGeek’s Spam Filter – Updated to Version 0.3 TouchFreeze Alternative in AutoHotkey The Icy Undertow Desktop Windows Home Server – Backup to LAN The Clear & Clean Desktop Use This Bookmarklet to Easily Get Albums Use AutoHotkey to Assign a Hotkey to a Specific Window Latest Software Reviews Tinyhacker Random Tips Revo Uninstaller Pro Registry Mechanic 9 for Windows PC Tools Internet Security Suite 2010 PCmover Professional Scan News With NY Times Article Skimmer SpeedyFox Claims to Speed up your Firefox Beware Hover Kitties Test Drive Mobile Phones Online With TryPhone Ben & Jerry’s Free Cone Day, 3/23/10 New Stinger from McAfee Helps Remove ‘FakeAlert’ Threats

    Read the article

  • Using a javax.servlet.Filter with Compojure

    - by mikera
    I'm trying to build a simple web site using Clojure / Compojure and want to feed apply a servlet filter to the request / response (i.e. a standard javax.servlet.Filter instance). e.g. if the current source code is: (defroutes my-app (GET "/*" (html [:h1 "Hello Foo!!"])) ) I would like to add a filter like this: (defroutes my-app (GET "/*" (FILTER my-filter-name (html [:h1 "Hello Foo!!"]))) ) Where my-filter-name is some arbitrary instance of javax.servlet.Filter. Any idea how to do this effectively and elegantly?

    Read the article

  • Allow email from a particular sender through spam filter

    - by Greg
    We are running exchange 2010 and are using the built in anti-spam feature. We have set up Content Filtering, IP Block List Providers, Sender ID, Sender Reputation and it filters out most of the junk but it also quarantines all emails from one of our customers. It is being quarantined because of the Content Filter agent (Report Below). How can I add an exception for this email address to the Content Filter. I can see how to setup an exception for a delivery address ("Don't filter messages sent TO the following recipients") but I want to add [email protected] to our safe list. I don't want to add the whole domain as it is a very popular ISP in Australia and we often get junk from them. Filter Report: > Diagnostic information for administrators: > > Generating server: something.com > > [email protected] > #550 5.2.1 Content Filter agent quarantined this message ## > > Original message headers: > > Received: from icp-osb-irony-out4.external.iinet.net.au (203.59.1.220) > by server.local.something.com.au (192.5.0.105) with Microsoft SMTP > Server id > 14.1.218.12; Mon, 5 Nov 2012 02:40:40 +1100 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: > AscOALeLllB8qwLw/2dsb2JhbABEKYUFhiigRQOWCwQEgQiBCIIZFAEBTiwCCAIBBwEIFDkBBBoqARoCAQIDAYd4uEuRXGEDiCWFT44UijeDAw > X-IronPort-AV: E=Sophos;i="4.80,710,1344182400"; > d="scan'208,217";a="55137861" Received: from unknown (HELO > asdf83c05c53a3) ([124.171.2.240]) by icp-osb-irony-out4.iinet.net.au > with ESMTP; 04 Nov 2012 23:40:26 +0800 Message-ID: > <E8C866D0299E4BCB8B156723893EB735@asdf83c05c53a3> From: Customer > <[email protected]> To: 'Person' <[email protected]> > Subject: A long sentance Date: Mon, 5 Nov 2011 06:07:57 +1100 > MIME-Version: 1.0 Content-Type: multipart/alternative; > boundary="----=_NextPart_000_0005_01C5F962.3CD09120" X-Priority: 3 > X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express > 6.00.2900.5931 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.6157 Return-Path: [email protected] Received-SPF: None > (server.local.something.com.au: [email protected] does not > designate permitted sender hosts)

    Read the article

  • web.xml - Java Servlet Filters and WebSphere - URL Pattern issues

    - by Ed
    Hi, So we are running a web application that has been tested on Tomcat, Glassfish, WebLogic and WebSphere. All run correctly except WebSphere. The issue is that filters are not processed for files under a certain directory. For example I have a filter that checks the user's lanuage from browser cookies and another that get the user's username, in the web.xml there are configured like so: <!-- ****************************** --> <!-- * Security context filtering * --> <!-- ****************************** --> <filter> <filter-name>SetSecurityContextFilter</filter-name> <filter-class> com.test.security.SecurityContextServletFilter </filter-class> </filter> <!-- ****************************** --> <!-- ** Locale context filtering ** --> <!-- ****************************** --> <filter> <filter-name>SetLocaleFilter</filter-name> <filter-class> com.test.locale.LocaleServletFilter </filter-class> </filter> <filter-mapping> <filter-name>SetSecurityContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>SetLocaleFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Both filters set a static threadlocal variable which can be accessed from a static getter, but when the same file 'test.jsp' invokes the getters, under 'contextroot/js' they return the default values (as if unset) while under 'contextroot/pages' they are correct. Any ideas? Thanks in advance.

    Read the article

  • Adding Netem Filter Rules

    - by fontsix
    iam new in programming and using linux. My Question is, is it possible to add Netem Filter Rules later ? I want to create an PHP-Interface for Netem and I don't know how much filters were required. This should be some kind of dynamically. In Example : A user with a static IP starts an Netem Command (Latency) with PHP Interface this means these five command werde executed by php in the first step $classid = 11; $handle = 10; "sudo tc qdisc add dev eth0 handle 1: root htb"; "sudo tc class add dev eth0 parent 1: classid 1:1 htb rate 100Mbps"; "sudo tc class add dev eth0 parent 1:1 classid 1:$classid htb rate 100Mbps"; "sudo tc qdisc add dev eth0 parent 1:$classid handle $handle: netem delay 100ms"; "sudo tc filter add dev eth0 protocol ip parent 1:0 prio 3 u32 match ip dst $dest flowid 1:$classid"; Now, if there would be a second user who wants to use Netem independent of the first user, i only want to execute the last 3 commands, like "sudo tc class add dev eth0 parent 1:1 classid 1:$classid htb rate 100Mbps"; "sudo tc qdisc add dev eth0 parent 1:$classid handle $handle: netem delay 100ms"; "sudo tc filter add dev eth0 protocol ip parent 1:0 prio 3 u32 match ip dst $dest flowid 1:$classid"; There is an Algorithmus for increasing variables $classid and $handle. This should work. Now my Question: Is it possible only to add these 3 commands to add a new class with new qdisc and a new filter rule ? Or how can i realize it ? The Apache Error_log tells me "sh: line 1: flowid: command not found" but i can't find any mistake. I hope you could help Best regards fontsix

    Read the article

  • DirectShow Filter I wrote dies after 10-24 seconds in Skype video call

    - by Robert Oschler
    I've written a DirectShow push filter for use with Skype using Delphi Pro 6 and the DSPACK DirectShow library. In preview mode, when you test a video input device in the Skype client Video Settings window, my filter works flawlessly. I can leave it up and running for many minutes without an error. However when I start a video call after 10 to 24 seconds, never longer, the video feed freezes. The call continues fine with the call duration counter clicking away the seconds, but the video feed is dead, stuck on whatever frame the freeze happened (although after a long while it turns black which I believe means Skype has given up on the filter). I tried attaching to the process from my debugger with a breakpoint literally set on every method call and none of them are hit once the freeze takes place. It's as if the thread that makes the DirectShow FillBuffer() call to my filter on behalf of Skype is dead or has been shutdown. I can't trace my filter in the debugger because during a Skype call I get weird int 1 and int 3 debugger hard interrupt calls when a Skype video call is in progress. This behavior happens even with my standard web cam input device selected and my DirectShow filter completely unregistered as a ActiveX server. I suspect it might be some "anti-debugging" code since it doesn't happen in video input preview mode. Either way, that is why I had to attach to the process after the fact to see if my FillBuffer() called was still being called and instead discovered that appears to be dead. Note, my plain vanilla USB web cam's DirectShow filter does not exhibit the freezing behavior and works fine for many minutes. There's something about my filter that Skype doesn't like. I've tried Sleep() statements of varying intervals, no Sleep statements, doing virtually nothing in the FillBuffer() call. Nothing helps. If anyone has any ideas on what might be the culprit here, I'd like to know. Thanks, Robert

    Read the article

  • Instantiate object from Linq to XML Query

    - by objectsbinding
    Hi All I have the following class public class CountrySpecificPIIEntity { public string Country { get; set; } public string CreditCardType { get; set; } public String Api { get; set; } public List<String> FilterList { get; set; } } I am trying to use a linq to XMl query to create a list of instances of type CountrySpecificPIIEntity. The XML is as below <piisettings> <country countrycode="DE"> <creditcardype credicardtype="mastercard"> <api api="INSERT_FILTERS"> <filters> <filter>FIRSTNAME</filter> <filter>HOUSENUMBER</filter> <filter>ADDITIONALADDRESSINFO</filter> <filter>EMAIL</filter> </filters> </api> </creditcardype> <creditcardype credicardtype="visa"> <api api="INSERT_FILTERS"> <filters> <filter>STATE</filter> <filter>EMAIL</filter> </filters> </api> </creditcardype> <creditcardype credicardtype="visa"> <api api="UPDATE_FILTERS"> <filters> <filter>STATE</filter> <filter>EMAIL</filter> </filters> </api> </creditcardype> </country> <country countrycode="GB"> <creditcardype credicardtype="americanexpress"> <api api="INSERT_FILTERS"> <filters> <filter>STREET</filter> <filter>ZIP</filter> <filter>CITY</filter> <filter>STATE</filter> <filter>EMAIL</filter> </filters> </api> </creditcardype> <creditcardype credicardtype="debank"> <api api="INSERT_FILTERS"> <filters> <filter>IPADDRESSCUSTOMER</filter> <filter>FIRSTNAME</filter> <filter>SURNAME</filter> <filter>HOUSENUMBER</filter> <filter>STREET</filter> <filter>ZIP</filter> <filter>CITY</filter> <filter>STATE</filter> <filter>EMAIL</filter> </filters> </api> </creditcardype> </country> </piisettings> what should the Linq to XML query be?

    Read the article

  • grouping objects to achieve a similar mean property for all groups

    - by cytochrome
    I have a collection of objects, each of which has a numerical 'weight'. I would like to create groups of these objects such that each group has approximately the same arithmetic mean of object weights. The groups won't necessarily have the same number of members, but the size of groups will be within one of each other. In terms of numbers, there will be between 50 and 100 objects and the maximum group size will be about 5. Is this a well-known type of problem? It seems a bit like a knapsack or partition problem. Are efficient algorithms known to solve it? As a first step, I created a python script that achieves very crude equivalence of mean weights by sorting the objects by weight, subgrouping these objects, and then distributing a member of each subgroup to one of the final groups. I am comfortable programming in python, so if existing packages or modules exist to achieve part of this functionality, I'd appreciate hearing about them. Thank you for your help and suggestions.

    Read the article

  • JAVA: Can't get context parameters in Filter

    - by DaTval
    Hello, I have a filter and parameters in web.xml web.xml is like this: <filter> <description> </description> <display-name>AllClassFilter</display-name> <filter-name>AllClassFilter</filter-name> <filter-class>com.datval.homework.AllClassFilter</filter-class> <init-param> <param-name>DB_URL</param-name> <param-value>jdbc:derby:C:/Users/admin/workspace/homework03/homework/databases/StudentsDB;create=true</param-value> </init-param> <init-param> <param-name>DB_DIALECT</param-name> <param-value>org.hibernate.dialect.DerbyDialect</param-value> </init-param> <init-param> <param-name>DB_DRIVER</param-name> <param-value>org.apache.derby.jdbc.EmbeddedDriver</param-value> </init-param> </filter> mapping is working well. But I can't get this parameters in my filter. public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub debugMessage = config.getInitParameter("debugMessage"); ctx = config.getServletContext(); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here ctx.log("Start - " + debugMessage); String myDbUrl = ctx.getInitParameter("DB_URL"); String DB_DIALECT = ctx.getInitParameter("DB_DIALECT"); String DB_DRIVER = ctx.getInitParameter("DB_DRIVER"); Map<String,String> pr = new HashMap<String,String>(); pr.put("hibernate.connection.url", myDbUrl); pr.put("hibernate.dialect", DB_DIALECT); pr.put("hibernate.connection.driver_class", DB_DRIVER); EntityManagerFactory emf = Persistence.createEntityManagerFactory("students",pr); EntityManager em = emf.createEntityManager(); request.setAttribute("em", em); chain.doFilter(request, response); em.close(); ctx.log("end - " + debugMessage); } I have checked and myDbUrl is null. What I'm doing wrong? Any idea? Sorry about code, I will change it later :)

    Read the article

  • MvcExtensions - ActionFilter

    - by kazimanzurrashid
    One of the thing that people often complains is dependency injection in Action Filters. Since the standard way of applying action filters is to either decorate the Controller or the Action methods, there is no way you can inject dependencies in the action filter constructors. There are quite a few posts on this subject, which shows the property injection with a custom action invoker, but all of them suffers from the same small bug (you will find the BuildUp is called more than once if the filter implements multiple interface e.g. both IActionFilter and IResultFilter). The MvcExtensions supports both property injection as well as fluent filter configuration api. There are a number of benefits of this fluent filter configuration api over the regular attribute based filter decoration. You can pass your dependencies in the constructor rather than property. Lets say, you want to create an action filter which will update the User Last Activity Date, you can create a filter like the following: public class UpdateUserLastActivityAttribute : FilterAttribute, IResultFilter { public UpdateUserLastActivityAttribute(IUserService userService) { Check.Argument.IsNotNull(userService, "userService"); UserService = userService; } public IUserService UserService { get; private set; } public void OnResultExecuting(ResultExecutingContext filterContext) { // Do nothing, just sleep. } public void OnResultExecuted(ResultExecutedContext filterContext) { Check.Argument.IsNotNull(filterContext, "filterContext"); string userName = filterContext.HttpContext.User.Identity.IsAuthenticated ? filterContext.HttpContext.User.Identity.Name : null; if (!string.IsNullOrEmpty(userName)) { UserService.UpdateLastActivity(userName); } } } As you can see, it is nothing different than a regular filter except that we are passing the dependency in the constructor. Next, we have to configure this filter for which Controller/Action methods will execute: public class ConfigureFilters : ConfigureFiltersBase { protected override void Configure(IFilterRegistry registry) { registry.Register<HomeController, UpdateUserLastActivityAttribute>(); } } You can register more than one filter for the same Controller/Action Methods: registry.Register<HomeController, UpdateUserLastActivityAttribute, CompressAttribute>(); You can register the filters for a specific Action method instead of the whole controller: registry.Register<HomeController, UpdateUserLastActivityAttribute, CompressAttribute>(c => c.Index()); You can even set various properties of the filter: registry.Register<ControlPanelController, CustomAuthorizeAttribute>( attribute => { attribute.AllowedRole = Role.Administrator; }); The Fluent Filter registration also reduces the number of base controllers in your application. It is very common that we create a base controller and decorate it with action filters and then we create concrete controller(s) so that the base controllers action filters are also executed in the concrete controller. You can do the  same with a single line statement with the fluent filter registration: Registering the Filters for All Controllers: registry.Register<ElmahHandleErrorAttribute>(new TypeCatalogBuilder().Add(GetType().Assembly).Include(type => typeof(Controller).IsAssignableFrom(type))); Registering Filters for selected Controllers: registry.Register<ElmahHandleErrorAttribute>(new TypeCatalogBuilder().Add(GetType().Assembly).Include(type => typeof(Controller).IsAssignableFrom(type) && (type.Name.StartsWith("Home") || type.Name.StartsWith("Post")))); You can also use the built-in filters in the fluent registration, for example: registry.Register<HomeController, OutputCacheAttribute>(attribute => { attribute.Duration = 60; }); With the fluent filter configuration you can even apply filters to controllers that source code is not available to you (may be the controller is a part of a third part component). That’s it for today, in the next post we will discuss about the Model binding support in MvcExtensions. So stay tuned.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >