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

MVC interview — Set 3

1. Explain Model, View, and Controller in Brief Model: Represents the data and the business logic of the application. It interacts with the database, retrieves, and stores information. View: Responsible for displaying the data provided by the model. It represents the user interface of the application. Controller: Handles user input and interaction. It processes incoming requests, performs operations on the model, and returns the appropriate view. 2. What are the Different Return Types Used by the Controller Action Method in MVC? ViewResult: Returns a view. PartialViewResult: Returns a partial view. JsonResult: Returns JSON data. RedirectResult: Redirects to a different URL. RedirectToRouteResult: Redirects to a specific route. ContentResult: Returns raw content (string). FileResult: Returns a file download. EmptyResult: Represents no result (no response). 3. Name the Assembly in which the MVC Framework is Typically Defined The MVC framework is typically defined in the System.Web.Mvc assembly. 4. Explain the MVC Application Life Cycle Application Start: The application starts, and configuration settings are loaded. Routing: Incoming requests are matched against defined routes to determine the controller and action. Controller Initialization: The controller that matches the route is instantiated. Action Execution: The controller action method is executed. Result Execution: The result of the action (usually a view) is rendered. Response: The rendered HTML or other output is sent back to the client. 5. What are the Various Steps to Create the Request Object? Filling Route Data: Matches the URL with the routes defined in RouteConfig.cs. Request Context Creation: Forms a request context using the matched route data. Controller Creation: Instantiates the controller using the request context. 6. Explain Some Benefits of Using MVC Separation of Concerns: Different aspects of the application (input logic, business logic, and UI) are separated into different components. Testability: Each component can be tested independently, improving testability. Scalability: Applications are easier to scale due to the modular nature. Flexibility: MVC architecture makes it easier to implement new technologies or patterns. 7. Explain in Brief the Role of Different MVC Components Model: Manages the application data and enforces business rules. View: Displays data from the model and sends user input to the controller. Controller: Handles user input, updates the model, and selects the view to display. 8. How Will You Maintain the Sessions in MVC? Sessions in MVC can be maintained using: Session object: Stores data using key-value pairs. Cookies: Store session data on the client side. Query strings or hidden fields. 9. What Do You Mean by Partial View of MVC? A partial view is a reusable component that renders a portion of a view. It does not have a complete HTML structure (e.g., no <html> or <body> tags) and is used to encapsulate reusable content. 10. Explain in Brief the Difference Between Adding Routes in a WebForm Application & an MVC Application? WebForm Application: Routes are defined using RouteTable in the Global.asax.cs file. MVC Application: Routes are typically defined in the RouteConfig.cs file within the App_Start folder, using the RouteCollection.MapRoute() method. 11. How Will You Define the 3 Logical Layers of MVC? Presentation Layer: Includes the views that are responsible for the UI. Business Logic Layer: Includes controllers that handle user input and business logic. Data Access Layer: Includes models that interact with the database. 12. What is the Use of ActionFilters in MVC? Action filters are used to implement logic that should be executed before or after an action method runs. Examples include authentication checks, logging, or error handling. 13. How to Execute Any MVC Project? Explain its Steps. Step 1: Open the MVC project in Visual Studio. Step 2: Set the desired project as the startup project. Step 3: Build the project using Ctrl + Shift + B. Step 4: Run the project by pressing F5 (debug mode) or Ctrl + F5 (without debugging). 14. What is the Concept of Routing in MVC? Routing is a pattern-matching system that maps incoming requests to specific controller actions. It uses route templates defined in the application to determine how URLs are processed. 15. What are the 3 Important Segments for Routing? Controller: Specifies which controller to use. Action: Specifies which action method to invoke. Parameters: Any additional values required by the action method. 16. What are the Different Properties of MVC Routes? Name: The name of the route. URL Pattern: The URL format associated with the route. Defaults: Default values for segments that are optional. Constraints: Restrict the values that segments can accept. 17. How is the Routing Carried Out in MVC? When a request is received, the routing engine matches the URL against defined routes. If a match is found, it routes the request to the corresponding controller and action method. 18. How Will You Navigate from One View to Another View in MVC? Explain with a Hyperlink Example. You can use the Html.ActionLink helper to navigate between views. 1 @Html.ActionLink("Go to About Page", "About", "Home") This creates a hyperlink that navigates to the About action of the Home controller. 19. Explain the 3 Concepts in One Line; TempData, View, and ViewBag? TempData: Temporary data storage, persists across requests. View: The user interface component that displays data. ViewBag: Dynamic object for passing data from controller to view within a single request. 20. Mention & Explain the Different Approaches You Will Use to Implement Ajax in MVC? Using jQuery: Send AJAX requests with jQuery’s $.ajax() method. Using AJAX Helpers: Utilize built-in MVC AJAX helper methods like Ajax.BeginForm(). Using Fetch API: Use the modern JavaScript Fetch API for making AJAX requests. 21. How Will You Differentiate Between ActionResult and ViewResult? ActionResult: A base class for all action results, allows returning different types of results (e.g., ViewResult, JsonResult). ViewResult: A derived class of ActionResult that specifically returns a view. 22. What is Spring MVC? Spring MVC is a Java-based framework used to build web applications. It follows the MVC design pattern and is part of the larger Spring Framework ecosystem. 23. Explain Briefly What You Understand by Separation of Concern. Separation of Concern means dividing an application into distinct sections, each handling a specific aspect of functionality, reducing interdependencies and making it easier to manage, develop, and test. 24. What is TempData in MVC? TempData is used to store temporary data that needs to be available across multiple requests, such as data used during a redirect. 25. Define Output Caching in MVC. Output caching stores the content generated by the controller action, so subsequent requests for the same content can be served quickly from the cache without re-processing. 26. Why are Minification and Bundling Introduced in MVC? Minification reduces the size of JavaScript and CSS files by removing unnecessary characters. Bundling combines multiple files into one. Both improve performance by reducing the number and size of requests. 27. Describe ASP.NET MVC. ASP.NET MVC is a framework for building scalable, standards-based web applications using the MVC design pattern, focusing on separation of concerns and providing a testable architecture. 28. Which Class Will You Use for Sending the Result Back in JSON Format in MVC? The JsonResult class is used to send a JSON-formatted response back to the client. 29. Make a Differentiation Between View and Partial View? View: Represents a complete HTML page. Includes layout and full HTML structure. Partial View: Represents a segment of the page. Used for reusable components and does not include layout. 30. Define the Concept of Filters in MVC? Filters allow executing code before or after specific stages in the request processing pipeline, such as authorization checks, error handling, or logging. 31. **Mention the Significance of NonAction Attribute?** ...

