Shorten Controller method in MVC - asp.net-mvc

So I am writing an ASP.NET Core MVC application where users should be able to upload an Excel file, when a file gets uploaded I need to read the uploaded file an create a Model of the data inside the file.
I am currently creating this model in my Controller method but this made my method quite long.
My current solution is creating a class inside my Controller which deals with creating a model from an Excel file but I feel like this is the wrong way to do it.
So my question is: What is the right place to put the code that reads my excel file and puts it inside a model?

You should create a new .NET Standard library and create there the class that builds the model.
The recommended way is to use the class as an implementation and an interface (IExcelModelBuilder) that exposes all the public methods of that class (ExcelModelBuilder). This way you can inject this service into your controller constructor and, as a bonus, you can easily unit test it too.
You can read more about Dependency Injection in .NET Core.
You can register the service in your startup file:
// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
{...}
services.AddTransient<IExcelModelBuilder, ExcelModelBuilder>();
}

Step 1:Create a new .NET Standard library (Services)
Step 2:Add the reference into the mvc application of that library.
Step 3:Step two create a class that will be dealing with all the stuff like that if you have a limited number of tasks to perform ,
but if you want to separate it and wants a generic solution then Create an Interface (IUpload) and then implement all its methods in a class (Upload).also register the service in your startup file:

Related

How do I utilise Assembly from within WebAPI Controller

I have a VS2017 WebAPI solution that I am working on at the moment. I need to make a call to an assembly (included in the solution) from within the Controller. Much to my frustration it appears that I cannot make a call to methods within the assembly.
The graphic below I believe should supply sufficient detail for the right advice. Likely I am trying to do something with the WebAPI project that it will not allow (but I hope not) :-)
Update
On reflection the graphic doesn't appear to be all that legible. Within the PIInterfaceController I have added the following code:
Imports System.Net.Http
Imports System.Web.Http
Imports SPEN.PIInterface
Namespace Controllers
Public Class PIInterfaceController
Inherits ApiController
Dim piServerSetting As String
'Instantiate the SPEN PI Interface object so we can supply necessary data elements as required to extract the correct data from PI
Dim piIntfc As New SPEN.PIInterface(piServerSetting)
piIntfc.
End Class
End Namespace
My problem is that I am unable to access any of the methods from the PIInterface instance 'piIntfc'.

What are Modules in aspnetBoilerplate?

aspnetBoilerplate is based on Domain Driven Design design pattern.
I see that aspnetBoilerplate compose an application using modules.
I didn't understand what a module is , i searched it's definition in the context of domain driven design and i found that it serves as a container for a specific set of classes of an application.
So does that means ,For example , in c# namespace is a module because it can contains many classes ?
But even with this definition , it's not clear in the context of aspnetBoilerplate, a module defintion in aspnetBoilerplate have this structure :
public class MyBlogApplicationModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
so it's just one class,that have one method !
Also what is the relationship between model and dependency injection ?
Why there is a registration of the model as a service in an IocContainer?
Abp module is just a way for you to organize your code under the same domain/layer and at the same time still being able to configure/interact with other modules
E.g. your module is a separate library project that contains certain domain logic, to initialize your module correctly, you can place the initialization code in module life cycle hooks
Note: register DI in the life cycle hooks is an example of interacting with the DI service (that might be configured outside of your project)
See
https://aspnetboilerplate.com/Pages/Documents/Module-System#lifecycle-methods
Abp provides convenient way to register classes that follows the convention
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
Note: the recommended way is to only have a abp module per assembly
See
https://aspnetboilerplate.com/Pages/Documents/Dependency-Injection#registering-dependencies

Common place to add methods

I am a newbie to Grails and still learning the ropes! The application that i work on uses services.
My task is to add a new method in one of the services and have it get called from clients.
This new method is going to be pretty long and i don't want all the method body to be in the service class.
I would like to add another method in a place other than this service to do all the calculations for this new method.
Which is the best place to add a method like that? Should i add a new domain? Or just a controller class?
I don't want any of the information in the new method to be saved to database.
A sample code look like this:
class MyService {
String getDomainName(String ID) {
return domainNameGenerator(ID);
}
}
Now i want to put the domainNameGenerator method into another place.
Place your standalone code in src/groovy or src/java depending on the actual language of your code, but there's nothing wrong with putting code in the service class itself. If the new class and the service package is the same, you don't even have to add an import.

What's the best way to inject different implementations of the same interface in to a controller using StructureMap?

