Add Extension Method to MembershipProvider - asp.net

I am currently working on a Custom MembershipProvider implementation. But I need additional methods. I would like to call those methods directly on the Membership object within my Controller like this:
Membership.DoStuff()
Is it possible to do that with an extension method? Where would I start?
thanks!

learning more about extension methods is a good start. Please refer to following articles
http://technico.qnownow.com/2012/03/17/how-to-create-extension-methods-in-net/
extension methods (MSDN)

Why don't you add it directly to you class (which have the custom MemebershipProvider) then cast the membership clasd to your then you will find it.
If you asking about the extension methods it should work on any class, so the answer to your question is Yes.

After trying a lot of examples I have found this post where they state that you cannot write extension methods to a static class.
Membership is a static class and you cannot extend it.

yes, Membership is extensible, but you don't extends static class Membership (because it's impossible), you must extends abstract class MembershipProvider, and calls extension methods like Membership.Provider.DoStuff().
For example:
extension class
namespace Infrastructure.Extensions
{
public static class MembershipProviderExtensions
{
public static void DoStuff(this MembershipProvider provider)
{
// do stuff
}
}
}
in your code
using Infrastructure.Extensions;
...
Membership.Provider.DoStuff()
...

Related

ASP.NET Core MVC application dependency injection issue when using BaseController

Recently i tried to create a MVC application using ASP.NET Core 2.0 and i had some values defined in appsettings.json,
"MySettings": {
"WebApiBaseUrl": "http://localhost:6846/api/"
}
In order to read these values i have added
services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));
above line in ConfigureServices method in Startup.cs
and in my home controller i have added
private readonly IOptions<MySettingsModel> appSettings;
public HomeController(IOptions<MySettingsModel> app)
{
appSettings = app;
}
MySettingsModel class is just a model with property same as key define in appsettings.json.
by this method i'm able to read the value of this key.
Now my issue is that i want to use this key in many controllers so i don't want to repeat this code in every controller so what i did was i created a BaseConntroller, added its constructor and i got my values there. But when i inherit other controllers with my BaseController , it throws me an error and tells me to generate it's constructor, so basically it tells me to add constructor in every controller which is what i wanted to avoid.
How can i achieve this?
You can see the image for the error
And these are the potential fixes that it shows me.
This is just basic C# inheritance. Derived classes must re-implement constructors on base classes (at least the ones you want or need). The only exception is the empty constructor, which is implicit. In other words, you simply need:
public class HomeController : BaseController
{
public HomeController(IOptions<MySettingsModel> app)
: base(app)
{
}
And, of course, you need to change the accessibility of the base class field to protected instead of private. Otherwise, derived classes will not be able to access it.
Of course, this doesn't really save you that much. However, there's no free lunch here. Like I said, this is a limitation of C#, itself, so you have no choice. Although, it's worth mentioning, that while this can sometimes be annoying, it's actually a kind of useful feature of C#. You can look at any class and see exactly what constructors it has available, without having to trace down all its ancestors.
Actually, there is a good solution here:
https://stackoverflow.com/a/48886242/2060975
I am mostly using this method.
[Authorize]
[ApiController]
public abstract class ApiControllerBase : ControllerBase
{
private IOptions<AppSettings> _appSettings;
protected IOptions<AppSettings> appSettings => _appSettings ?? (_appSettings = (IOptions<AppSettings>)this.HttpContext.RequestServices.GetService(typeof(IOptions<AppSettings>)));
...
}
I hope it helps someone:)

Why are OWIN startup classes declared as partial, yet sometimes not?

If I use VS2015.1 to create a new sample project (either WebForms or MVC), two files are created for configuring OWIN:
\Startup.cs (or .vb)
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(WebApplication6.Startup))]
namespace WebApplication6
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
\App_Start\Config.Auth.cs (or .vb)
namespace WebApplication6
{
public partial class Startup {
public void ConfigureAuth(IAppBuilder app)
{
// removed for brevity
}
}
}
I see that both classes are declared as partial, but in the many examples online of how to use OWIN, the classes are not partial (see here, here, here and here).
Could anyone please explain if there is a correct or best approach, and what difference it makes to the application whether partial is used or not?
The accepted answer is true if and only if the code generator is generating the file each and every time a build happens. The example with OWIN does not qualify since both files are generated only once when the framework / scaffolding choices are made.
Therefore the only reason I can see that the startup is generated as a partial class is that the framework developers did not want to couple the generation of the owin authorization (a cross cutting concern) with the generation of the startup scaffolding; however, they were only successful in removing the clutter from the base startup.cs scaffolding and were not able to decouple it since they had to introduce the OwinStartupAttribute to the base start up and make a call to the method introduced in the new partial class ConfigureAuth. This is actually a perfect example of how not to use a partial class. Partial class definitions should be decoupled otherwise the benefit gained by using partial class is outweighed by the indirection it creates. Having to modify the base partial class definition to add another partial class to add the OWIN authorization makes it clear to me that this is a flawed approach.
I think I found an answer here, but would still appreciate anything others can add in the context of OWIN specifically:
https://stackoverflow.com/a/3601918/792888
The biggest use of partial classes is make life easier on code
generators / designers. Partial classes allow the generator to simply
emit the code they need to emit and do not have to deal with user
edits to the file. Users are likewise free to annotate the class with
new members by having a second partial class. This provides a very
clean framework for separation of concerns.
So the partial class is simply compiled into a class. The partial declaration allows other classes with the same name to co-exist (which are then all compiled together into a single class).

