mvc – C# – Transformar CUIL/CUIT numerico pasandole a string y agregandole los 2 guiones (-) que lleva

quisiera saber cual es la mejor forma para poder hacer lo siguiente en C#
Recibo los CUIL/CUIT de la siguiente forma numerica. Ejemplo: 20354002003
y quisiera pasarlo a string y a su vez agregarle los dos guines que lleva y que quede de la forma: 20-35400200-3

Muchas gracias!

web applications – What is the recommended javascript front end for asp.net mvc core

We are planning to start developing a new web application, as we chose the following technologies:

  1. Asp.net CORE MVC

  2. Entity Framework

  3. Sql Server 2016

but we did not settle on the front end tool used, we have these 3 options:

  1. Angular

  2. React js

  3. Run the front end using pure jQuery and bootstrap, without using dedicated front end framework..

so can anyone advice about the advantages and disadvantages of each approach?

Thanks

asp.net mvc – Ao publicar o projeto no IIS não aparece script e css, o que pode ser?

Ao publicar o projeto no servidor e configurar o iis ele não reconhece o css e script, ele não da erro, encontra o endereço mais não carrega o código css e js.

Verifiquei no diretório do publish no servidor, eu abro o arquivo no notepad e o código está la, mais ele não interpreta.

Se alguem tiver alguma ideia que possa ajudar, agradeço. Pois como se ver na imagem, tenho um monte de projeto publicado sem erro.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

design – OOD vs MVC; Live Objects vs Everything in Database

How to make memory-efficient code, but still have all the possible code nicely encapsulated ?

I have a feeling that the OO (object oriented) approach is more intuitive and the code is nicely organized and encapsulated, but it can use a lot of memory, because there are usually many live object instances in the memory.

In contrast, the MVC (controller, model (database)) approach code is much less encapsulated but uses much less memory, because the objects in memory are only when some client asks for them, and then they are disposed.


I need to make an internal health monitoring system, to periodically ping ip cameras.
There will be about 10,000 items (cameras) to monitor, with a boolean state – Good / Bad.

If I go the OO way – I will hold a class for each of the item, with its ping result, timer, events to notify some other items. So I will end up with 10,000 instances in memory all the time. There is not much, but what if there were 100,000,000 items. I prefer this way, because it is intuitive and I have a perfect (encapsulated) place for any code I may need to run in the concrete item class (timers, events, handlers, subscriptions).

If I go the MVC way – I will hold all the data in database, so the memory usage will be minimum.
But I will have to improvise a way to trigger code execution, like periodic timers, events, handlers, subscriptions.
And that code – where will it be written? Will it be nicely encapsulated?
Also, what code will call those triggers? Will it also be encapsulated?
For example, I can make a timers engine, and hold a dictionary of timers for each of the 10000, but then the code will not be encapsulated.

design patterns – I am writing a small 3-tier mvc application. I am a beginner, and i would like to know what can i do better on it

I have heard using other design patterns like factory, or observer, but i don’t really see how to implement them in my application. Since i am a beginner, i am sure this needs improvements, but i don’t really know how. Any help is welcome.

Repository class

internal class Repository<T> : IRepository<T>
    where T : class
{
    private readonly DbSet<T> dbSet;
    private readonly ApplicationDbContext dbContext;

    public Repository(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
        this.dbSet = dbContext.Set<T>();
    }

    public async Task<T> GetAsync(Expression<Func<T, bool>> predicate)
    {
        return await dbSet.FirstOrDefaultAsync(predicate);
    }

    public IAsyncEnumerable<T> GetAll(Expression<Func<T, bool>> predicate)
    {
        return dbSet.Where(predicate).AsAsyncEnumerable();
    }

    public async Task AddAsync(params T() entities)
    {
        await dbSet.AddRangeAsync(entities);

        await SaveChanges();
    }

    public async Task UpdateAsync(params T() entities)
    {
        dbSet.UpdateRange(entities);

        await SaveChanges();
    }

    public async Task DeleteAsync(params T() entities)
    {
        dbSet.RemoveRange(entities);

        await SaveChanges();
    }

    private async Task SaveChanges()
    {
        await dbContext.SaveChangesAsync();
    }
}

Unit of work class

