Create a Base TagHelper with no TargetElement - asp.net-core-mvc

I'm creating a library of MVC6 TagHelpers for a large project.
I find myself writing certain functionality in these TagHelpers again and again.
I'd like to make a base TagHelper that all the others inherit from to remove all the duplicated code.
The issue is this - suppose I create a base TagHelper as below:
public class BaseTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
//Some implementation...
}
}
Now, when I go to write a view, I will have intellisense suggesting the taghelper <base>.
Is there any way I can tell intellisense that this isn't a TagHelper I actually want to use, just a base class containing implementation common to other TagHelpers I've created?

Create it as an abstract class, see some examples in the official MVC Core repo like CacheTagHelperBase
public abstract class BaseTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
//Some base implementation...
}
}

Related

Error if the [AssemblyInitialize] already exists in the test project with Specflow

I've updated Specflow from the 3.0.225 to the 3.1.62 and I received the error Tests_Integration_MSTestAssemblyHooks: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.
The reason is obviously that I'd had the [AssemblyInitialize] attribute in my project already. How can I fix it?
The reason is that Specflow generates another file in the background which has the AssemblyInitialize/AssemblyCleanup hooks defined. In order to fix that one should use the hooks provided by Specflow, namely BeforeTestRun/AfterTestRun. Like this:
[Binding] // add the Binding attribute on the class with the assembly level hooks
public abstract class SeleniumTest
{
// it used to be [AssemblyInitialize]
[BeforeTestRun]
public static void AssemblyInitialize(/* note there is no TestContext parameter anymore */)
{
// ...
}
// it used to be [AssemblyCleanup]
[AfterTestRun]
public static void AssemblyCleanup()
{
// ...
}
}

How can i use custom dbcontext (Audit Log) with sharprepository

I have a custom dbcontext which name is Tracker-enabled DbContext (https://github.com/bilal-fazlani/tracker-enabled-dbcontext).I want to use it for audit log
And how can I implement EFRepository?
I implemented tracker-enabled-context but i cant solve how override sharp repo commit method.
public class HayEntities : TrackerContext
{
static HayEntities()
{
Database.SetInitializer<HayEntities>(null);
}
public HayEntities() : base(HayEntities)
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ValidateOnSaveEnabled = false;
}
public DbSet<Dummy> Dummys{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new DummyConfiguration());
} }
}
public class DummyRepository : ConfigurationBasedRepository<DE.Dummy, long>, IDummyRepository
{
private readonly IRepository<DE.Dummy, long> _servisHasarRepository;
public DummyRepository (HayEntities hayEntities, ICachingStrategy<DE.Dummy, long> cachingStrategy = null)
{this.CachingEnabled = false;
_dummyRepository = new EfRepository<DE.Dummy, long>(hayEntities, cachingStrategy);
}
public void UpdateOrCreate() {
//In this area how can override save/commit method
}
}
You will want to tell SharpRepository to use an IoC provider to inject the DbContext. This will take care of getting the proper DbContext for your EfRepository.
If you want to control things based on the configuration and have custom repositories so you can implement your own mehods like UpdateOrCreate() then you would inherit from ConfigurationBasedRepository as you have in the example.
There are more details on setting up IoC with SharpRepository here: http://fairwaytech.com/2013/02/sharprepository-configuration/ (look in the "Entity Framework and Sharing the DbContext" section)
First look on NuGet for SharpRepository.Ioc.* to find the specific IoC you are using. If you are using StructureMap then you would do something like this.
In your StructureMap configuration:
// Hybrid (once per thread or ASP.NET request if you’re in a web application)
For<DbContext>()
.HybridHttpOrThreadLocalScoped()
.Use<HayEntities>()
.Ctor<string>("connectionString").Is(entityConnectionString);
Then you need to tell SharpRepository to use StructureMap by calling this in your startup code:
RepositoryDependencyResolver.SetDependencyResolver(new StructureMapDependencyResolver(ObjectFactory.Container));
After doing these things, then if you use EfRepository then it will know to ask StructureMap for the DbContext.
Now in your example above where you are using ConfigurationBasedRepository, I would suggest setting the caching in the configuration file instead of in code since you are using the configuration to load the repository. Since IoC is handling the DbContext you don't need to do anyhing with that and you can focus on the custom method you want to write.
public class DummyRepository : ConfigurationBasedRepository<DE.Dummy, long>, IDummyRepository
{
public void UpdateOrCreate()
{
// You have access to the underlying IRepository<> which is going to be an EfRepository in your case assuming you did that in the config file
// here you can call Repository.Add(), or Reposiory.Find(), etc.
}
}

