TECHNICAL BLOG

Why to use repository pattern in c#

The Repository Pattern is a widely used design pattern in C# and other object-oriented programming languages. It provides a way to separate the data access logic from the business logic of an application. Here are several reasons why you might choose to use the Repository Pattern in C#:

1.Separation of Concerns

  • Business Logic vs. Data Access Logic: The Repository Pattern allows you to separate business logic from data access logic. This separation makes your code cleaner and more maintainable because each layer has a single responsibility.

2.Testability

  • Mocking and Unit Testing: By using the Repository Pattern, you can create interfaces for your repositories, which makes it easier to mock the data layer during unit testing. This is crucial for writing effective unit tests, as you can isolate the business logic without relying on a database or external data sources.

3.Abstraction

  • Hiding Complex Data Access: The Repository Pattern abstracts the data access layer, providing a clean API for the rest of the application to use. This hides the details of the database queries or the data source from the business logic, making it easier to change the underlying data source if needed.

4.Centralized Data Access Logic

  • Reusability: All data access logic is centralized in the repository classes. This centralization means that data access code isn't scattered throughout the application, leading to more reusable and maintainable code.

5.Decoupling from ORM

  • Change ORM or Data Source: By using repositories, your application is decoupled from the specific ORM (e.g., Entity Framework, Dapper) or data source (e.g., SQL Server, NoSQL). If you decide to switch to a different ORM or database, you only need to modify the repository implementation, leaving the rest of the application unchanged.