August 3, 2024 · 9 min · 1893 words · PrashantUnity
Download Logo

MVC interview — Set 4

General MVC Concepts What is Model-View-Controller? Model-View-Controller (MVC) is a software architectural pattern that separates an application into three main logical components: the Model, the View, and the Controller. Each of these components is responsible for handling different aspects of the application. What does Model-View-Controller represent in an MVC application? Model: Represents the data and business logic. It directly manages the data, logic, and rules of the application. View: Represents the user interface. It displays the data from the model to the user and sends user commands to the controller. Controller: Handles user input, manipulates the model, and updates the view as needed. It acts as an intermediary between the model and the view. Name the Assembly to Define MVC ...

August 3, 2024 · 9 min · 1878 words · PrashantUnity
Download Logo

MVC interview — Set 5

ASP.NET MVC Overview What is ASP.NET MVC? ASP.NET MVC is a framework for building web applications using the Model-View-Controller (MVC) architectural pattern. It allows developers to create scalable, testable, and maintainable web applications. ASP.NET MVC provides a clear separation of concerns between the presentation layer (views), the business logic (controllers), and the data model (models). What are the Three Main Components of an ASP.NET MVC Application? Model: Represents the application’s data and the business rules that govern access to and updates of this data. Models are typically used to retrieve data from the database. View: Responsible for displaying the data to the user. It represents the UI of the application. Controller: Handles user input and interaction. It reads data from the view, controls user input, and sends input data to the model. Explain about ASP.NET MVC 5. ...

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