public class UnitOfWork : IUnitOfWork
{
    public IRepository<User> UserRepository
    {
        get
        {
            return this.userRepository ?? (this.userRepository = new Repository<User>(dbContext));
        }
    }
    public IRepository<Following> FollowingRepository
    {
        get
        {
            return this.followingRepository ?? (this.followingRepository = new Repository<Following>(dbContext));
        }
    }
    public IRepository<Attendance> AttendanceRepository
    {
        get
        {
            return this.attendanceRepository ?? (this.attendanceRepository = new Repository<Attendance>(dbContext));
        }
    }
    public IRepository<Genre> GenreRepository
    {
        get
        {
            return this.genreRepository ?? (this.genreRepository = new Repository<Genre>(dbContext));
        }
    }

    public IRepository<Notification> NotificationRepository
    {
        get
        {
            return this.notificationRepository ?? (this.notificationRepository = new Repository<Notification>(dbContext));
        }
    }

    public IRepository<UserNotification> UserNotificationRepository
    {
        get
        {
            return this.userNotificationRepository ?? (this.userNotificationRepository = new Repository<UserNotification>(dbContext));
        }
    }
    public IRepository<Show> ShowRepository
    {
        get
        {
            return this.showRepository ?? (this.showRepository = new Repository<Show>(dbContext));
        }
    }

    private IRepository<User> userRepository;
    private IRepository<Following> followingRepository;
    private IRepository<Attendance> attendanceRepository;
    private IRepository<Genre> genreRepository;
    private IRepository<Notification> notificationRepository;
    private IRepository<UserNotification> userNotificationRepository;
    private IRepository<Show> showRepository;

    private readonly ApplicationDbContext dbContext;

    public UnitOfWork(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext;
    }
}

Service Class

public class UserService : IUserService
{
    private readonly IUnitOfWork unitOfWork;

    public UserService(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    public LoggedInUserDto Login(UserLoginDto userLogin)
    {
        LoggedInUserDto loggedInUser = new LoggedInUserDto
        {
            SessionId = Guid.NewGuid()
        };
        return loggedInUser;
    }

    public void Logout(long userId)
    {
        // do the logout
    }

    public async Task RegisterAsync(UserDto userDto)
    {
        User user = new User();
        user.FirstName = userDto.FirstName;
        user.LastName = userDto.LastName;
        user.Type = (UserType) userDto.Type;
        await unitOfWork.UserRepository.AddAsync(user);
    }

    public async Task<bool> UpdateUserAsync(UserDto userDto)
    {
        User user = await unitOfWork.UserRepository.GetAsync(u => u.Id == userDto.Id);
        if (user == null)
            return false;
        else
        {
            user.FirstName = userDto.FirstName;
            user.LastName = userDto.LastName;
            user.Type = (UserType)userDto.Type; 
            await unitOfWork.UserRepository.UpdateAsync(user);
        }
        return true;
    }

    public async Task<UserDto> GetUserAsync(Guid Id)
    {
        User user = await unitOfWork.UserRepository.GetAsync(u => u.Id == Id);
        if (user != null)
        {
            UserDto userDto = new UserDto();
            userDto.FirstName = user.FirstName;
            userDto.LastName = user.LastName;
            userDto.Type = (UserTypeEnum)user.Type;
            return userDto;
        }
        return null;
    }
}

Controller class

public class UserController : LiveShowApiControllerBase
{
    private readonly IUserService userService;
    private readonly IShowService showService;

    public UserController(IUserService userService)
    {
        this.userService = userService;
        this.showService = showService;
    }

    (HttpPost("login"))
    public IActionResult Login(UserLoginDto userLogin)
    {
        LoggedInUserDto loggedInUser = userService.Login(userLogin);

        return Ok(loggedInUser);
    }

    (HttpGet("logout"))
    public IActionResult Logout()
    {
        return Ok("logout");
    }

    (HttpGet("{id:guid}"))
    public async Task<IActionResult> ProfileAsync(Guid id)
    {
        var user = await userService.GetUserAsync(id);
        return Ok(user);
    }

    (HttpPost("register"))
    public async Task<IActionResult> RegisterAsync(UserDto user)
    {
        await userService.RegisterAsync(user);
        return Ok(user);
    }