Implementing IntelliSense support for custom language (C++)

I wan to implement IntelliSense support for custom language. Actually it is a customize version of C++. i.e the methods resides in separate files
So my main class is like followings and it has import file MyClassMethods which has all the methods.
public class MyClass {
#import MyClassMethods
// my code goes here
}
So my MyClassMethods fiel looks like following and it has two methods,
public void testMethod1() {
}
public void testMethod2() {
}
Then at the end I want to have IntelliSense features when I working on MyClass. Example when I put dot character on that class in a required place I want to have testMethod1() and testMethod2() in the IntelliSense menu.
Is this possible to achieve and if so how can I achieve this?

WebApi Controller action parameter base class for common features

Where WebApi Controller actions share identical features, E.g. pagination and partial response, is it possible to create a base class to model these parameters?
For example, this URI:
http://letsdoitclean.com/api/v1/athletes?clean=true&fields=name,age&offset=0&limit=25
might map to:
class AthletesController
{
IHttp Get(bool clean, string[] fields, int offset, int limit)
{
...
}
}
However, fields, offset and limit are concepts that will be frequently used. So I want something like:
abstract class ActionParameter
{
public string[] fields;
public int offset;
public int limit;
}
class AthletesGetParameter : ActionParameter
{
public bool clean;
}
class AthletesController
{
IHttp Get(AthletesGetParameter param)
{
...
}
}
Can I do it?
This could also be achieved by adding it globally to your WebApiConfig so that you don't have to mark it up in every single controller action:
config.ParameterBindingRules.Insert(0, descriptor =>
typeof(ActionParameter).IsAssignableFrom(descriptor.ParameterType)
? new FromUriAttribute().GetBinding(descriptor)
: null);
Yes, absolutely you can do this. ASP.NET will handle the parameter binding if you, in this example, specify the FromUriAttribute for the complex object:
public class AthletesController : ApiController
{
public string Get([FromUri] AthletesGetParameter athletesGetParam)
{
// ...
}
}
The only thing I would argue against from your question, is the name of the abstract class. It doesn't really describe the base class all that well and what it's intended for. Maybe something like abstract class PaginationParameter or something similar. To call it ActionParameter could confuse you in the future (or other programmers) that all action parameters should derive this class, and I don't think that's right.
Maybe minutia on the naming of the base class, but to answer your direct question... yes you can do this.

Mvc3 - Best practice to deal with data which are required for (almost) all requests?

I am creating an application in mvc3 and wondering how to deal with database data which is required for all application requests, some of them depends on a session, some of them depends on url pattern basically all data is in database.
Like to know best practice
What I do in my applications and consider to be the best practice is to load your common data to the ViewBag on the Controller constructor.
For every project, I have a DefaultController abstract class that extends Controller. So, every controller in the project must inherit from DefaultController, instead of Controller. In that class' constructor, I load all data common to the whole project, like so:
// DefaultController.cs
public abstract class DefaultController : Controller
{
protected IRepository Repo { get; private set; }
protected DefaultController(IRepository repo)
{
Repo = repo;
ViewBag.CurrentUser = GetLoggedInUser();
}
protected User GetLoggedInUser()
{
// your logic for retrieving the data here
}
}
// HomeController.cs
public class HomeController : DefaultController
{
public HomeController(IRepository repo) : base(repo)
{
}
// ... your action methods
}
That way you will always have the logged in user available in your views.
I do the same as #rdumont but with one exception: I create a CommonViewModel which I use to define all common properties that I use.
public class CommonViewModel
{
public string UserName {get;set;}
public string Extension {get;set; }
}
Declare a property in the base controller:
public abstract class BaseController : Controller
{
protected CommonViewModel Commons { get; private set; }
protected virtual void OnResultExecuting(ResultExecutingContext filterContext)
{
ViewBag.Commons = Commons;
}
}
By doing so I get everything almost typed. The only cast that I need to do is to cast ViewBag.Commons to the CommonViewModel.
Best is to avoid ViewBag at all.
See this answer, which details how to use Html.RenderAction() for that purpose:
Best way to show account information in layout file in MVC3
I'd suggest using a base ViewModel class.
So a base class with properties/functions which should be available at any point.

Resources