6.DRY Principle

  • Avoid Repetition: The Repository Pattern helps you adhere to the DRY (Don't Repeat Yourself) principle. Common data access code, such as queries or transformations, can be centralized in repository methods, preventing code duplication.

7.Single Responsibility Principle

  • Clear Separation of Responsibilities: Repositories adhere to the Single Responsibility Principle by handling only data access logic. They act as intermediaries between the data source and the business logic, which manages only the business rules.

8.Easier Maintenance

  • Simplified Code Updates: When business rules change, the business logic layer might need to be updated, but the data access code remains untouched. Similarly, if the database schema changes, only the repository layer might need updating, leaving business logic unaffected.

9.Standardized Data Access

  • Consistent API for Data Access: By using repositories, you provide a standardized way of accessing data. This consistency makes it easier for developers to work on different parts of the application without needing to understand the specifics of the data access for each entity.

10. Support for Multiple Data Sources

  • Aggregating Data from Different Sources: A repository can aggregate data from multiple sources (e.g., databases, APIs, files) and present it in a unified way to the business logic. This approach makes it easier to work with complex data scenarios.

Example Use Case

Imagine you have an application that initially uses SQL Server for data storage but later needs to support another database like MySQL. If your data access logic is spread across the application, this change will be very costly. However, if you've implemented a Repository Pattern, only the repository layer needs to be updated to support MySQL, and the rest of your application remains unaffected.

Summary

The Repository Pattern in C# is beneficial for:

  • Promoting clean code architecture.
  • Improving testability and maintainability.
  • Providing abstraction and flexibility.
  • Facilitating easier code updates and adherence to SOLID principles.

By implementing this pattern, you create a more robust and flexible application that is easier to manage and scale over time.


a. Explore how to integrate the Unit of Work pattern with the Repository Pattern for more complex data operations.
b. Implement a generic repository to handle common CRUD operations across multiple entities.

Using the Repository Pattern in ASP.NET MVC 4.8

Using the Repository Pattern in ASP.NET MVC 4.8 allows for a more structured, testable, and maintainable codebase by abstracting data access logic. Below is a step-by-step guide on how to implement the Repository Pattern in an MVC 4.8 application using a User entity as an example.

Steps to Implement the Repository Pattern in MVC 4.8
  • Create the Models: Define the User entity.
  • Create the Repository Interface: Define an interface for the repository with the methods you need (e.g., GetUserById, AddUser).
  • Implement the Repository: Create a concrete class that implements the repository interface.
  • Create the Service Layer: Optionally, create a service layer to abstract the repository logic.
  • Use Dependency Injection: Since native dependency injection isn't available in MVC 4, use a third-party library like Unity or Ninject, or manually inject dependencies.
  • Use the Repository in the Controller: Inject the repository/service into your controller and use it to interact with the data.

1. Create the Models Models/User.cs:
   
     using System.ComponentModel.DataAnnotations;
     namespace YourNamespace.Models
     {
     public class User
     {
     public int Id { get; set; }
     [Required]
     public string Name { get; set; }
     [Required]
     [EmailAddress]
     public string Email { get; set; }
     // Additional properties
     }
     }
    
2. Create the Repository Interface Repositories/IUserRepository.cs:

      using System.Collections.Generic;
      using YourNamespace.Models;
      namespace YourNamespace.Repositories
      {
      public interface IUserRepository
      {
      User GetUserById(int id);
      IEnumerable
     GetAllUsers();
     void AddUser(User user);
     void UpdateUser(User user);
     void DeleteUser(int id);
     }
     }
     
3. Implement the Repository Repositories/UserRepository.cs:

     using System.Collections.Generic;
     using System.Linq;
     using YourNamespace.Models;

     namespace YourNamespace.Repositories
     {
     public class UserRepository : IUserRepository
     {
     private readonly ApplicationDbContext _context;

     public UserRepository(ApplicationDbContext context)
     {
     _context = context;
     }
     public User GetUserById(int id)
     {
     return _context.Users.Find(id);
     }
     public IEnumerable
     GetAllUsers()
     {
     return _context.Users.ToList();
     }
     public void AddUser(User user)
     {
     _context.Users.Add(user);
     _context.SaveChanges();
     }
     public void UpdateUser(User user)
     {
     _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
     _context.SaveChanges();
     }
     public void DeleteUser(int id)
     {
     var user = _context.Users.Find(id);
     if (user != null)
     {
     _context.Users.Remove(user);
     _context.SaveChanges();
     }
     }
     }
     }   
                        
4. (Optional) Create the Service Layer To further abstract the repository, you can create a service layer.

     Services/IUserService.cs:    
    
     using System.Collections.Generic;
     using YourNamespace.Models;

     namespace YourNamespace.Services
     {
     public interface IUserService
     {
     User GetUserById(int id);
     IEnumerable
     GetAllUsers();
     void AddUser(User user);
     void UpdateUser(User user);
     void DeleteUser(int id);
     }
     }
     Services/UserService.cs:     
     
     using System.Collections.Generic;
     using YourNamespace.Models;
     using YourNamespace.Repositories;

     namespace YourNamespace.Services
     {
     public class UserService : IUserService
     {
     private readonly IUserRepository _userRepository;

     public UserService(IUserRepository userRepository)
     {
     _userRepository = userRepository;
     }
     public User GetUserById(int id)
     {
     return _userRepository.GetUserById(id);
     }
     public IEnumerable
     GetAllUsers()
     {
     return _userRepository.GetAllUsers();
     }
     public void AddUser(User user)
     {
     _userRepository.AddUser(user);
     }
     public void UpdateUser(User user)
     {
     _userRepository.UpdateUser(user);
     }
     public void DeleteUser(int id)
     {
     _userRepository.DeleteUser(id);
     }
     }
     }   
5. Set Up Dependency Injection ASP.NET MVC 4 does not have built-in dependency injection, so you need to use a third-party DI container like Unity or Ninject. Here’s how you can set up Unity.
Step a: Install Unity via NuGet

      bash     
      Install-Package Unity.Mvc4
      
Step b: Configure Unity in App_Start/UnityConfig.cs

     using Microsoft.Practices.Unity;
     using System.Web.Mvc;
     using Unity.Mvc4;
     using YourNamespace.Repositories;
     using YourNamespace.Services;

     namespace YourNamespace
     {
     public static class UnityConfig
     {
     public static void RegisterComponents()
     {
     var container = new UnityContainer();

     container.RegisterType< IUserRepository, UserRepository> ();
     container.RegisterType< IUserService, UserService> ();
     DependencyResolver.SetResolver(new UnityDependencyResolver(container));
     }
     }
     }
     
Step c: Call RegisterComponents() in Global.asax

     protected void Application_Start()
     {
     UnityConfig.RegisterComponents();
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     }
     
6. Use the Repository in the Controller Now, you can inject the IUserService or IUserRepository directly into your controllers.

     Controllers/UserController.cs:   
    
     using System.Web.Mvc;
     using YourNamespace.Models;
     using YourNamespace.Services;

     namespace YourNamespace.Controllers
     {
     public class UserController : Controller
     {
     private readonly IUserService _userService;

     public UserController(IUserService userService)
     {
     _userService = userService;
     }

     public ActionResult Index()
     {
     var users = _userService.GetAllUsers();
     return View(users);
     }

     public ActionResult Details(int id)
     {
     var user = _userService.GetUserById(id);
     if (user == null)
     {
     return HttpNotFound();
     }
     return View(user);
      }

      public ActionResult Create()
      {
      return View();
      }

      [HttpPost]
      public ActionResult Create(User user)
      {
      if (ModelState.IsValid)
      {
      _userService.AddUser(user);
      return RedirectToAction("Index");
      }
      return View(user);
      }

      public ActionResult Edit(int id)
      {
      var user = _userService.GetUserById(id);
      if (user == null)
      {
      return HttpNotFound();
      }
      return View(user);
      }

      [HttpPost]
      public ActionResult Edit(User user)
      {
      if (ModelState.IsValid)
      {
      _userService.UpdateUser(user);
      return RedirectToAction("Index");
      }
      return View(user);
      }

      public ActionResult Delete(int id)
      {
      var user = _userService.GetUserById(id);
      if (user == null)
      {
      return HttpNotFound();
      }
      return View(user);
      }

      [HttpPost, ActionName("Delete")]
      public ActionResult DeleteConfirmed(int id)
      {
      _userService.DeleteUser(id);
      return RedirectToAction("Index");
      }
      }
      }

Unit of Work pattern

The Unit of Work pattern is commonly used in conjunction with the Repository pattern to manage transactions and maintain consistency in your database operations. The Unit of Work pattern ensures that multiple operations can be treated as a single transaction, allowing for commit or rollback operations if any part of the transaction fails.

Why Use Unit of Work with Repository Pattern?
Consistency: Ensures that all operations within a transaction either complete successfully or none of them do.
Decoupling: Separates the logic of business transactions from the persistence layer.
Efficiency: Manages changes across multiple repositories, preventing unnecessary database calls.

Summary

This Article demonstrates how to implement the Repository Pattern in an ASP.NET MVC 4.8 application, including how to set up the repository, optionally use a service layer, and configure dependency injection using Unity. This structure will help in creating a more maintainable, testable, and scalable MVC application.Using the Repository Pattern in ASP.NET MVC 4.8 allows for a more structured, testable, and maintainable codebase by abstracting data access logic.


Why Microsoft Visual studio code when we have Microsoft Visual Studio?

I was quite surprised to see that there is something Visual studio Code Microsoft has released because I have worked with Visual studio since 1997 which I believe is one of the best IDE and of Couse a complete IDE in market. Why Visual studio code when we Microsoft has “Visual Studio” already in place, On the very first Instant I thought it might be light weight Visual studio. “Visual Studio” and “Visual Studio Code” are two different things. Visual Studio is an integrated development environment (IDE) and Visual Studio Code is light weight IDE with some small features of visual studio, or we can say Visual Studio Code is a streamlined code editor with support for development operations like debugging, task running, and version control for multiple languages and all operating systems including Linux What is Visual Studio? Visual Studio was first released in 1997 by Microsoft. It's an integrated development environment (IDE) for developing, editing, and debugging websites, web, and mobile applications as well as cloud services. I believe any damn application Visual Studio comes with built-in support for C#, VB.NET and .NET. It also supports other programming languages like C, C++, Python, F#, web languages (HTML, CSS, JavaScript, TypeScript, React, Nodejs.), and a lot more. Visual Studio runs on Windows and Mac. It has 3 editions

Community
Professional
Enterprise

The community version is free, while the professional and enterprise are not. It needs good bit of storage space locally in your system ...yah, you still can customize it by choosing only required components to reduce installation time and save local storage space.

What is Visual Studio Code?

Visual Studio Code (also called VS Code) is like the light version of Visual Studio. It is an open-source and lightweight text editor available on Windows, Mac, and Linux. VS Code comes with built-in support for JavaScript, TypeScript and Node JS, but you can use it to code in any language you want. All you need to do is download the relevant extensions..
Some of the extensions are made by Microsoft, but a lot of others are third-party extensions. You can see extensions popping up on left side panel Unlike Visual Studio, you don’t need much space to download VS Code. You might not need more than 250 MB of disk space to download it. Since it supports JavaScript, TypeScript, and Node JS by default, you get a debugger and intelligence, too. But to get IntelliSense, a compiler, and debuggers for other languages, you have to download relevant extensions. Now you know that Visual Studio is an IDE and Visual Studio Code is a text editor. So let's summarize their main differences next.

What is the Difference between "Visual Studio" and "Visual Studio Code"?

BasisVisual StudioVisual Studio Code
TypeVisual Studio is a full-fledged IDEVS Code is a text editor witd some basic capability of debugging, connecting to services
PlatformVisual Studio runs on Windows and MacVS Code runs on Windows, Mac, and Linux
SizeVisual Studio is relatively large. VS Code is a small download less than 200 MB and has a disk footprint of less than 500 MB
SupportVisual Studio has built in support for C# and .NET, alongside several common languages VS Code supports JavaScript, Typescript, and Node JS out of the box. It also supports other programming languages – as long as there’s an extension(s) for that
ExtensionsVisual Studio does not have as many extensions as VS CodeVS Code has numerous professionally and curated extensions for various purposes

What is Not supported by VS Code?

VS Code does not support application virtualization solutions such as Microsoft App-V or MSIX for Windows, or third-party app virtualization technologies. Running VS Code in a virtual machine environment requires a full operating system.
VS Code does not support multiple simultaneous users using the software on the same machine, including shared virtual desktop infrastructure machines or a pooled Windows/Linux Virtual Desktop host pool.
Running the full VS Code in Windows/Linux containers is not supported but running with the Dev Containers extension is supported. When using the Dev Containers extension, the VS Code server is running in the container while the VS Code client is on the desktop

Which should you Choose between "Visual Studio” and “Visual Studio Code"?

There has been a long-running debate about which is better and which to choose between Visual Studio and Visual Studio Code. Well, it depends on what you are doing..
If you’re developing exclusively with a language supported by Visual Studio such as C#, C, C++, Python, and others, Visual Studio or other relevant IDEs are likely the best option for you..
But even if you’re developing in those languages but you require a React, Vue, or Angular frontend, VS code might be the best option for you..
If you’re working in a team, they might provide you with the enterprise version of Visual Studio, or any other IDE that correlates with the language you are working with. For example, PyCharm for Python and IntelliJ Idea for Java..
If you’re using Linux, you have to choose Visual Studio Code or some other IDE apart from Visual Studio. That’s because Visual Studio does not run on Linux..
If you’re the kind of person that likes to customize your editor to your taste, just go for VS Code because it's highly customizable. You also should probably choose VS Code if you are mixing technologies.

Conclusion

This article showed you the differences between Visual Studio and VS Codei hope this will help you in choosing right IDE while developing software Applications


Service Bus queues and storage queues

Two Azure services include message queues: Service Bus and Azure Storage. As a general guide, storage queues are simpler to use, but they're less sophisticated and less flexible than Service Bus queues. The key advantages of Service Bus queues include:

Supports larger messages sizes of 256 KB (standard tier) or 100 MB (premium tier) per message versus 64 KB for Azure Storage queue messages.
Supports both at-most-once and at-least-once delivery. Choose between a very small chance that a message is lost or a very small chance it's handled twice.
Guarantees first-in, first-out (FIFO) order. Messages are handled in the same order they're added. Although FIFO is the normal operation of a queue, the default FIFO pattern is altered if the organization sets up sequenced or scheduled messages or during interruptions like a system crash.
Can group multiple messages in one transaction. If one message in the transaction fails to be delivered, all messages in the transaction aren't delivered.
Supports role-based security.
Doesn't require destination components to continuously poll the queue.

Advantages of storage queues:

Supports unlimited queue size (versus 80-GB limit for Service Bus queues)
Maintains a log of all messages

How to choose a communications technology

You've seen the different concepts, and the implementations Azure provides. Next, consider what your decision process should look like for each of your communications.


Considerations

As you choose a method for sending and receiving messages, consider the following questions:

Is the communication an event? If so, consider using Event Grid or Event Hubs.
Should a single message be delivered to more than one destination? If so, use a Service Bus topic. Otherwise, use a Service Bus queue.

Queues: Service Bus vs. storage

If you decide that you need a queue, narrow down your choice further. Choose a Service Bus queue if:

You need an at-most-once delivery guarantee.
You need a FIFO guarantee (if no other settings pre-empt the default FIFO order).
You need to group messages into transactions.
You want to receive messages without polling the queue
You need to provide role-based access to the queues.
You need to handle messages larger than 64 KB but smaller than 256 KB for the standard tier or 100 MB for the premium tier.
Your queue size won't grow larger than 80 GB.
You'd like to be able to publish and consume batches of messages.

Choose a storage queue if:

You need a simple queue with no particular extra requirements.
You need an audit trail of all messages that pass through the queue.
You expect the queue to exceed 80 GB in size.
You want to track progress for processing a message inside the queue.

Conclusion

Although the components of a distributed application can communicate directly, you often can increase that communication's reliability by using an intermediate communication platform like Azure Event Hubs or Azure Event Grid.
Event Hubs and Event Grid are designed for events, which notify recipients only of an event and don't contain the raw data associated with that event. Azure Event Hubs is designed for high-flow, analytics types of events.
Azure Service Bus and storage queues are for messages, which you can use for binding the core pieces of any application workflow.
If your requirements are simple, if you want to send each message to only one destination, or if you want to write code as quickly as possible, a storage queue might be the best option. Otherwise, Service Bus queues provide many more options and flexibility. If you want to send messages to multiple subscribers, use a Service Bus topic.


Azure Logic Apps Explained

Azure Logic Apps is a cloud-based service that enables you to automate workflows and integrate apps, data, and services across different systems. It provides a visual interface to design workflows, known as "logic apps," which can be triggered by various events and can integrate with a wide range of systems using pre-built connectors.

Key Concepts of Azure Logic Apps:

Triggers: A trigger starts a logic app. It could be a time-based trigger (e.g., every hour), an event (e.g., when a file is uploaded), or an action in another system (e.g., receiving an email).
Actions: Actions are the steps that the logic app performs after it is triggered. These can include calling APIs, manipulating data, sending emails, etc.
Connectors: Connectors allow logic apps to interact with various services, such as Office 365, Salesforce, Azure services, databases, etc.

Example Scenario: Automating Invoice Processing

Let’s say you want to automate the process of receiving invoices via email, saving them to a SharePoint document library, and then notifying the accounting team.

Steps to Implement This Workflow Using Azure Logic Apps:

  1. Create the Logic App In the Azure portal, create a new Logic App by navigating to Create a resource > Integration > Logic App.

  2. Give it a name, select a resource group, and click Create. Design the Workflow

    • Step 1: Add a Trigger Trigger: Choose the trigger to start your logic app. In this case, you might choose When a new email arrives (V2) from the Office 365 Outlook connector. Condition: Set conditions to filter emails. For instance, you might only want to trigger the workflow when the subject contains "Invoice."

    • Step 2: Extract Invoice Attachment Action: Use the Get attachments action to retrieve any files attached to the email.

    • Step 3: Save the Attachment to SharePoint Action: Add a Create file action from the SharePoint connector. Configure it to save the attachment to a specific document library in SharePoint. Set the file name and content based on the email attachment.

    • Step 4: Notify the Accounting Team Action: Use the Send an email (V2) action from the Office 365 Outlook connector to send a notification email to the accounting team. The email can include details like the sender’s email address, the subject of the email, and a link to the saved file in SharePoint.

  3. Test and Monitor the Logic App Test: Send an email with an invoice attachment to see if the logic app correctly processes it. Monitor: Azure Logic Apps provides built-in monitoring tools. You can see the run history and inspect any errors that occurred during the execution.

  4. Enhance the Workflow Error Handling: Add error handling actions like Scope and Terminate to manage what happens if a step fails (e.g., retry, log the error).
    Data Transformation: Use data operations like Compose or Parse JSON to transform or extract specific information from the email content or attachment.
    Approval Workflow: You can add an approval step where the accounting team reviews the invoice before it is saved to SharePoint.

    Final Workflow Overview

    Trigger: The workflow starts when an email with the subject "Invoice" is received.
    Get Attachments: The attachment(s) from the email are retrieved.
    Save to SharePoint: The attachment is saved to a designated SharePoint document library.
    Notify Team: An email notification is sent to the accounting team, including details of the invoice.

    Benefits of Using Azure Logic Apps:

    No-Code/Low-Code Solution: Allows non-developers to create complex workflows using a visual designer.
    Scalability: Automatically scales with demand, processing multiple workflows concurrently.
    Integration: Easily integrates with hundreds of services and on-premises systems.
    Cost-Effective: Pay only for what you use, with a straightforward pricing model based on the number of actions executed.

Summary

Azure Logic Apps is a powerful tool for automating business processes and integrating systems. By creating a simple workflow, you can automate tasks such as invoice processing, saving time and reducing the potential for human error. With its extensive library of connectors and easy-to-use interface, Azure Logic Apps is suitable for both technical and non-technical users.

The perfect choice for Entrepreneur, business advisor and corporates.