Pass objects to application from HttpModule

Is there a way to create objects in HTTP module and pass those objects to applications.
I can use HTTPContext.Items. But that means I will reference System.Web in any DLL in the application that will use those data. Utility.dll is reading data generated by the http module, and I don't want to reference System.Web in that DLL because it is used by both web and desktop applications.
of course Desktop applications will not find the object, this is not a problem.
You can use the new and extensible cache API in System.Runtime.Caching, namely, the MemoryCache class. Just use a shared constant as the name and you're done.
I think your web module should communicate with Utility.dll and not the other way around. It should call a function inside Utility.dll with the data it needs. Since we don't know much about the nature of your application and that you didn't provide much information about how you want your different modules to communicate, it hard to give a definite answer.
The Utility.dll module could have a method accepting data like
public void QueueProcessingData(YourDataType[] data) {/* ... */}
If you really want your Utility.dll module to pull data from the web server, then you could use the builtin cache like #Ricardo Peres said. Example of using the builtin MemoryCache:
var data = "object your web module created and you want to pass to utility.dll";
ObjectCache cache = MemoryCache.Default;
cache.Add("The name you want", data, new CacheItemPolicy { AbsoluteExpiration = DateTime.MaxValue });
That way your other modules don't have to reference System.Web
HttpContext.Items is an IDictionary, so you can avoid a System.Web dependency in your common code by depending on that abstraction:
Utility.dll
class Util
{
static void DoStuff(IDictionary environment) { ... }
}
App.dll
class App
{
void DoStuff()
{
Util.DoStuff(new Hashtable { { "Foo", "Bar" } });
}
}
Web.dll
class MyModule : IHttpModule
{
void Init(HttpApplication context)
{
Util.DoStuff(context.Context.Items);
}
}
Thanks to #user1429080. it is kind of simple DI pattern.
Add an interface to Util.dll.
Add a reference to it in class Util add a property to access it.
The interface is implemented in WebUtil.dll. WebUtil is referencing System.Web.
In HttpModule.Init() I assign the implementation to the interface.
Util class is using the interface to read data generated from HttpModule instead of accessing System.Web.
Now I can have another source of data by creating another implementation for the interface.

Setting up Non-Public Properties using Moq Functional Syntax

Anyone know if the Moq functional syntax supports setups for Non-Public properties? I noticed that it doesn't work.
NOTE: This is for the functional syntax.
public class Foo
{
public virtual int FooProperty { get; protected set; }
}
This doesn't throw an error, but fails to mock FooProperty
Mock.Of<Foo>(x => x.FooProperty == 1);
The regular syntax works fine.
var mockFoo = new Mock<Foo>(); mockFoo.SetupGet(x=>x.FooProperty)
.Returns(1)
It might be worth looking at the Pex/Moles tool from Microsoft Research. Moles is used to create accessors for non-public stuff.
It will support mocking of internal properties if you add an assembly attribute to the assembly containing the class under test (add to AssemblyInfo.cs):
// This assembly is the default dynamic assembly generated Castle DynamicProxy,
// used by Moq. Paste in a single line.
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
(You would also have to add an InternalsVisibleTo entry for your test project, of course.)
If you do this, you can mock any internal property in the assembly to which this is added. If you want to mock private or protected properties, I'm pretty sure there's no way to do that directly. If they're protected, you could create a Dummy inheritor and give it public methods or properties that access/manipulate its protected members. For private, there's really nothing you can do, I believe.

How to use Ninject.Web.PageBase alongside another, custom .NET PageBase

I am trying to get Ninject working with a WebForms application that already has a custom PageBase object. But, I don't know for sure if I can use Ninject's PageBase object alongside another, custom PageBase. I've been searching for a while now to see if I could find an answer to this problem, or to learn how to do it, but all I've found is this:
I've hacked together an alternative using a shared base class that
derives from Page. It looks roughly like this
public abstract class PageBase : Page
{
public IKernel Kernel { get; private set; }
public PageBase() { Kernel = ...; }
public void Page_Init() { Kernel.Inject(this); }
}
This will allow you to property and method injection on any pages that
inherit from PageBase. Note that the constructor is incomplete --
you'll have to access the kernel in some static fashion. You should
be able to read it from the HttpApplication somehow.
(source: http://groups.google.com/group/ninject/browse_thread/thread/317fc48387399aa6, linked from Ninject with ASP.Net webforms and MVC):
This looks like it might work for me because it appears that I could apply this code to the existing, custom PageBase. But, I am hung up on the part in which the author says, "... the constructor is incomplete -- you'll have to access the kernel in some static fashion."
Does anyone have any idea what that sentence means, and how one might go about accessing the Ninject kernel in a static fashion?
You do not need to derive from a Ninject page base. You can alternatively use the NinjectHttpModule.
https://github.com/ninject/ninject.web/blob/master/src/Ninject.Web/NinjectHttpModule.cs

Resources