Search Results

Search found 37 results on 2 pages for 'allowmultiple'.

Page 1/2 | 1 2  | Next Page >

  • What's the point of indicating AllowMultiple=false on an abstract Attribute class?

    - by tvanfosson
    On a recent question about MVC attributes, someone asked whether using HttpPost and HttpDelete attributes on an action method would result in either request type being allowed or no requests being allowed (since it can't be both a Post and a Delete at the same time). I noticed that ActionMethodSelectorAttribute, from which HttpPostAttribute and HttpDeleteAttribute both derive is decorated with [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] I had expected it to not allow both HttpPost and HttpDelete on the same method because of this, but the compiler doesn't complain. My limited testing tells me that the attribute usage on the base class is simply ignored. AllowMultiple seemingly only disallows two of the same attribute from being applied to a method/class and doesn't seem to consider whether those attributes derive from the same class which is configured to not allow multiples. Moreover, the attribute usage on the base class doesn't even preclude your from changing the attribute usage on a derived class. That being the case, what's the point of even setting the values on the base attribute class? Is it just advisory or am I missing something fundamental in how they work? FYI - it turns out that using both basically precludes that method from ever being considered. The attributes are evaluated independently and one of them will always indicate that the method is not valid for the request since it can't simultaneously be both a Post and a Delete.

    Read the article

  • MEF GetExports<T, TMetaDataView> returning nothing with AllowMultiple = True

    - by sohum
    I don't understand MEF very well, so hopefully this is a simple fix of how I think it works. I'm trying to use MEF to get some information about a class and how it should be used. I'm using the Metadata options to try to achieve this. My interfaces and attribute looks like this: public interface IMyInterface { } public interface IMyInterfaceInfo { Type SomeProperty1 { get; } double SomeProperty2 { get; } string SomeProperty3 { get; } } [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class ExportMyInterfaceAttribute : ExportAttribute, IMyInterfaceInfo { public ExportMyInterfaceAttribute(Type someProperty1, double someProperty2, string someProperty3) : base(typeof(IMyInterface)) { SomeProperty1 = someProperty1; SomeProperty2 = someProperty2; SomeProperty3 = someProperty3; } public Type SomeProperty1 { get; set; } public double SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } } The class that is decorated with the attribute looks like this: [ExportMyInterface(typeof(string), 0.1, "whoo data!")] [ExportMyInterface(typeof(int), 0.4, "asdfasdf!!")] public class DecoratedClass : IMyInterface { } The method that is trying to use the import looks like this: private void SomeFunction() { // CompositionContainer is an instance of CompositionContainer var myExports = CompositionContainer.GetExports<IMyInterface, IMyInterfaceInfo>(); } In my case myExports is always empty. In my CompositionContainer, I have a Part in my catalog that has two ExportDefinitions, both with the following ContractName: "MyNamespace.IMyInterface". The Metadata is also loaded correctly per my exports. If I remove the AllowMultiple setter and only include one exported attribute, the myExports variable now has the single export with its loaded metadata. What am I doing wrong?

    Read the article

  • Extension Methods in Dot Net 2.0

    - by Tom Hines
    Not that anyone would still need this, but in case you have a situation where the code MUST be .NET 2.0 compliant and you want to use a cool feature like Extension methods, there is a way.  I saw this article when looking for ways to create extension methods in C++, C# and VB:  http://msdn.microsoft.com/en-us/magazine/cc163317.aspx The author shows a simple  way to declare/define the ExtensionAttribute so it's available to 2.0 .NET code. Please read the article to learn about the when and why and use the content below to learn HOW. In the next post, I'll demonstrate cross-language calling of extension methods. Here is a version of it in C# First, here's the project showing there's no VOODOO included: using System; namespace System.Runtime.CompilerServices {    [       AttributeUsage(          AttributeTargets.Assembly          | AttributeTargets.Class          | AttributeTargets.Method,       AllowMultiple = false, Inherited = false)    ]    class ExtensionAttribute : Attribute{} } namespace TestTwoDotExtensions {    public static class Program    {       public static void DoThingCS(this string str)       {          Console.WriteLine("2.0\t{0:G}\t2.0", str);       }       static void Main(string[] args)       {          "asdf".DoThingCS();       }    } }   Here is the C++ version: // TestTwoDotExtensions_CPP.h #pragma once using namespace System; namespace System {        namespace Runtime {               namespace CompilerServices {               [                      AttributeUsage(                            AttributeTargets::Assembly                             | AttributeTargets::Class                            | AttributeTargets::Method,                      AllowMultiple = false, Inherited = false)               ]               public ref class ExtensionAttribute : Attribute{};               }        } } using namespace System::Runtime::CompilerServices; namespace TestTwoDotExtensions_CPP { public ref class CTestTwoDotExtensions_CPP {    public:            [ExtensionAttribute] // or [Extension]            static void DoThingCPP(String^ str)    {       Console::WriteLine("2.0\t{0:G}\t2.0", str);    } }; }

    Read the article

  • Multiple file upload with asp.net 4.5 and Visual Studio 2012

    - by Jalpesh P. Vadgama
    This post will be part of Visual Studio 2012 feature series. In earlier version of ASP.NET there is no way to upload multiple files at same time. We need to use third party control or we need to create custom control for that. But with asp.net 4.5 now its possible to upload multiple file with file upload control. With ASP.NET 4.5 version Microsoft has enhanced file upload control to support HTML5 multiple attribute. There is a property called ‘AllowedMultiple’ to support that attribute and with that you can easily upload the file. So what we are waiting for!! It’s time to create one example. On the default.aspx file I have written following. <asp:FileUpload ID="multipleFile" runat="server" AllowMultiple="true" /> <asp:Button ID="uploadFile" runat="server" Text="Upload files" onclick="uploadFile_Click"/> Here you can see that I have given file upload control id as multipleFile and I have set AllowMultiple file to true. I have also taken one button for uploading file.For this example I am going to upload file in images folder. As you can see I have also attached event handler for button’s click event. So it’s time to write server side code for this. Following code is for the server side. protected void uploadFile_Click(object sender, EventArgs e) { if (multipleFile.HasFiles) { foreach(HttpPostedFile uploadedFile in multipleFile.PostedFiles) { uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),uploadedFile.FileName)); Response.Write("File uploaded successfully"); } } } Here in the above code you can see that I have checked whether multiple file upload control has multiple files or not and then I have save that in Images folder of web application. Once you run the application in browser it will look like following. I have selected two files. Once I have selected and clicked on upload file button it will give message like following. As you can see now it has successfully upload file and you can see in windows explorer like following. As you can see it’s very easy to upload multiple file in ASP.NET 4.5. Stay tuned for more. Till then happy programming. P.S.: This feature is only supported in browser who support HTML5 multiple file upload. For other browsers it will work like normal file upload control in asp.net.

    Read the article

  • Guarding against CSRF Attacks in ASP.NET MVC2

    - by srkirkland
    Alongside XSS (Cross Site Scripting) and SQL Injection, Cross-site Request Forgery (CSRF) attacks represent the three most common and dangerous vulnerabilities to common web applications today. CSRF attacks are probably the least well known but they are relatively easy to exploit and extremely and increasingly dangerous. For more information on CSRF attacks, see these posts by Phil Haack and Steve Sanderson. The recognized solution for preventing CSRF attacks is to put a user-specific token as a hidden field inside your forms, then check that the right value was submitted. It's best to use a random value which you’ve stored in the visitor’s Session collection or into a Cookie (so an attacker can't guess the value). ASP.NET MVC to the rescue ASP.NET MVC provides an HTMLHelper called AntiForgeryToken(). When you call <%= Html.AntiForgeryToken() %> in a form on your page you will get a hidden input and a Cookie with a random string assigned. Next, on your target Action you need to include [ValidateAntiForgeryToken], which handles the verification that the correct token was supplied. Good, but we can do better Using the AntiForgeryToken is actually quite an elegant solution, but adding [ValidateAntiForgeryToken] on all of your POST methods is not very DRY, and worse can be easily forgotten. Let's see if we can make this easier on the program but moving from an "Opt-In" model of protection to an "Opt-Out" model. Using AntiForgeryToken by default In order to mandate the use of the AntiForgeryToken, we're going to create an ActionFilterAttribute which will do the anti-forgery validation on every POST request. First, we need to create a way to Opt-Out of this behavior, so let's create a quick action filter called BypassAntiForgeryToken: [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] public class BypassAntiForgeryTokenAttribute : ActionFilterAttribute { } Now we are ready to implement the main action filter which will force anti forgery validation on all post actions within any class it is defined on: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class UseAntiForgeryTokenOnPostByDefault : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (ShouldValidateAntiForgeryTokenManually(filterContext)) { var authorizationContext = new AuthorizationContext(filterContext.Controller.ControllerContext);   //Use the authorization of the anti forgery token, //which can't be inhereted from because it is sealed new ValidateAntiForgeryTokenAttribute().OnAuthorization(authorizationContext); }   base.OnActionExecuting(filterContext); }   /// <summary> /// We should validate the anti forgery token manually if the following criteria are met: /// 1. The http method must be POST /// 2. There is not an existing [ValidateAntiForgeryToken] attribute on the action /// 3. There is no [BypassAntiForgeryToken] attribute on the action /// </summary> private static bool ShouldValidateAntiForgeryTokenManually(ActionExecutingContext filterContext) { var httpMethod = filterContext.HttpContext.Request.HttpMethod;   //1. The http method must be POST if (httpMethod != "POST") return false;   // 2. There is not an existing anti forgery token attribute on the action var antiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ValidateAntiForgeryTokenAttribute), false);   if (antiForgeryAttributes.Length > 0) return false;   // 3. There is no [BypassAntiForgeryToken] attribute on the action var ignoreAntiForgeryAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassAntiForgeryTokenAttribute), false);   if (ignoreAntiForgeryAttributes.Length > 0) return false;   return true; } } The code above is pretty straight forward -- first we check to make sure this is a POST request, then we make sure there aren't any overriding *AntiForgeryTokenAttributes on the action being executed. If we have a candidate then we call the ValidateAntiForgeryTokenAttribute class directly and execute OnAuthorization() on the current authorization context. Now on our base controller, you could use this new attribute to start protecting your site from CSRF vulnerabilities. [UseAntiForgeryTokenOnPostByDefault] public class ApplicationController : System.Web.Mvc.Controller { }   //Then for all of your controllers public class HomeController : ApplicationController {} What we accomplished If your base controller has the new default anti-forgery token attribute on it, when you don't use <%= Html.AntiForgeryToken() %> in a form (or of course when an attacker doesn't supply one), the POST action will throw the descriptive error message "A required anti-forgery token was not supplied or was invalid". Attack foiled! In summary, I think having an anti-CSRF policy by default is an effective way to protect your websites, and it turns out it is pretty easy to accomplish as well. Enjoy!

    Read the article

  • Postsharp duplicate attribute?

    - by yodaj007
    Can anyone explain why I'm getting this compile error? Duplicate 'Rad.Core.Aop.MethodArgumentValidation' attribute E:\Scripting\Rad.Core\Properties\AssemblyInfo.cs This is the code: [assembly: Rad.Core.Aop.MethodArgumentValidation(AttributeTargetTypes="Rad.*", AttributePriority=1)] [assembly: Rad.Core.Aop.MethodArgumentValidation(AttributeTargetTypes = "Rad.Core.Aop.*", AttributePriority = 2, AttributeExclude=true)] Here is the declaration of the aspect: [Serializable] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)] [MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple=true)] public class MethodArgumentValidationAttribute : OnMethodInvocationAspect { ... } It looks like I'm following this example: http://www.sharpcrafters.com/blog/post/multicasting-of-custom-attributes.aspx Can anyone help?

    Read the article

  • Implementing INotifyPropertyChanged with PostSharp 1.5

    - by no9
    Hello all. Im new to .NET and WPF so i hope i will ask the question correctly. I am using INotifyPropertyChanged implemented using PostSharp 1.5: [Serializable, DebuggerNonUserCode, AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = false), MulticastAttributeUsage(MulticastTargets.Class, AllowMultiple = false, Inheritance = MulticastInheritance.None, AllowExternalAssemblies = true)] public sealed class NotifyPropertyChangedAttribute : CompoundAspect { public int AspectPriority { get; set; } public override void ProvideAspects(object element, LaosReflectionAspectCollection collection) { Type targetType = (Type)element; collection.AddAspect(targetType, new PropertyChangedAspect { AspectPriority = AspectPriority }); foreach (var info in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(pi => pi.GetSetMethod() != null)) { collection.AddAspect(info.GetSetMethod(), new NotifyPropertyChangedAspect(info.Name) { AspectPriority = AspectPriority }); } } } [Serializable] internal sealed class PropertyChangedAspect : CompositionAspect { public override object CreateImplementationObject(InstanceBoundLaosEventArgs eventArgs) { return new PropertyChangedImpl(eventArgs.Instance); } public override Type GetPublicInterface(Type containerType) { return typeof(INotifyPropertyChanged); } public override CompositionAspectOptions GetOptions() { return CompositionAspectOptions.GenerateImplementationAccessor; } } [Serializable] internal sealed class NotifyPropertyChangedAspect : OnMethodBoundaryAspect { private readonly string _propertyName; public NotifyPropertyChangedAspect(string propertyName) { if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); _propertyName = propertyName; } public override void OnEntry(MethodExecutionEventArgs eventArgs) { var targetType = eventArgs.Instance.GetType(); var setSetMethod = targetType.GetProperty(_propertyName); if (setSetMethod == null) throw new AccessViolationException(); var oldValue = setSetMethod.GetValue(eventArgs.Instance, null); var newValue = eventArgs.GetReadOnlyArgumentArray()[0]; if (oldValue == newValue) eventArgs.FlowBehavior = FlowBehavior.Return; } public override void OnSuccess(MethodExecutionEventArgs eventArgs) { var instance = eventArgs.Instance as IComposed<INotifyPropertyChanged>; var imp = instance.GetImplementation(eventArgs.InstanceCredentials) as PropertyChangedImpl; imp.OnPropertyChanged(_propertyName); } } [Serializable] internal sealed class PropertyChangedImpl : INotifyPropertyChanged { private readonly object _instance; public PropertyChangedImpl(object instance) { if (instance == null) throw new ArgumentNullException("instance"); _instance = instance; } public event PropertyChangedEventHandler PropertyChanged; internal void OnPropertyChanged(string propertyName) { if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); var handler = PropertyChanged as PropertyChangedEventHandler; if (handler != null) handler(_instance, new PropertyChangedEventArgs(propertyName)); } } } Then i have a couple of classes (user and adress) that implement [NotifyPropertyChanged]. It works fine. But what i want would be that if the child object changes (in my example address) that the parent object gets notified (in my case user). Would it be possible to expand this code so it automaticly creates listeners on parent objects that listen for changes in its child objets?

    Read the article

  • restricting the property type of a custom attribute

    - by Guy
    Does anyone knows if it is possible to define/declare on your own custom attribute a restriction to the field type it may apply on? There are a flags that do restrict the usage of the attribute: [AttributeUsage( AttributeTargets.Property, AllowMultiple = false)] Im looking for something like: UseOnlyOnType = typeof(string) Any ideas?

    Read the article

  • help me with asp.net mvc 2 custom validation attribute

    - by Omu
    I'm trying to write a validation attribute that is going to check that at least one of the specified properties is true [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class AtLeastOneTrueAttribute : ValidationAttribute { private const string DefaultErrorMessage = "select at least one"; public AtLeastOneTrueAttribute(params string[] props) : base(DefaultErrorMessage) { this.props = props; } private readonly string[] props; public override string FormatErrorMessage(string name) { return DefaultErrorMessage; } public override bool IsValid(object value) { var properties = TypeDescriptor.GetProperties(value); return props.Any(p => (bool) properties.Find(p, true).GetValue(value)); } } now when I'm trying to use I can't really get specify the props after the fir , the intellisence shows me that I'm entering the ErrorMessage and only the first string is the params string[] props

    Read the article

  • How do I suppress eclipse warning: Referenced identifier 'VIEWNAME:secondaryid' in attribute 'id' ca

    - by Jeremy
    In eclipse 3.4, here is the section of my plugin.xml: <extension point="org.eclipse.ui.views"> <view allowMultiple="true" class="the.full.class.name" icon="images/icon.gif" id="VIEWNAME" name="View Name"> </view> </extension> <extension point="org.eclipse.ui.perspectiveExtensions"> <perspectiveExtension targetID="com.p21csi.fps.sim.rcp.perspective.SimPerspective"> <view closeable="false" id="VIEWNAME:secondaryid" minimized="false" moveable="false" ratio=".75" relationship="left" relative="org.eclipse.ui.editorss" showTitle="true" standalone="true" visible="true"> </view> </perspectiveExtension> </extension> The application works fine, I just can't get rid of that annoying warning!

    Read the article

  • C# - Silverlight - CustomAttribute with Enum

    - by cmaduro
    I have the following class: [MetadataAttribute] [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class ModuleActivationButtonAttribute : ExportAttribute { public Enum TargetRegion { get; set; } public ModuleActivationButtonAttribute(Enum targetRegion) : base(typeof(IModuleActivationButton)) { TargetRegion = targetRegion; } } The class compiles fine, but when I decorate my property with it: [ModuleActivationButton(Regions.Tabs)] public IModuleActivationButton ModuleActivationButton { get { return new ModuleActivationButton() as IModuleActivationButton; } set { ModuleActivationButton = value; } } public enum Regions { Content, Tabs } The compiler spits out: Error 1 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type C:\...\Manpower4U.Modules.Home\HomeModule.cs 28 33 Manpower4U.Modules.Home

    Read the article

  • How do I get the member to which my custom attribute was applied?

    - by Sarah Vessels
    I'm creating a custom attribute in C# and I want to do different things based on whether the attribute is applied to a method versus a property. At first I was going to do new StackTrace().GetFrame(1).GetMethod() in my custom attribute constructor to see what method called the attribute constructor, but now I'm unsure what that will give me. What if the attribute was applied to a property? Would GetMethod() return a MethodBase instance for that property? Is there a different way of getting the member to which an attribute was applied in C#? [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class MyCustomAttribute : Attribute Update: okay, I might have been asking the wrong question. From within a custom attribute class, how do I get the member (or the class containing the member) to which my custom attribute was applied? Aaronaught suggested against walking up the stack to find the class member to which my attribute was applied, but how else would I get this information from within the constructor of my attribute?

    Read the article

  • Inheritance of Custom Attributes on Abstract Properties

    - by Marty Trenouth
    I've got a custom attribute that I want to apply to my base abstract class so that I can skip elements that don't need to be viewed by the user when displaying the item in HTML. It seems that the properties overriding the base class are not inheriting the attributes. Does overriding base properties (abstract or virtual) blow away attributes placed on the original property? From Attribute class Defination [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public class NoHtmlOutput : Attribute { } From Abstract Class Defination [NoHtmlOutput] public abstract Guid UniqueID { get; set; } From Concrete Class Defination public override Guid UniqueID{ get{ return MasterId;} set{MasterId = value;}} From class checking for attribute Type t = o.GetType(); foreach (PropertyInfo pi in t.GetProperties()) { if (pi.GetCustomAttributes(typeof(NoHtmlOutput), true).Length == 1) continue; // processing logic goes here }

    Read the article

  • c# Attribute Question

    - by Petoj
    Well i need some help here i don't know how to solve this problem. the function of the attribute is to determine if the function can be run... So what i need is the following: The consumer of the attribute should be able to determine if it can be executed. The owner of the attribute should be able to tell the consumer that now it can/can't be executed (like a event). It must have a simple syntax. This is what i have so far but it only implements point 1, 3. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class ExecuteMethodAttribute : Attribute { private Func<object, bool> canExecute; public Func<object, bool> CanExecute { get { return canExecute; } } public ExecuteMethodAttribute() { } public ExecuteMethodAttribute(Func<object, bool> canExecute) { this.canExecute = canExecute; } }

    Read the article

  • How to dynamically set validation messages on properties with a class validation attribute

    - by Dan
    I'm writing Validation attribute that sits on the class but inspects the properties of the class. I want it to set a validation message on each of the properties it finds to be invalid. How do I do this? This is what I have got so far: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class LinkedFieldValidationAttribute : ValidationAttribute { private readonly string[] _properiesToValidate; public LinkedFieldValidationAttribute(params string[] properiesToValidate) { _properiesToValidate = properiesToValidate; } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); foreach (var propertyName in _properiesToValidate) { var propertyValue = properties.Find(propertyName, false).GetValue(value); //if value is invalid add message from base } //return validity } }

    Read the article

  • C# - Custom Attributes - Setting an attribute property to the type of the decorated class.

    - by cmaduro
    Is it possible to get the decorated class' type inside of the custom attribute's class? For example: [MetadataAttribute] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)] public class ViewAttribute : ExportAttribute { public object TargetRegion { get; set; } public Type ViewModel { get; set; } public Type Module { get; set; } public ViewAttribute() : base(typeof(UserControl)) { Module = GetDecoratedClassType(); //I need this method } } In the following example GetDecoratedClassType() would return HomeView [View] HomeView MyHomeView { get; set; }

    Read the article

  • How to override [Authorize] attribute in the MVC Web API?

    - by NullReference
    I have a MVC Web Api Controller that uses the [Authorize] attribute at the class level. This makes all of the api methods require authorization but I'd like to create an attribute called [ApiPublic] that overrides the [Authorize] attribute. There is a similar technique described here for normal MVC controllers. I tried creating an AuthorizeAttribute based of the System.Web.Http.AuthorizeAttribute but none of the overridden events are called if I put it on a api method that has the [Authorize] at the class level. Anyone have an idea how to override the authorize for the web api? [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ApiPublicAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { base.HandleUnauthorizedRequest(actionContext); } public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { base.OnAuthorization(actionContext); } protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { return true; } }

    Read the article

  • Field annotated multiple times by the same attribute

    - by Jaroslaw Waliszko
    For my ASP.NET MVC application I've created custom validation attribute, and indicated that more than one instance of it can be specified for a single field or property: [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public sealed class SomeAttribute: ValidationAttribute I've created validator for such an attribute: public class SomeValidator : DataAnnotationsModelValidator<SomeAttribute> and wire up this in the Application_Start of Global.asax DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof (SomeAttribute), typeof (SomeValidator)); Finally, if I use my attribute in the desired way: [SomeAttribute(...)] //first [SomeAttribute(...)] //second public string SomeField { get; set; } when validation is executed by the framework, only first attribute instance is invoked. Second one seems to be dead. I've noticed that during each request only single validator instance is created (for the first annotation). How to solve this problem and fire all attributes?

    Read the article

  • Setting an attribute property to the type of the decorated class.

    - by cmaduro
    Is it possible to get the decorated class' type inside of the custom attribute's class? For example: [MetadataAttribute] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)] public class ViewAttribute : ExportAttribute { public object TargetRegion { get; set; } public Type ViewModel { get; set; } public Type Module { get; set; } public ViewAttribute() : base(typeof(UserControl)) { Module = GetDecoratedClassType(); //I need this method } } In the following example GetDecoratedClassType() would return HomeView [View] HomeView MyHomeView { get; set; }

    Read the article

  • Issue intercepting property in Silverlight application

    - by joblot
    I am using Ninject as DI container in a Silverlight application. Now I am extending the application to support interception and started integrating DynamicProxy2 extension for Ninject. I am trying to intercept call to properties on a ViewModel and ending up getting following exception: “Attempt to access the method failed: System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Reflection.Module, Boolean)” This exception is thrown when invocation.Proceed() method is called. I tried two implementations of the interceptor and they both fail public class NotifyPropertyChangedInterceptor: SimpleInterceptor { protected override void AfterInvoke(IInvocation invocation) { var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy; model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length)); } } public class NotifyPropertyChangedInterceptor: IInterceptor { public void Intercept(IInvocation invocation) { invocation.Proceed(); var model = (IAutoNotifyPropertyChanged)invocation.Request.Proxy; model.OnPropertyChanged(invocation.Request.Method.Name.Substring("set_".Length)); } } I want to call OnPropertyChanged method on the ViewModel when property value is set. I am using Attribute based interception. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class NotifyPropertyChangedAttribute : InterceptAttribute { public override IInterceptor CreateInterceptor(IProxyRequest request) { if(request.Method.Name.StartsWith("set_")) return request.Context.Kernel.Get<NotifyPropertyChangedInterceptor>(); return null; } } I tested the implementation with a Console Application and it works alright. I also noted in Console Application as long as I had Ninject.Extensions.Interception.DynamicProxy2.dll in same folder as Ninject.dll I did not have to explicitly load DynamicProxy2Module into the Kernel, where as I had to explicitly load it for Silverlight application as follows: IKernel kernel = new StandardKernel(new DIModules(), new DynamicProxy2Module()); Could someone please help? Thanks

    Read the article

  • Windows Azure ASP.NET MVC Role behaves strangely when redirecting from HTTP to HTTPS

    - by Rinat Abdullin
    Subj. I've got an ASP.NET 2 MVC Worker Role Application, that does not differ much from the default template. When attempting redirect from HTTP to HTTPS (this happens when we access constroller secured by the usual RequireSSL attribute implementation) we get blank page with "Bad Request" message. IntelliTrace shows this: Thrown: "The file '/Views/Home/LogOnUserControl.aspx' does not exist." (System.Web.HttpException) Call stack is really short: [External Code] App_Web_vfahw7gz.dll!ASP.views_shared_site_master.__Render__control1(System.Web.UI.HtmlTextWriter __w = {unknown}, System.Web.UI.Control parameterContainer = {unknown}) [External Code] App_Web_bsbqxr44.dll!ASP.views_home_index_aspx.ProcessRequest(System.Web.HttpContext context = {unknown}) [External Code] User control reference is the usual one in /Views/Shared/Site.Master: <div id="logindisplay"> <% Html.RenderPartial("LogOnUserControl"); %> </div> And partial view LogOnUserControl.ashx is located in Views/Shared (and it is ASHX, not ASPX). Problem shows up, when we try to access site pages, that require auth and redirect. These pages are secured by RequireSSL attribute (Redirect == true): [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class RequireSslAttribute : FilterAttribute, IAuthorizationFilter { public bool Redirect { get; set; } // Methods public void OnAuthorization(AuthorizationContext filterContext) { // this get's messy, when we are running custom ports // within the local dev fabric. // hence we disable code in the debug #if !DEBUG if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.HttpContext.Request.IsSecureConnection) return; var canRedirect = string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase); if (canRedirect && Redirect) { var builder = new UriBuilder { Scheme = "https", Host = filterContext.HttpContext.Request.Url.Host, Path = filterContext.HttpContext.Request.RawUrl }; filterContext.Result = new RedirectResult(builder.ToString()); } else { throw new HttpException(0x193, "Access forbidden. The requested resource requires an SSL connection."); } #endif } } Obviously we compile in RELEASE for this case. Does anybody have any idea, what could cause this strange exception and how to get rid of it?

    Read the article

  • Custom Model Validator for MVC

    - by scottrakes
    I am trying to add a custom model validation at the property level but need to pass in two values. Below is my class definition and validation implementation. When it runs, the "value" in the IsValid method is always null. I can get this working at the class level but the property level is causing me issues. What am I missing? Event Class: public class Event { public int? EventID {get;set;} [ValidPURL("EventID", "PURLValue")] public string PURLValue { get; set; } ... } Validation Class [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] public sealed class ValidPURL : ValidationAttribute { private const string _defaultErrorMessage = "Web address already exist."; private readonly object _typeId = new object(); public ValidPURL(int eventID, string purlValue) : base(_defaultErrorMessage) { EventID = eventID; PURLValue = purlValue; } public int EventID { get; private set; } public string PURLValue { get; private set; } public override object TypeId { get { return _typeId; } } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, EventID, PURLValue); } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object eventIDValue = properties.Find(EventID, true /* ignoreCase */).GetValue(value); object purlValue = properties.Find(PURLValue, true /* ignoreCase */).GetValue(value); [Some Validation Logic against the database] return true; } } Thank for the help!

    Read the article

  • How do I prevent a C# method from executing using an attribute validator?

    - by Boydski
    I'd like to create an attribute-based validator that goes a few steps beyond what I've seen in examples. It'll basically prevent methods or other functionality from executing. Please be aware that I'm having to use AzMan since I have no availability to Active Directory in this scenario. Here's some pseudo code of what what I'm looking for: // Attribute validator class AttributeUsage is arbitrary at this point and may include other items [AttributeUsage( AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true, Inherited = true )] public class PermissionsValidatorAttribute : Attribute { public PermissionsValidatorAttribute(PermissionEnumeration permission){...} public bool UserCanCreateAndEdit(){...} public bool UserCanDelete(){...} public bool UserCanUpload(){...} } Here's a sample of a class/member that'll be decorated. The method will not be executed at all if the PermissionValidator.UserCanDelete() doesn't return true from wherever it's executed: public class DoStuffNeedingPermissions { [PermissionValidator(PermissionEnumeration.MustHaveDeletePermission)] public void DeleteSomething(){...} } I know this is a simple, incomplete example. But you should get the gist of what I'm needing. Make the assumption that DeleteSomething() already exists and I'm preferring to NOT modify the code within the method at all. I'm currently looking at things like the Validation Application Block and am messing with custom attribute POC's. But I'd love to hear opinions with code samples from everyone out there. I'm also certainly not opposed to other methods of accomplishing the same thing such as extension methods or whatever may work to accomplish the same thing. Please remember I'm making the attempt to minimize changes to existing DoStuffNeedingPermissions code. Thanks everyone!

    Read the article

  • MVC.NET custom validator is not working

    - by IvanMushketyk
    I want to write a custom validator for MVC.NET framework that checks if entered date is in the future. To do it, I wrote the following class: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class InTheFutureAttribute : ValidationAttribute, IClientValidatable { private const string DefaultErrorMessage = "{0} should be date in the future"; public InTheFutureAttribute() : base(DefaultErrorMessage) { } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name); } public override bool IsValid(object value) { DateTime time = (DateTime)value; if (time < DateTime.Now) { return false; } return true; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var clientValidationRule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "wrongvalue" }; return new[] { clientValidationRule }; } } and added attribute to field that I want to check. On the View page I create input field in the following way: <div class="editor-label-search"> @Html.LabelFor(model => model.checkIn) </div> <div class="editor-field-search-date"> @Html.EditorFor(model => model.checkIn) <script type="text/javascript"> $(document).ready(function () { $('#checkIn').datepicker({ showOn: 'button', buttonImage: '/Content/images/calendar.gif', duration: 0, dateFormat: 'dd/mm/yy' }); }); </script> @Html.ValidationMessageFor(model => model.checkIn) </div> When I submit the form for the controller that requires model with checked attribute code in my validator is called and it returns false, but instead of displaying an error it just call my controller's action and send invalid model to it. Am I doing something wrong? How can I fix it? Thank you in advance.

    Read the article

  • Anti-Forgery Request in ASP.NET MVC and AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent by the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> which writes to token to the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and the cookie: __RequestVerificationToken_Lw__=J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, I encountered 2 problems: It is expected to add [ValidateAntiForgeryToken] to each controller, but actually I have to add it for each POST actions, which is a little crazy; After anti-forgery validation is turned on for server side, AJAX POST requests will consistently fail. Specify validation on controller (not on each action) Problem For the first problem, usually a controller contains actions for both HTTP GET and HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become always invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { [HttpGet] public ActionResult Index() // Index page cannot work at all. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If user sends a HTTP GET request from a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each HTTP POST action in the application:public class SomeController : Controller { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one attribute for one HTTP POST action), I created a wrapper class of ValidateAntiForgeryTokenAttribute, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // Actions for HTTP GET requests are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all HTTP POST actions. Submit token via AJAX Problem For AJAX scenarios, when request is sent by JavaScript instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The token must be printed to browser then submitted back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called in the page where the AJAX POST will be sent. Then jQuery must find the printed token in the page, and post it:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated in a tiny jQuery plugin:(function ($) { $.getAntiForgeryToken = function () { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. return $("input[type='hidden'][name='__RequestVerificationToken']").val(); }; var addToken = function (data) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } data = data ? data + "&" : ""; return data + "__RequestVerificationToken=" + encodeURIComponent($.getAntiForgeryToken()); }; $.postAntiForgery = function (url, data, callback, type) { return $.post(url, addToken(data), callback, type); }; $.ajaxAntiForgery = function (settings) { settings.data = addToken(settings.data); return $.ajax(settings); }; })(jQuery); Then in the application just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() instead of $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. This solution looks hard coded and stupid. If you have more elegant solution, please do tell me.

    Read the article

1 2  | Next Page >