Elegant Asp.Net MVC 3 custom membership wrapper class with extended (custom) methods and properties - asp.net-mvc-3

I am attempting to write a custom membership class. It seems to work ok inhering the Membership class and providing functions for all the included required items (validate user, create user, delete user, isapproved, etc).
However, where I run into a problem is when I try to add properties or methods.
As all the other properties and methods are public override classes in a sealed class,
the additional properties do not show up.
Say for example (example only, not "real" code):
public sealed class Membership : MembershipProvider
{
public override string ApplicationName
{
get
{
return "myApp";
}
}
public string myValue { get;set;}
}
Now, I understand why myValue will not show up when I try to do Membership.myValue but Membership.ApplicationName will.
My question is, how to extend membership to show the custom items? Do I ditch Membership.xxx entirely and write a wrapper class? If so, how? I can find all the documentation in the world on how to create a custom membership class. I've got a working custom membership that works fine if I use all the available options only. I've got a custom roles provider and a custom config section to store everything and it's best friend.
What I don't have is an elegant solution.
I'd like the end result to be that I use one reference (such as Membership.xxx or myClass.xxxx) to reference all membership items + custom items.
Please provide examples of how to implement or links to appropriate items that will resolve the custom methods item.

Any time you reference the membership instance you will just have to cast it to your class type, that's all.

You can take a look at Extension Methods if you don't want to cast back and forth your instances

Related

Serialize VM vs state class

After my wonderings on the events registration (you can find here ViewModel Event Registration and ViewModel Lifetime), now I'm thinking about viewmodel tombstoning:
In case of Tombstoning, is the ViewModel serialization a good approach ?
I'm thinking about the case in which different viewmodels have a reference to the same class. In case of Viewmodels serialization and deserialization the referenced class instance could have duplicated instance, isn't it ?
Wouldn't be better to have specialized state classes whose unique purpose in to contain all the app data, everyviewmodel get data (i mean reference to the data) from there and update the data in there and the app think only to serialize those specialized class ?
Any experience on this subject is appreciated.
Regards
SkyG
Caliburn Micro has a lot of this built in to the framwork allowing you to save properties of a view model or the entire graph to both phone state and app settings. You just need to create a class and inherit from StorageHandler.
public class PivotPageModelStorage : StorageHandler<PivotPageViewModel>
{
public override void Configure()
{
this.ActiveItemIndex().InPhoneState().RestoreAfterViewLoad();
}
}
And to your other posted question. CM has a nice way of handling the forced view first approach on the phone. It allows you to do page navigation by specifying the VM and it will handle the rest. And as a bonus, if you specify parameters to pass CM will pull them off the query string and populate properties on the target VM.
public void GotoPageTwo()
{
navigationService.UriFor<PivotPageViewModel>().WithParam(x => x.NumberOfTabs, 5).Navigate();
}

Bind customizable views to dynamic models