    (HttpPut)
    public async Task<IActionResult> UpdateProfile(UserDto user)
    {
        bool success = await userService.UpdateUserAsync(user);
        if (success)
            return Ok("found & updated");
        else
            return BadRequest("Entity not found");
    }
}

PHP: Transformación de web estructurada a POO + MVC

Estoy “traduciendo” una página que ya casi tenía hecha de forma estructurada a POO + MVC. Lo estoy haciendo siguiendo las indicaciones de un curso de Udemy, y el instructor utiliza un controlador frontal en el index que decide vía GET a qué controlador y a qué método de dicho controlador se está llamando; algo similar a esto:

if($GET("controlador")) $controlador_c = $GET("controlador")."C";
else $controlador_c = controlador_base;

if(class_exists($controlador_c))
{
    $controlador = new $controlador_c;

    if($GET("accion"))
    {
        $accion = $GET("accion");
        $controlador->$accion();
    }
    else
    {
        $accion = accion_base;
        $controlador->$accion();
    }
}

Mi web original tiene un “controlador” frontal que carga documentos enteros en los que se mezclan llamadas a la base de datos, lógica diversa, HTML, etc., tal que así:

if($_GET('fichero')) $archivo = $_GET('fichero');
else $archivo = 'global.php';

include($archivo);

Mi duda es cómo adaptar mi web al nuevo sistema, porque para replicar algunos documentos creo que voy a tener que cargar en ocasiones varios objetos distintos creados a partir del mismo controlador, o de distintos controladores incluso, y me surge la duda de cómo llamarlos a todos a la vez.

Por ejemplo, el documento “decadas.php”:

Décadas

En éste se hacen dos llamadas a la base de datos muy similares, lo que pasa que la de la columna izquierda está limitada a 15 resultados y la de la derecha, a 3.

Esto, en POO, supongo que implicaría crear dos objetos con distintos parámetros a partir del mismo controlador, pero ¿a cuál llamar mediante el controlador frontal? ¿Y cómo mostrar ambos a continuación?

Un saludo y gracias por adelantado.

c# – System Design – ASP.Net MVC Preparations

I’m about to start an asp.net mvc project with Repositorty-Service pattern and I’m first gathering information. Therefore I’ve got few questions that I need clarification before I start implementing.

In my company, most of the asp.net mvc projects developed by senior developers possess common features such as :

So my questions are :

1) Do I always need a caching mechanism and logging and Security(Encryption – AES…) in an asp.net mvc app?

2) When do I need them? I mean in what situation do I need caching and logging and Security(Encryption)? please give me detailed answer for each for clarification.

3) Is it fine/professional to use in a real-world asp.net project, the default ASP.Net MVC authentication code that gets generated when you create a new asp.net app? as I’m building a quite big asp.net (not very big) web app with Repository-Service pattern and I just want to reuse the default MS ASP.Net authentication (to save me time) instead of writing a new one.

4) Do I need to use SQL Server or MongoDB as database? I know that MongoDB is best suited for scalability but I don’t want to use a library which I’ll be forced to dig in to its library DLL and modify some code in order to make it work, as I don’t want to waste my time as the project is timed.

database – Does the Controller contain get methods in MVC?

In a true MVC, the controller takes the input from the user, and translates it into commands either for controlling the views (e.g. create a new view or close a view) or for the model (e.g. updating the price, saving changes,…).

The methods that you describe do not belong to the controller but to the model: adding priced items, updating prices, removing stock keeping units (sku) and remove all the items is the responsibilitiy of the model. To quote your article:

the Model is the name given to the permanent storage of the data used in the overall design. It must allow access for the data to be viewed, or collected and written to, (…)
The Controller can be summed up simply as a collector of information, which then passes it on to the Model to be organized for storage, and does not contain any logic other than that needed to collect the input. (…)
The most common mistake made by developers is confusing the Controller for a gateway, (…)

So the controller shall not just be a gateway to the database. All database interactions belong to the model: the controller and the view know nothing about the database: they only know about the model.

Additional remarks :

There are several MVC variants that all share the principles above. In your article, there is one controller per view.

An ORM makes the mapping between objects (application) and tables (database) and facilitates access to the database. In an MVC architecture, the ORM is used to implement the model. It should not replace the model.

Different architectures may distribute responsibilities differently. But it’s no longer MVC:

  • If a controller acts as middleman between views and model, and views querry the controllen, then it’s probably no longer a controller but a presenter in an MVP
  • If a view has furthermore some databinding that is synched with the model via the controler, it’s probably no longer a controller but a view-model in an MVVM
  • If a controller has some business logic and database responsibilities that are not in the model, you probably made something wrong in the MVC, or there is a misunderstanding about the architecture that implements and EBC pattern in which the controller has a different purpose.