Download Logo

MVC filters

What do you understand by filters in MVC? Filters are components that enable developers to inject logic into the request processing pipeline at various stages. Filters are used to perform tasks such as logging, authentication, authorization, exception handling, caching, and more. Filters provide a way to encapsulate cross-cutting concerns. Filters can be applied globally to the entire application or selectively to specific controllers or action methods. There are several types of filters in ASP.NET MVC: ...

August 3, 2024 · 3 min · 585 words · PrashantUnity
Download Logo

MVC request lifecycle

Explain the MVC application life cycle Any web application has two primary execution steps: Understanding the request Sending out an appropriate response MVC application life cycle includes two main phases: Creating the request object Sending response to the browser The steps included in creating a request object are: Request Routing: When a user makes a request, the ASP.NET MVC application starts by using a routing engine to determine which controller and action method should handle the request. The route configuration defines how URLs map to controllers and actions. Controller Execution: ...

August 3, 2024 · 3 min · 432 words · PrashantUnity
Download Logo

MVC routing Q&A

How is routing carried out in the MVC pattern? The routing mechanism in ASP.NET MVC is responsible for determining which controller and action should handle a particular request based on the URL of the request. The routing process typically involves the following steps: Incoming Request: When a user makes a request to our ASP.NET MVC application by entering a URL in the browser, the request is received by the ASP.NET runtime. ...

August 3, 2024 · 4 min · 802 words · PrashantUnity
Download Logo

MVC set — starter

What is ASP.NET MVC Core? ASP.NET MVC Core is a modern, open-source, cross-platform framework for building web applications. It is a part of the larger ASP.NET Core framework and follows the Model-View-Controller (MVC) architecture pattern. MVC Core is designed to offer greater performance, scalability, and flexibility compared to its predecessors. It allows developers to create web applications that can run on various platforms (Windows, Linux, macOS) and supports cloud-based deployment. Key features include: ...

August 3, 2024 · 40 min · 8437 words · PrashantUnity
Download Logo

Services in Razor views

Accessing Services in Views 1. Using Dependency Injection in Views with Razor Pages To use services directly in Razor Pages, follow these steps: 1.1. Register Services in Startup.cs Ensure your service is registered in the DI container within Startup.cs (or Program.cs in .NET 6 and later). 1 2 3 4 5 public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddScoped<IMyService, MyService>(); // Register your service } 1.2. Inject Services into the View In Razor Pages (.cshtml files), you can inject services directly into the page using the @inject directive. ...

August 3, 2024 · 3 min · 530 words · PrashantUnity
Download Logo

Singleton in C#

Basic Implementation 1 2 3 4 5 6 7 8 9 10 Singleton singleton = Singleton.Instance; sealed class Singleton { public static Singleton Instance { get; } = new(); private Singleton() { } } Null Checking 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Singleton singleton = Singleton.Instance; sealed class Singleton { private static Singleton _instance = default!; public static Singleton Instance { get { if (_instance is null) { _instance = new Singleton(); } return _instance; } } private Singleton() { Console.WriteLine("Instantiating singleton"); } } Thread Safe 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Singleton singleton = Singleton.Instance; sealed class Singleton { private static Singleton _instance = default!; private static object _lock = new(); public static Singleton Instance { get { if (_instance is null) { Console.WriteLine("Locking"); lock (_lock) { if (_instance is null) { _instance = new Singleton(); } } } return _instance; } } private Singleton() { Console.WriteLine("Instantiating singleton"); } } using Dotnet Base Class Library (BCL) 1 2 3 4 5 6 7 8 9 10 11 12 13 Singleton singleton = Singleton.Instance; sealed class Singleton { private static readonly Lazy<Singleton> _lazyInstance = new(() => new()); public static Singleton Instance => _lazyInstance.Value; private Singleton() { Console.WriteLine("Instantiating singleton"); } } Jon Skeet way 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Singleton singleton = Singleton.Instance; sealed class Singleton { public static string ClassName; public static Singleton Instance => Nested.Instance; private class Nested { internal static Singleton Instance { get; } = new(); static Nested() { } } private Singleton() { } static Singleton() { ClassName = "asdf"; } } Using Microsoft Dependency Injection Package 1 2 3 <ItemGroup> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" /> </ItemGroup> 1 2 3 4 5 6 7 8 9 10 11 12 13 using Microsoft.Extensions.DependencyInjection; IServiceCollection services = new ServiceCollection(); services.AddSingleton<Singleton>(); var serviceProvider = services.BuildServiceProvider(); var instance = serviceProvider.GetRequiredService<Singleton>(); class Singleton() { }

August 3, 2024 · 2 min · 371 words · PrashantUnity
Download Logo

SQLite + EF Core