I am fairly new to StructureMap, but my understanding is that there are two ways of getting an instance from the ObjectFactory:
By type (i.e. ObjectFactory.GetInstance<IFoo>())
By type and name (i.e. ObjectFactory.GetNamedInstance<IFoo>("foo.bar"))
I have seen a multitude of examples out there demonstrating how to create an MVC Controller Factory that will provide controller instances using StructureMap, and in most cases I have seen, they are using the method from option #1 above.
Let's say we have some controller that accepts a repository/DAO interface as a constructor arg...
public class FooController : Controller
{
public FooController (IFooRepository fooRepository)
{
// constructor code goes here
}
}
Using the interface class gives me the ability to "inject" any implementation of that interface in to my controller. What if for two different actions, I want to inject different implementations? Perhaps in one case, I need an implementation of my repository that will query a SQL Server database, and in another case, I need an implementation that will get data from an XML file or through a Web Service call.
It seems that if you use the ObjectFactory.GetInstance() method, you would be restricted to only providing your controller with a single implementation of your repository interface.
However, if you go with named instances, then you will end up having to create the instances based on the name of the controller that the MVC framework provides. In most cases, this will typically be the controller name coming from the URL, but it's really up to the route configuration. This seems like it could be very confusing, and would only get more confusing as the number of routes increased.
Is there any alternative method that would allow for different controller instantiation strategies without using named instances? Would it be a better idea to just create separate controllers, and make sure that all the actions in any given controller will be valid for the same concrete instance of a repository/DAO class?
For what it's worth, I ended up going with named instances, where the names of each instance are based on the name of the controller that the MVC framework pulls from the URL.
For instance, the URL /foo/DoSomething might get an IController instance from the ObjectFactory that is instantiated with a Repository object that uses the SqlClient API for data access. A URL such as /foo.webservice/DoSomething would then create an instance of the same concrete controller class, but pass that instance's constructor a repository object that uses a web service for data access.
There are several ways to override StructureMap's default auto-wiring behavior for constructor arguments. In my case, I used the CtorDependency and Is methods, and had mappings that looked something like this...
// create a named instance for the "foo" controller that uses the SqlClient based repository
InstanceOf<IController>()
.Is.OfConcreteType<FooController>()
.CtorDependency<IFooRepository>()
.Is(new FooRepositorySql(Constants.FooConnectionString))
.WithName("foo");
// create a named instance for the "foo.webservice" controller that uses the Web Service based repository
InstanceOf<IController>()
.Is.OfConcreteType<FooController>()
.CtorDependency<IFooRepository>()
.Is(new FooRepositoryWs(Constants.FooServiceUrl))
.WithName("foo.webservice");

Access to Entity Manager in ASP .NET MVC

Greetings,
Trying to sort through the best way to provide access to my Entity Manager while keeping the context open through the request to permit late loading. I am seeing a lot of examples like the following:
public class SomeController
{
MyEntities entities = new MyEntities();
}
The problem I see with this setup is that if you have a layer of business classes that you want to make calls into, you end up having to pass the manager as a parameter to these methods, like so:
public static GetEntity(MyEntities entityManager, int id)
{
return entityManager.Series.FirstOrDefault(s => s.SeriesId == id);
}
Obviously I am looking for a good, thread safe way, to provide the entityManager to the method without passing it. The way also needs to be unit testable, my previous attempts with putting it in Session did not work for unit tests.
I am actually looking for the recommended way of dealing with the Entity Framework in ASP .NET MVC for an enterprise level application.
Thanks in advance
Entity Framework v1.0 excels in Windows Forms applications where you can use the object context for as long as you like. In asp.net and mvc in particular it's a bit harder. My solution to this was to make the repositories or entity managers more like services that MVC could communicate with. I created a sort of generic all purpose base repository I could use whenever I felt like it and just stopped bothering too much about doing it right. I would try to avoid leaving the object context open for even a ms longer than is absolutely needed in a web application.
Have a look at EF4. I started using EF in production environment when that was in beta 0.75 or something similar and had no real issues with it except for it being "hard work" sometimes.
You might want to look at the Repository pattern (here's a write up of Repository with Linq to SQL).
The basic idea would be that instead of creating a static class, you instantiate a version of the Repository. You can pass in your EntityManager as a parameter to the class in the constructor -- or better yet, a factory that can create your EntityManager for the class so that it can do unit of work instantiation of the manager.
For MVC I use a base controller class. In this class you could create your entity manager factory and make it a property of the class so deriving classes have access to it. Allow it to be injected from a constructor but created with the proper default if the instance passed in is null. Whenever a controller method needs to create a repository, it can use this instance to pass into the Repository so that it can create the manager required.
In this way, you get rid of the static methods and allow mock instances to be used in your unit tests. By passing in a factory -- which ought to create instances that implement interfaces, btw -- you decouple your repository from the actual manager class.
Don't lazy load entities in the view. Don't make business layer calls in the view. Load all the entities the view will need up front in the controller, compute all the sums and averages the view will need up front in the controller, etc. After all, that's what the controller is for.

Resources