Dependency Inversion Principle (DIP) in C#

In my previous articles I wrote about Solid Principles in C#.

In this article, I am going to show you when and how to use the Dependency Inversion Principle (DIP) in C# with an example project. You can find the repository on GitHub.

The master branch shows the initial code used in the example.  There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:

What is the Dependency Inversion Principle (DIP) in C#?

The Dependency Inversion Principle (DIP) is the last, in alphabetical order, of the SOLID design principles. We can always reuse the definition from Wikipedia.

High-level modules should not import anything from low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

Let’s try to summarize these two definitions:

  • Instead of high-level modules relying directly on low-level modules, both should communicate through abstract interfaces. This promotes flexibility and allows for easier substitution of components.
  • Abstractions should not be tightly coupled to specific implementations; instead, the concrete details should adhere to the abstractions. This allows you to change or extend implementations without affecting the overall structure of your code.

Abstractions describe what:

  • Send a message;
  • Store a record;

Details specify how to do:

  • Send a push notification to a device;
  • Deserialize an object and store in a database;

In this example we expose implementation details and making the interface much less reusable. The interface should not know the details of the database, in this case mysql.

public interface IOrderDataAccess
{
    MySqlDataReader GetOrders(MySqlParameterCollection params);
}

This example hide the details above and make the interface reusable.

public interface IOrderDataAccess
{
    List<Order> GetOrders(Dictionary<string, string> params);
}

Continue reading

Interface Segregation Principle (ISP) in C#

In my previous articles I wrote about Solid Principles in C#.

In this article, I am going to show you when and how to use the Interface Segregation Principle in C# with an example project. You can find the repository on GitHub.

The master branch shows the initial code used in the example.  There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:

What is the Interface Segregation Principle (ISP) in C#?

The Interface Segregation Principle is the fourth of the SOLID design principles. Let us take a look at Robert C. Martin’s definition and try to analyse it.

Clients should not be forced to depend on methods that they do not use.

What’s a Client?

It’s the calling code. It’s the code that is interacting with an instance of the interface.

What does Interface mean in C# for the Interface Segregation Principle (ISP)?

In C# we have two kinds of interfaces described by the ISP.

A type’s interface is whatever can be accessed by a client.

Ok nice description but in the end what do we have to do?

Prefer small and related interfaces to fat ones.

Continue reading

Liskov Substitution Principle (LSP) in C#

In my previous articles I wrote about Solid Principles in C#.

In this article, I am going to show you when and how to use the Liskov Substitution Principle in C# with an example project. You can find the repository on GitHub.

The master branch shows the initial code used in the example.  There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:

What is the Liskov Substitution Principle (LSP) in C#?

The Liskov Substitution Principle is one of the SOLID design principles. We can always reuse the definition from Wikipedia but this time will be hard to fully understand…

Let Φ(x) be a property provable about objects x of type T. Then Φ(y) should be true for objects y of type S where S is a subtype of T.

We can transform this sentence in:

If S is a subtype of T, then objects of type T should be replaced with the objects of type S.

Which simply stated means that:

Subtypes must be substitutable for their base types.

Continue reading

Open Closed Principle (OCP) in C#

In my previous articles I wrote about Solid Principles in C# and the Single Responsibility Principle.

In this article, I am going to show you when and how to use the Open Closed Principle in C# with an example project. You can find the repository on GitHub.

The master branch shows the initial code used in the example.  There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:

What is the Open Closed Principle (OCP) in C#?

The Open Closed Principle is one of the SOLID design principles. We can always reuse the definition from Wikipedia.

The Open Closed Principle states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

So these software entities should be:

  • Open For Extension This means that the behavior of the module can be extended, for example we could add fields or new elements in the functions with a fixed behavior,
  • Closed for Modification The source code of such a module is inviolate. No one is allowed to make source code changes to it.

Why should you use the Open Closed Principle (OCP)?

  • Application robust. Don’t break existing code, prefer implementing new features in new classes, follow the SRP, no need to change tested class and less bug.
  • Flexible. Working with interfaces, it’s easy to accommodate new requirements and this reduces the cost of a business change requirement.
  • Better testability. Easy to test and less error prone.

Continue reading

Single Responsibility Principle (SRP) in C#

In my previous article I wrote about what they are and why to use Solid Principles in C#.

In this article, I am going to show you when and how to use the Single Responsibility Principle in C# with an example project. You can find the repository on GitHub.

The master branch shows the initial code used in the example.  There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:

What is the Single Responsibility Principle (SRP) in C#?

The Single Responsibility Principle is one of the SOLID design principles. We can reuse the definition from Wikipedia. The single-responsibility principle (SRP) is a computer-programming principle that states that every module, class or function in a computer program should have responsibility over a single part of that program’s functionality, and it should encapsulate that part. Robert C. Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to be changed.