Data Model 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 public class User { [Key] public Guid Id { get; set; } [Required] public string UserName { get; set; } = "Giga Chad"; public byte[] Image { get; set; }= DefaultImage(); private static byte[] DefaultImage() { // Provide logic to load a default image from a file or resource // For example: // return File.ReadAllBytes("default_image.png"); return new byte[0]; // Placeholder default image } public List<Challenge> Challenges { get; set; } } public class Challenge { [Key] public Guid Id { get; set; } [Required] public string Name { get; set; } = "Challenge"; [Required] public int DayCount { get; set; } [Required] public DateTime StartDate { get; set; } [Required] public DateTime EndDate { get; set; } public List<ToDo> ToDos { get; set; } [Required] public Guid UserId { get; set; } // Foreign key public User User { get; set; } // Navigation property } public class ToDo { [Key] public Guid Id { get; set; } public bool IsCompleted { get; set; } [Required] public string Description { get; set; } = "Exercise"; public DateTime CompletionDate { get; set; } public Guid ChallengeId { get; set; } // Foreign key public Challenge Challenge { get; set; } // Navigation property } DBContext or Repositiory 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 public class Repository : DbContext { public Repository(DbContextOptions<Repository> opts) : base(opts) { } public DbSet<User> Users { get; set; } public DbSet<Challenge> Challenges { get; set; } public DbSet<ToDo> ToDos { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { #region Seed Users var user = new User { Id = Guid.NewGuid(), UserName = "Default", Image = GetDefaultImage(), }; var chlng = new Challenge { Id = Guid.NewGuid(), Name = "Streak Visitors", DayCount = 7, StartDate = DateTime.Now, UserId = user.Id }; var todoOne = new ToDo { Id = Guid.NewGuid(), Description = "Task 1", ChallengeId = chlng.Id }; var todoTwo = new ToDo { Id = Guid.NewGuid(), Description = "Task 2", ChallengeId = chlng.Id }; #endregion modelBuilder.Entity<User>().HasData(user); // Seed Challenges modelBuilder.Entity<Challenge>().HasData(chlng); // Seed ToDos modelBuilder.Entity<ToDo>().HasData(todoOne,todoTwo); base.OnModelCreating(modelBuilder); } private byte[] GetDefaultImage() { // Provide logic to load a default image from a file or resource // For example: // return File.ReadAllBytes("default_image.png"); return new byte[0]; // Placeholder default image } } In Case of Live Design/DbCreation 1 2 3 4 5 6 7 8 9 10 11 12 13 public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<Repository> { public Repository CreateDbContext(string[] args) { var connectionString = "Data Source=database.db"; var optionsBuilder = new DbContextOptionsBuilder<Repository>(); optionsBuilder.UseSqlite(connectionString); return new Repository(optionsBuilder.Options); } } Setting up Connection String and using it ...

August 3, 2024 · 5 min · 962 words · PrashantUnity
Download Logo

Video streaming in ASP.NET Core

Video Streaming Implementation Create One Controller CLass and Paste below code in side that class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 [HttpGet("{fileName}")] public IActionResult GetMedia(string fileName) { var filePath = _mediaService.GetMediaFilePath(fileName); if (!System.IO.File.Exists(filePath)) { return NotFound(); } var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); var mimeType = "video/mp4"; var fileInfo = new FileInfo(filePath); long totalLength = fileInfo.Length; long start = 0; long end = totalLength - 1; if (Request.Headers.ContainsKey("Range")) { var range = Request.Headers["Range"].ToString(); var rangeSplit = range.Replace("bytes=", "").Split('-'); start = long.Parse(rangeSplit[0]); if (rangeSplit.Length > 1 && !string.IsNullOrEmpty(rangeSplit[1])) end = long.Parse(rangeSplit[1]); } var contentLength = end - start + 1; var responseStream = new MemoryStream(); fileStream.Seek(start, SeekOrigin.Begin); fileStream.CopyTo(responseStream, (int)contentLength); responseStream.Seek(0, SeekOrigin.Begin); Response.StatusCode = (int)HttpStatusCode.PartialContent; Response.Headers.AcceptRanges = "bytes"; Response.Headers.ContentLength = contentLength; Response.Headers.ContentType = "video/mp4"; Response.Headers.ContentRange = $"bytes {start}-{end}/{totalLength}"; return new FileStreamResult(responseStream, mimeType); }

August 3, 2024 · 1 min · 170 words · PrashantUnity
Download Logo

ViewBag & friends

Data Passing Between Controller and View Using Form Like POST Method ViewBag.Number and (int)ViewData[“Number”] from controller to View Controller to Controller TempData 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public ActionResult SubmitForm(MyModel model) { if (ModelState.IsValid) { // Process the form data // Store a success message in TempData TempData["Message"] = "Form submitted successfully!"; // Redirect to another action return RedirectToAction("Confirmation"); } return View(model); } public ActionResult Confirmation() { // Retrieve the message from TempData ViewBag.Message = TempData["Message"]; return View(); } 1. Using ViewData ViewData is a dictionary-based way to pass data to the view. It uses the ViewDataDictionary class and is accessed by string keys. ...

August 3, 2024 · 2 min · 374 words · PrashantUnity
Download Logo

MVC interview — Set 1

1. Difference between ViewResult and ActionResult ViewResult: It is a type of ActionResult that specifically returns a view. It is used when an action method is designed to return a rendered HTML view to the client. The ViewResult contains the model and view name that will be rendered. ActionResult: This is the base class for all action results in ASP.NET MVC. It represents the result of an action method. An ActionResult can return different types of responses, such as a view, JSON, a file, or a redirect. ViewResult is derived from ActionResult. ...

August 3, 2024 · 5 min · 1040 words · PrashantUnity