We are working on an ASP.NET MVC 3 using ext.net and EF 4.
Data model is mapped using EF4.
Views’ content is rendered from customizable XML files.
Example: Within one view, I can display fields that are related to both objects “customer” and “order”, so from this view I can modify the customer data and also add a new order.
How can we bind the view to the custom model that contains 2 objects (customer and order)? Using non strongly typed views will require a source code that will check all different possibilities (If I remove/add a field to display from the XML file, object constructor and CRUD operations parameters will change also.
We are wondering how can we handle such dynamic application?
Is this a common issue that was raised before? Or is there any solution to use dynamic views bound to custom model (object, xml, etc.)?
Your help is very appreciated, please enlighten me.
Based on what you replied to my comment, I can defenitely say that you need strongly typed views. That said, you decide what the model of your view is. If your view needs to manage users and orders at the same time, you can make a class like this:
public class MyCustomViewData
{
public IEnumerable<User> Users {get;set;}
public IEnumerable<Order> Orders {get;set;}
}
and then strongly type your view to MyCustomViewData and you're set. My example is oversimplified but I think you can get the point.
Unless I'm missing something, I believe the normal way round this would be to strongly type your view to say 'user' and then on the user object, define a property which is a collection of 'orders'.

business methods in playframework contolles

Could somebody explain is it possible to have potected, pivate methods in playfamewok's contolles except:
public static void method-action-name() {}
For example if I would have method like this:
protected static int doSomeWork() {}
and this method would be invoked in method-action-name() ..
public static void method-action-name() {
...
int resul = doSomeWork();
...
}
I do not want to have long action-method, so I would like to split it to smaller ones, and then reuse it in other action-methods.
I mean is it ok (from playframework's point of view) to have such method in controller side instead of having them in domain classes? In Spring Framework, we use BP (business process) beans for that, for example.
Is it ok to have such helper methods for business methods in playframework controllers ?
Added after having answer & comments:
For example if I have SearchController class then for that class would be nice to have methods like preSearch1(), preSearch2() what search() method would use, but if I move these methods (1,2) to another class then it should be class with name like SearchHelper then? in package named /src/helpers.. not very nice because they related to search too. But maybe then into /src/bp/SearchBP (bp=business-process). And then in controllers/Search i use /bp/SearchBP that use some Model object with .save() DAO methods (SearchBP can use Domain methods and Search class can use Domain methods as well)
The question here: what class ant package would be nice for those methods? (i just did watch it in examples - there alway very simple usage of controllers that use domain object that why i ask)
yes, you can. Controllers are normal classes, you can add whatever you want. It may not be recommended to clutter them with helper methods, I personally would move them to another class, but you can do what you say.
ANSWER TO EDIT:
The name of the package is "irrelevant", won't change it too much :). You can put them under controllers.support.search which would mean controllers.support is a package with helper classes and the subpackage search contains helper classes and methods related to search.
One alternative (which I like more) is to create a Service layer for that, in a "services" package. You seem to come from a Spring background, so it should come naturally to you. These services are instantiated in the controller as required, or maybe just used via static methods, and do the main business logic. That way the controller only tackles the "higher level" logic.
Another alternative is to move as much of that logic as possible into the Model (avoidid the Anemic Domain Model), and using the Model classes from the controller.
As most decisions in development, which one is better depends on your experience, possible impact/limitations in the codebase, practices in your project... anyway, you can always refactor. Just choose the one that you are more used to (it seems to be Services approach) and code away :)
Any behaviour that's complicated enough to be described as "business logic" (rather than "presentation logic") belongs in the model, not the controller. If your model does nothing but map to/from a set of database tables, then it isn't doing its job properly. Things like permissions and access control, in particular, should be enforced by the model.

Best way to implement extension methods

I am really really really new to all of this, and most of it is unexplored territory. Today I needed to create an anonymous class and put it to a list. I was trying to find how I can make a list of anonymous types, and found that I should make an extension method. I also already figured out an extension method should be in a static class. But what I haven't figured out yet is if there is some pattern that I should use? For now, I have made a static class in my App_Code folder named ExtensionMethods, but have no idea if I should put extension methods of all kinds of types in this class, or if I should make separate classes etc.
To my knowledge you can not implement extension methods for anonymous classes. And this makes sense as really and truly if the class has some semantics it should be made a named class.
To create a list of anonymous classes use this method:
public static List<T> CreateListFromType<T>(T anonType){
return new List<T>();
}
To use this method to create a list, do something like:
var list = CreateListFromType(new {A = default(int), B = default(int)});
Extension method is nothing more than easier-to-read static helper/utility methods. The way you organize them is the same principal as how you organize your normal classes. If you think those should stays together, then try to give them a meaningful, general enough name as the class name. Once you found your class name cannot include what that method doing, then you know that method should belongs to other places.
Firstly extension methods are normal static methods declared like this -
void MyExtension(this MyTarget target, int myparam){ ..
After this the C# compiler adds some syntactic sugar letting you call this method as
target.MyExtension(myparam);
The compiler will replace all these calls with
MyStaticClass.MyExtension(target, myparam);
The important thing is that an extension method is a normal static method. You should follow following guidelines while creating them -
Try to group extension methods for each target class in a separate static class and name it appropriately as Extensions.
Create a new namespace in your application for Extension methods such as MyAppExtensions and keep your static classes inside this namespace. This will keep the coder from misunderstanding them as Extension method and accidentally using them as instance methods.
Make these naming conventions for namespaces and static classes of Extension methods as a standard in the team.
In your extension method check if the first parameter is null and take appropriate action. If you do not then it will be possible to call the method with target being null and may result in unexpected behavior. If the first parameter is allowed to be null then document it clearly.
Consciously decide if it is correct to create and extension method or instance method will be better.
Be careful that the extension method names do not clash with instance method names or other existing extension method names for this class. Following point 1, 2 and 3 will help you achieve this.
I learnt these from Jon Skeet's C# In Depth. You should read it too.
This is how you create a list of an anonymous class.
var anonList = new[]{
new {Foo = "foo", Bar = 2},
new { Foo = "bar", Bar = 3},
}.ToList();
It has nothing to do with writing extension methods.
Edit:
In fact you will have a hard time to use extension methods to create anonymous types since anonymous types can not be used as method parameters or return type.
Edit2:
If you want to convert a list of anonymous types to a list of specific types you can use Select:
class MyClass
{
public string Prop1 {get;set;}
public int Prop2 {get;set;}
}
List<MyClass> myList = anonList.Select(x => new MyClass(){Prop1 = Foo, Prop2 = Bar}).ToList();
I use to put anonymous to DataTable. Due to it's limitation, DataTable provide more functionality such as serialization.

C# 3.0 Autoproperties - whats the difference?

0 What's the difference between the following?
public class MyClass
{
public bool MyProperty;
}
public class MyClass
{
public bool MyProperty { get; set; }
}
Is it just semantics?
Fields and properties have many differences other than semantic.
Properties can be overridden to provide different implementations in descendants.
Properties can help alleviate versioning problems. I.e. Changing a field to a property in a library requires a recompile of anything depending on that library.
Properties can have different accessibility for the getter and setter.
"Just semantics" always seems like a contradiction in terms to me. Yes, it changes the meaning of the code. No, that's not something I'd use the word "just" about.
The first class has a public field. The second class has a public property, backed by a private field. They're not the same thing:
If you later change the implementation of the property, you maintain binary compatibility. If you change the field to a property, you lose both binary and source compatibility.
Fields aren't seen by data-binding; properties are
Field access can't be breakpointed in managed code (AFAIK)
Exposing a field exposes the implementation of your type - exposing a property just talks about the contract of your type.
See my article about the goodness of properties for slightly more detail on this.
In that case, yes it is mostly semantics. It makes a difference for reflection and so forth.
However, if you want to make a change so that when MyProperty is set you fire an event for example you can easily modify the latter to do that. The former you can't. You can also specify the latter in an interface.
As there is so little difference but several potential advantages to going down the property route, I figure that you should always go down the property route.
The first one is just a public field, the second one is a so-called automatic property. Automatic properties are changed to regular properties with a backing field by the C# compiler.
Public fields and properties are equal in C# syntax, but they are different in IL (read this on a German forum recently, can't give you the source, sorry).
Matthias
The biggest difference is that you can add access modifiers to properties, for example like this
public class MyClass
{
public bool MyProperty { get; protected set; }
}
For access to the CLR fields and properties are different too. So if you have a field and you want to change it to a property later (for example when you want to add code to the setter) the interface will change, you will need to recompile all code accessing that field. With an Autoproperty you don't have this problem.
I am assuming you are not writing code that will be called by 3rd party developers that can’t recompile their code when you change your code. (E.g. that you don’t work for Microsoft writing the .Net framework it’s self, or DevExpress writing a control toolkip). Remember that Microsoft’s .NET framework coding standard is for the people writing the framework and tries to avoid a lot of problems that are not even issues if you are not writing a framework for use of 3rd party developers.
The 2nd case the defined a propriety, the only true advantage of doing is that that data binding does not work with fields. There is however a big political advantage in using proprieties, you get a lot less invalid complaints from other developers that look at your code.
All the other advantages for proprieties (that are well explained in the other answers to your questions) are not of interest to you at present, as any programmer using your code can change the field to a propriety later if need be and just recompile your solution.
However you are not likely to get stacked for using proprieties, so you make as well always use public proprieties rather the fields.

Resources