To better understand it, we need to divide the definition into two parts:

  • Single Responsibility A class/method/function should have only a single responsibility.
  • A reason to change A class or method should have only one reason to change. About the “reason” Martin clarified that this principle is about people/role. It is people who request changes.

Why should you use the Single Responsibility Principle (SRP)?

  • Reduction in complexity of a code. A code is based on its responsibility and functionality. So, it reduces the code complexity.
  • Increased readability, extensibility and maintenance. As each method has a single functionality so it is easy to read and maintain.
  • Reusability and reduced error. As code separates based functionality so you can reuse the code somewhere else in an application.
  • Reduced coupling. It reduced the dependency code. A method’s code doesn’t depend on other methods.
  • Better testability. In the maintenance, when a functionality changes then we don’t need to test the entire model.

Continue reading

How to solve Safari PDF first page problem for Apple iPhone and iPad?

Render a PDF file using your iPhone, it may seem like an easy operation but I had a bit of trouble doing it via Safari for iPhone and iPad.

Unfortunately only the first page of the PDF was shown, the rest was blocked. 🤪

What is the recommended way to render PDF in HTML?

  • iFrame ❌
  • Object ❌
  • Embed ❌
  • PDF.JS library
  • Google PDF viewer ❌

I tried all online solutions and PDF plugins but always same result:

  • Desktop: Chrome, Opera, Firefox working ✅
  • iOS: Safari not working ❌

So how to solve Safari PDF first page problem for Apple iPhone and iPad?

Using Javascript you can Decode base64 string, create a blob object with content-type “application/pdf” and navigates the browser to pdf.

Thanks for reading! 🌟

Solid Principles in C#

It’s time to talk about a topic that every developer should know to work better regardless of the language or framework used: The S.O.L.I.D principles.

What are the S.O.L.I.D. principles?

The S.O.L.I.D. design principles are a collection of best practices for object-oriented design. The term S.O.L.I.D. comes from the initial letter of each of the five principles that were collected in the book Agile Principles, Patterns, and Practices in C# by Robert C. Martin, or Uncle Bob to his friends.

It was written in 2000, 20 years ago since this article was published. But these Principles are still popular and are still being used widely in the world of OOP Paradigm. You can find the original pdf here https://web.archive.org/web/20150906155800/http://www.objectmentor.com/resources/articles/Principles_and_Patterns.pdf

Yes, you’re not reading it wrongly nor I have a typo. It was written in 2000, 20 years ago since this article was published. But these Principles are still quite popular and are still being used widely in the world of OOP Paradigm.

Why should you use the S.O.L.I.D. principles?

Short answer: Software Rot or Code Rot or Software Erosion is either a slow deterioration of software quality over time or its decreasing responsiveness, which will eventually lead to software becoming faulty, unusable, and in need of upgrade.

Long answer: Software rot refers to the slow degradation in the performance of computer software. Such software shows diminished responsiveness, lacks updates, may become faulty overtime owing to changes in the operating system it is running on and thus may need upgrading.

These are some signs for identifying Software Rot:

  • Rigidity: Difficult to modify the code. New requirements or small changes leads to rebuild the entire software.
  • Fragility: New modifications introduce bugs and vulnerability in the code.
  • Immobility: Non-portability of the code. if a component/module/function cannot be used in another system, this is considered as immobile.
  • Viscosity: When implementing and testing are difficult to perform and also take a long time to execute.
  • Changing Requirements or Changing Needs: Often changes need to be made quickly and may be made by engineers who are not familiar with the code. We cannot dodge the new requirements but we must somehow find a way to make our designs/project resilient to such changes and protect them from rotting.
  • Dependency Management: We know changes introduce new and unplanned for dependencies, so inappropriate module dependencies and increased coupling between systems make the source code more difficult to manage. In order to prevent the degradation of the dependency architecture, the dependencies between modules in an application must be managed.

What will you achieve by using the S.O.L.I.D. Principles?

  • Code More Maintainable
    • Using the Single Responsibility Principle (SRP) and the Open closed principle (OCP) you will be easier in maintaining your code.
  • Code More Flexible
    • It’s quite easy when you need to add features in your code because all codes are loosely coupled.
  • Code More Understandable
    • When you come back to your code six months later, you still understand what you wrote back then.

So what are you waiting for? Try opening your own old project and start applying the principles. You will only see improvements.

(S) Single Responsibility Principle – SRP

The Single Responsibility Principle (SRP) states that each software module should have one and only one reason to change.

(O) Open closed principle – OCP

The Open closed principle (OCP) states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

(L) Liskov substitution principle – LSP

