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
Download Logo

MVC interview — Set 2

1. What is MVC (Model View Controller)? MVC is a design pattern used for developing web applications. It separates the application into three interconnected components: Model: Represents the application’s data and business logic. View: The user interface that displays data from the model to the user. Controller: Handles user input, manipulates the model, and updates the view accordingly. 2. What are the Advantages of MVC? Separation of Concerns: MVC separates the application into three components, making it easier to manage and test. Scalability: The separation allows for scalability since each component can be developed and tested independently. Reusability: Components of the application can be reused, which reduces code duplication. Maintainability: Changes in one part (like the view) do not affect the others, making the application easier to maintain. 3. Explain MVC Application Life Cycle Application Start: Initializes application configurations (e.g., routes, filters). Routing: The routing module maps the URL to a specific controller and action method. Controller Initialization: Instantiates the appropriate controller. Action Execution: The action method is executed, and any data is processed. Result Execution: The result (typically a view) is executed, which generates the HTML output. Response: The generated output is sent back to the client’s browser. 4. List Out Different Return Types of a Controller Action Method ViewResult (returns a view) PartialViewResult (returns a partial view) JsonResult (returns JSON-formatted data) RedirectResult (redirects to another action or URL) RedirectToRouteResult (redirects to a specified route) ContentResult (returns raw string content) FileResult (returns a file download) EmptyResult (returns no content) 5. What are the Filters in MVC? Filters are used to execute code before or after an action method runs. Types of filters: Authorization Filters: Handle authorization logic. Action Filters: Run before and after an action method is called. Result Filters: Run before and after the view result is executed. Exception Filters: Handle exceptions thrown by action methods. 6. What are Action Filters in MVC? Action Filters are a specific type of filter that allow logic to be run before and after an action method execution. Examples include logging, authentication checks, and caching. 7. Explain What is Routing in MVC? What are the Three Segments for Routing Important? Routing is the process of mapping a URL to a controller and action method. The three segments of a typical route are: Controller: Determines which controller to instantiate. Action: Determines which action method of the controller to call. Parameters: Any additional parameters required by the action method. 8. What is Route in MVC? What is Default Route in MVC? A Route is a URL pattern that is mapped to a controller action. The Default Route is typically defined in RouteConfig.cs and looks like this: 1 2 3 4 5 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 9. Difference Between TempData, ViewData, and ViewBag? TempData: Stores data temporarily during a redirect. It uses session storage and can only persist between two requests. ViewData: Stores data in key-value pairs, accessible only for the current request. ViewBag: Similar to ViewData but uses dynamic properties, making it easier to use. It is also request-scoped. 10. What is Partial View in MVC? A partial view is a reusable piece of a user interface that can be rendered inside another view. It is commonly used for components like headers, footers, and widgets. 11. Difference Between View and Partial View? View: A complete page that renders the full layout, including _Layout.cshtml. Partial View: A segment of a page that does not render the full layout. It is intended to be used within other views. 12. What are HTML Helpers in MVC? HTML Helpers are methods that generate HTML markup for use in views. Examples include Html.TextBoxFor(), Html.DropDownListFor(), etc. 13. Explain Attribute-Based Routing in MVC? Attribute-based routing allows routes to be defined directly on controller actions using attributes. It provides fine-grained control over routing. 1 2 [Route("products/details/{id:int}")] public ActionResult Details(int id) { ... } 14. What is TempData in MVC? TempData is used to pass data from one action to another. It stores data temporarily, and it uses the session state to persist data across requests. 15. What is Razor in MVC? Razor is a view engine that provides a streamlined syntax for embedding server-side code into HTML using C#. It uses @ as a marker for code. 16. Differences Between Razor and ASPX View Engine in MVC? Razor View Engine: Uses @ syntax. Cleaner and less verbose. Supports IntelliSense. ASPX View Engine: Uses <%= %> syntax. More verbose. No modern features like Razor. 17. Main Razor Syntax Rules Use @ to transition from HTML to C#. Use @{ ... } for inline C# code blocks. Use @model to specify the type of the model. Use @Html helpers to generate HTML markup. 18. Implement Forms Authentication in MVC Configure forms authentication in web.config. Use the [Authorize] attribute on controllers or actions. Redirect users to a login page if not authenticated. 19. Explain Areas in MVC Areas allow you to partition an MVC application into multiple sections. Each area can have its own controllers, views, and models. They are useful for organizing large applications into smaller modules. 20. Explain the Need of Display Mode in MVC Display modes allow the application to select different views based on the browser or device type. This is useful for creating mobile-optimized views. 21. Explain the Concept of MVC Scaffolding MVC scaffolding is a code generation tool that automatically creates CRUD operations and views for models, speeding up the development process. 22. What is Route Constraints in MVC? Route constraints restrict the type of data that parameters can accept in a route. Example: 1 2 3 4 5 6 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { id = @"\d+" } // id must be numeric ); 23. What is Razor View Engine in MVC? The Razor View Engine is a templating engine that allows embedding C# code within HTML. It uses a .cshtml file extension. 24. What is Output Caching in MVC? Output caching stores the rendered HTML of a page so that subsequent requests can be served from the cache rather than regenerating the page. This improves performance. 25. What is Bundling and Minification in MVC? Bundling combines multiple CSS or JavaScript files into a single file. Minification removes unnecessary characters (like whitespace) from code to reduce file size. Both techniques improve page load time. 26. What is Validation Summary in MVC? The ValidationSummary helper displays a summary of all validation errors on the page. It collects errors from all fields and displays them at the top of the form. 27. What is Database First Approach in MVC using Entity Framework? The Database First approach generates model classes and a DbContext from an existing database schema. It is useful when you have a pre-existing database that you want to use. 28. What are the Folders in MVC Application Solutions? Controllers: Contains controller classes. Models: Contains model classes. Views: Contains view files (.cshtml). wwwroot: Stores static files like images, CSS, and JavaScript. Areas: Contains sub-folders for modular parts of the application. 29. Difference Between MVC and Web Forms MVC: Uses the MVC pattern (Model-View-Controller). Promotes separation of concerns. Does not use ViewState. Web Forms: Follows an event-driven programming model. ...

August 3, 2024 · 9 min · 1864 words · PrashantUnity