1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle
.MonoRail
.Framework
.Filters
18 using System
.Configuration
;
19 using System
.Globalization
;
20 using System
.Threading
;
23 /// Enum to identify where a value is stored.
25 public enum RequestStore
28 /// Value is stored in the Session object.
32 /// Value is stored in a cookie object.
36 /// Value is stored in the querystring.
40 /// Value is stored in the form collection.
44 /// Value is stored in either query string or form collection.
50 /// The LocalizationFilter can be used to determine the culture to use
51 /// for resources and UI.
53 public class LocalizationFilter
: IFilter
, IFilterAttributeAware
55 private LocalizationFilterAttribute setup
;
57 #region IFilterAttributeAware Members
59 public FilterAttribute Filter
63 if (!(value is LocalizationFilterAttribute
))
65 String message
= "LocalizationFilter can only be defined by a LocalizationFilterAttribute.";
66 throw new ConfigurationErrorsException(message
);
69 setup
= value as LocalizationFilterAttribute
;
75 #region IFilter Members
77 public bool Perform(ExecuteEnum exec
, IRailsEngineContext context
, Controller controller
)
81 String localeId
= GetLocaleId(context
);
83 if (localeId
== null && setup
.UseBrowser
)
84 localeId
= GetUserLanguage(context
.Request
);
88 CultureInfo culture
= CultureInfo
.CreateSpecificCulture(localeId
);
90 Thread
.CurrentThread
.CurrentCulture
= culture
;
91 Thread
.CurrentThread
.CurrentUICulture
= culture
;
96 if (setup
.FailOnError
) throw;
104 #region Get locale id from the store
106 private String
GetUserLanguage(IRequest request
)
108 if (request
.UserLanguages
!= null && request
.UserLanguages
.Length
> 0)
109 return request
.UserLanguages
[0];
114 private String
GetLocaleId(IRailsEngineContext context
)
118 case RequestStore
.Session
:
119 return context
.Session
[setup
.Key
] as String
;
120 case RequestStore
.Cookie
:
121 return context
.Request
.ReadCookie(setup
.Key
);
122 case RequestStore
.QueryString
:
123 return context
.Request
.QueryString
[setup
.Key
];
124 case RequestStore
.Form
:
125 return context
.Request
.Form
[setup
.Key
];
126 case RequestStore
.Params
:
127 return context
.Request
.Params
[setup
.Key
];