The Liskov substitution principle – (LSP) states that objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.

(I) Interface segregation principle – ISP

The Interface segregation principle – (ISP) states that no client should be forced to depend on methods it does not use

(D) Dependency inversion principle – DIP

The Dependency inversion principle – (DIP) introduces an abstraction that decouples the high-level and low-level modules from each other.

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟

 

 

Nuget TextCase library for .NET

I have often used and created nuget packages in many companies and never had the desire or time to create/manage my own nuget package that could help other fellow developers.

So i decide to create the TextCase library for .NET, it helps changing the cases of existing texts.

Nuget TextCase library for .NET

There are the cases currently available:

  • UpperCase
  • LowerCase
  • TitleCase
  • CapitaliseCase
  • CapitaliseWordsCase
  • ReverseCase
  • AlternateCase
  • CamelCase
  • PascalCase
  • KebabCase
  • SnackCase
  • HashtagCase

Continue reading

How to localize info.plist in Xcode

As you know with iOS 14 Apple requires consent to access the IDFA (Identifier for Advertisers), you need to display the App Tracking Transparency authorization request for accessing the IDFA. How to implement this change? Just update your Info.plist and add the NSUserTrackingUsageDescription key with a custom message describing your usage. My app supports more languages and the info.plist file is only one… 🤔

How to localize info.plist in Xcode ?

<key>NSUserTrackingUsageDescription</key>
<string>This identifier will be used to deliver personalized ads to you.</string>

I read a lot of articles about automatically localize the info.plist file but i had several problems. The easiest solution was to:

  • Add in the project a new Strings file InfoPlist.strings (case sensitive), I’ve already written it but I want to repeat it otherwise it won’t work. You need to create the InfoPlist.strings file, not Infoplist.strings or infoPlist.strings.
  • Open the InfoPlist.strings file and add your keys and custom descriptions.
"NSUserTrackingUsageDescription" = "My app will use this identifier to provide you with personalized ads.";
  • Select the InfoPlist.strings and use the Localization section in the File Inspector to localize the file. Press the Localize… button to add additional Localizations to your app.
  • Run the simulator in each languages and this will work 👍

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟

 

Reference: About Information Property List Files

How to Take a Screenshot or Record a Video using the iOS Simulator

As an iOS  to show my project or to publish an app on the AppStore I need to take screenshots or to record a video.

The first idea was to use the Simulator and press the button Save Screen when i need, for the video to use QuickTime Player, you can follow this link to understand how to do.

I’ve been using the xcrun command for some time and now I feel comfortable with it. You can automate it by creating a script.

What is xcrum command ?

xcrun is a tool provided by Apple to run any tool inside Xcode from the command line, usually it’s available with the installation of xcode but you can get downloading the Command Line Tools package from the Developer website. The Command Line Tools package is available for download on the Download for Apple Developers page. Log in with your Apple ID, then search and download the Command Line Tools package appropriate for your machine

How to Take a Screenshot with xcrum ?

  1. Run your app in the Simulator.
  2. Launch Terminal.app (in /Applications/Utilities) and run this command:

1
xcrun simctl io booted screenshot screenshot.png

xcrun simctl io booted screenshot screenshot.png

There are several option to use with this command to improve your screenshot:

  • –type
    • Can be “png”, “tiff”, “bmp”, “gif”, “jpeg”. Default is png.
  • –display
    • iOS: supports “internal” or “external”. Default is “internal”
    • tvOS: supports only “external.
    • watchOS: supports only “internal.
  • –mask
    • You may also specify a port by UUID. For non-rectangular displays, handle the mask by policy:
      • ignored: The mask is ignored and the unmasked framebuffer is saved.
      • alpha: The mask is used as premultiplied alpha.
      • black: The mask is rendered black.

How to Record a Video with xcrum ?

  1. Run your app in the Simulator.
  2. Launch Terminal.app (in /Applications/Utilities) and run this command:

1
xcrun simctl io booted recordVideo video.mov

There are several option to use with this command to improve your video:

  • –codec
    • Specifies the codec type: “h264” or “hevc”. Default is “hevc”.
  • –display
    • iOS: supports “internal” or “external”. Default is “internal”
    • tvOS: supports only “external.
    • watchOS: supports only “internal.
  • –mask
    • For non-rectangular displays, handle the mask by policy:
      • ignored: The mask is ignored and the unmasked framebuffer is saved.
      • alpha: Not supported, but retained for compatibility; the mask is rendered black.
      • black: The mask is rendered black.
  • –force
    • Force the output file to be written to, even if the file already exists.

 

If you think your friends/network would find this useful, please share it with them. I’d really appreciate it.

Thanks for reading! 🌟