...

What We Think

Blog

Keep up with the latest in technological advancements and business strategies, with thought leadership articles contributed by our staff.
TECH

April 25, 2024

Dependency Injection Overview: Using Dependency Injection in ASP.NET Core

In the world of software development, Dependency Injection (DI) stands as a fundamental concept, often hailed as a cornerstone of good design and modular architecture. But, for many developers, especially those newer to the field, the term can evoke confusion or difficult to understand. I hope that the blog will help you understand DI better.

1. Understanding Dependency Injection

At its core, Dependency Injection is a design pattern used to manage dependencies between different components or modules within a software system. It can be understood simply as follows:
  • Modules do not communicate directly with each other, but through an interface. The low-level module will implement the interface, the high-level module will call the low-level module through the interface.
  • For example: To communicate with customer service, we have the ICustomerService interface, the low-level modules are CustomerService. The high-level module CustomerController will only use the ICustomerService interface.
  • Initialization of low-level modules will be performed by DI Container. For example: In the CustomerController, we will not initialize ICustomerService service = new CustomerService (), this will be done by DI Container. The CustomerController will not know anything about the class CustomerService
  • Which Module is attached to which interface will be configured in the class Program.cs

2. The Three Types of Dependency Injection

Dependency Injection can be implemented in three main ways: Constructor Injection, Setter Injection, and Interface Injection.
  • Constructor Injection: In this approach, dependencies are provided through a class's constructor. This ensures that all required dependencies are available when an object is instantiated, promoting immutability and simplifying testing.
  • Setter Injection: Also known as property injection, Setter Injection involves providing dependencies through setter methods. While not as preferred as Constructor Injection due to the potential for objects to be in an invalid state, Setter Injection can be useful for optional dependencies.
  • Interface Injection: This approach is less common and involves providing dependencies through an interface that the client class implements. However, this method can introduce tight coupling between the client class and the injector, making it less flexible compared to Constructor Injection.
Among the three types of Inject, Constructor Injection method is very popular because of its flexibility, ease of building DI libraries...

3. Advantages and disadvantages of Dependency Injection

Advantage

  • Reduce adhesion between modules
  • Code is easy to maintain, easy to replace modules
  • Very easy to test and write Unit Test

Disadvantages

  • The concept of DI is quite difficult to understand new developers will have difficulty learning it
  • Objects are completely initialized from the beginning, which can reduce performance Increases code complexity

4. Using DI in .NET CORE

Use Dependency Injection through these steps:
  1. Use an interface or base class to abstract implementation dependencies.
  2. Register the dependency in the service container. ASP.NET Core allows us to register our application services with the IoC container, in the Program.cs class use IServiceCollection to register application services
  3. Include the service in the constructor of the class in which it is used. The framework will create an instance of the dependency and remove it when it is no longer needed.
Example: The ICustomerService interface defines the SendMessage method
public interface ICustomerService {
    void SendMessage(string message);
}
We have the CustomerAService implement ICustomerService1
public class CustomerAService : ICustomerService {
    public void SendMessage(string message)
    {
        Console.WriteLine($"CustomerAService.SendMessage Message: {message}");
    }
}
The AddScoped method registers the service with scoped lifetime, the lifetime of a singleton request
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ICustomerAService, CustomerAService>();
 
var app = builder.Build();
There are 3 lifecycle levels: addTransient, addScoped, addSingleton.
  • Transient: Instance is initialized each time a service is created
  • Scoped: Instance is initialized per scope. (Scope here is each request sent to the application). In the same scope, the service will be reused.
  • Singleton: The service instance is created uniquely at application launch and is used everywhere
ICustomerService is required and used to call the SendMesasge method
public class CustomerController : PageModel {
    private readonly ICustomerService _customerService;
    public Index2Model(ICustomerService customerService) {
        _customerService = customerService;
    }
    public void OnSendMesasge() {
        _customerService.SendMessage("Send message");
    }
}
By using the DI pattern, the controller will: Not use CustomerAService, only use the ICustomerService interface. That makes it easy to change the Controller's implementation without modifying the Controller.

View More
TECH

April 9, 2024

Top Angular interview questions (part 1)

Interviews allow the interviewer to collect relevant information from the interviewee. This information can include details about qualifications, experiences, skills, and suitability for the position.

In a technical interview for a position related to Angular framework, the candidates need to prepare for the understanding of the framework, it will help them perform well during the interview.

This post will introduce the top 5 common questions about Angular framework.

View More
TECH

April 3, 2024

The Power of Memos

Memo-taking habits recommended for all people.
People who are good at work, such as people who have the ability to take action, people who are good at speaking and writing, people who have planning skills, and people who have good judgment and decision-making skills, have the ability to take notes. They frequently write down in notebooks or diaries things they see or hear, ideas that come into their minds, lessons learned insights and so on. They often review their notes and use them in their work.
The human brain is not a universal device that remembers all events and information. On the contrary, it forgets most things. When you are busy at work, you may break out in a cold sweat and say, "I can't remember what you said to me just now".
A good way to avoid the risk of forgetting is to take memos. A memo is like an external hard disk for the brain. Therefore, you don't have to remember what you have written down.

Here are memo-taking situations and their respective purposes.

1. Meetings and conferences

There are many situations where memos are taken in the company, such as meetings and conferences, where there are many items to be noted, such as what was said and what was decided on the spot.
The memos taken in these situations are sometimes written down in the form of minutes, so the memos taken on the spot are positioned as a record for the purpose of writing them down. People's conversations in meetings unfold faster than the speed at which notes are taken, so speed and technique are required to successfully jot down only the main points.

2. Business negotiations and meetings with clients

Business negotiations and meetings with suppliers and customers are activities outside the company, so handling memos is more important than within the company. If you are inside the company, you can ask the same question again if you bow down, but if you are outside the company, it can become a trust issue for the company if it continues over and over again. Therefore, taking notes is essential, but another effect is that it is also a business technique to show that you are listening carefully to what the other person is saying and that you are taking notes to ensure that there are no mistakes.

3. Training and seminars

Memos are also very useful in training courses, seminars and other opportunities for self-improvement. In this case, the main purpose is to efficiently take home the information necessary for self-improvement, so the notes should be easy to understand when you read them back later and reproducible, so that you can easily remember them.

4. Writing down inspiring ideas

Writing down information that comes in from the outside is not the only role of a memo. It is also very important to take notes on ideas that occur to you in your mind. Ideas come to you suddenly and disappear quickly, but by writing them down, you can remember them later. It also allows you to brush them up further and develop them into a draft plan.

Conclusions

No one has a bad impression when they see the person they are talking to taking copious notes. At the same time, it gives a good impression that they are listening attentively so as not to miss anything you say, and at the same time, it gives you a sense of security that your message will be understood if they are taking this many notes.

Since the obvious act of taking memos out of necessity can make such a good impression on the other person, you should make great use of memos as a consistent communication technique.
When you see someone taking memos seriously, the person you are talking to will naturally become more serious. If that is how you get information of high value, then thank goodness for memos.

※Image source and Reference website:

  • [https://www.pexels.com]
  • [https://navi.dropbox.jp/memo]
  • [https://next.rikunabi.com/journal/20170425_m1/]
View More
TECH

April 2, 2024

Online word lookup skills

As a Japanese interpreter in the IT industry, you will certainly encounter many new words and new knowledge during your interpreting process.

In such situations, we need to learn about new knowledge from that new word, and there are many ways to get answers, including: asking knowledgeable people, searching online, searching in books, etc.

Here, I would like to share about “How to search wording on internet”.

View More
TECH

April 1, 2024

Some tips when writing emails in Japanese to Customers

When we work with Japanese customers, we need to become familiar with exchanging information that is related to work via email. Business emails have different expressions compared to spoken communication. Based on my learning and experiences, I would like to introduce some basic tips for writing work-related emails in Japanese.

View More
TECH

April 1, 2024

The Bluetooth Qualification Process: Overview for Individuals and Businesses

In the world of wireless communication, Bluetooth technology has become an integral part of our daily lives. From smartphones to smart home devices, Bluetooth enables seamless connectivity and data transfer. However, before a device can bear the official Bluetooth logo, it must go through a rigorous qualification process. In this blog post, we will delve into the steps involved in the Bluetooth qualification process for individuals and businesses, while also highlighting the potential risks of non-compliance. Please note that this article serves as a personal perspective and a reference guide.

View More
TECH

April 1, 2024

Understanding Stunnel: A Basic Overview

In today's digital landscape, safeguarding sensitive data on networks is paramount. Stunnel serves as a widely-used tool for achieving this goal.

View More
TECH

April 1, 2024

Introducing PHPStan: Improving PHP Code Quality

While developing PHP applications, IDEs like PhpStorm or Visual Studio Code can help you quickly detect and fix errors. However, there are error cases that the IDE cannot detect, such as:

  • Type errors: IDEs cannot check the data types of variables when they are passed between functions or methods.
  • Call to undefined method errors: IDEs cannot check the calling of methods of an object if they are not defined.
  • Accessing non-existing elements of an array or object: IDEs cannot check accessing non-existing elements of an array or object.
  • ...

PHPStan is a static analysis tool for PHP code that helps detect errors in source code that regular IDEs cannot detect. Unlike dynamic analysis tools that identify issues during runtime, PHPStan performs its analysis by examining the codebase without actually running the application. This approach allows developers to catch errors and potential problems before deploying the code.

Key Features of PHPStan:

  1. Static Analysis: PHPStan analyzes your code without running it, identifying a wide range of potential issues such as type mismatches, undefined variables, and unreachable code.
  2. Type Inference: By analyzing the code flow, PHPStan can infer types of variables, enabling early detection of type-related errors and improving the overall reliability of your code.
  3. Error Detection: It flags common mistakes and potential bugs in your code, helping you catch errors early in the development process.
  4. Customizable Rules: PHPStan allows you to define your own rules and levels of strictness, tailoring the analysis to your specific project requirements.
  5. Integration: It seamlessly integrates with popular PHP development tools and continuous integration pipelines, making it easy to incorporate into your existing workflow.

Benefits of Using PHPStan:

  1. Early Issue Detection: PHPStan finds problems in your code before it runs, helping to catch and prevent bugs early.
  2. Better Code Quality: PHPStan points out areas where your code can be improved, which helps make your code easier to maintain and understand.
  3. Increased Developer Efficiency: Developers get immediate feedback in their coding environment, which speeds up development and reduces time spent debugging.
  4. Type Safety: PHPStan checks types in your code, making it safer and less likely to have runtime errors caused by type mismatches.
  5. Customizable Rules: You can customize PHPStan to fit your project’s requirements by creating your own rules and extensions, ensuring it follows your coding standards.

How to use PHPStan:

To start using PHPStan, follow these simple steps:

  1. Organize project structure:

    Below is an example of a simple directory structure for a project using PHPStan:

    project_root/

    ├── src/ # Directory containing the PHP source code of the application
    │ ├── index.php

    ├── vendor/ # Directory containing libraries and Composer dependencies
    │ └── ...

    ├── phpstan.neon # PHPStan configuration file
    └── composer.json # Composer configuration file

  2. Install PHPStan using Composer

    composer require --dev phpstan/phpstan

  3. Create PHPStan Configuration:

    Add config to phpstan.neon configuration file. This file can define rules, paths to analyze, and other configuration options.

    Example phpstan.neon configuration:

    parameters:
      level: 7
      phpVersion: 80000
      paths:
        - src

    + level: This sets the strictness level of PHPStan to 7, indicating a high level of analysis.
    + phpVersion: Configuration option specifies the PHP version that PHPStan should use for analysis. In this case, 80000 corresponds to PHP version 8.0.0.
    + paths: Specifies the directories to analyze.

  4. Run PHPStan:

    We will add some error code examples to the index.php file for PHPStan to check.

    index.php

    1   <?php
    2   // Using an undeclared variable
    3   echo $undefinedVariable;
    4   
    5   // Calling a non-existent function
    6   nonExistentFunction();
    7   
    8   // Calling a non-existent method within a class
    9   class AnotherClass {
    10       public function method() {
    11           $this->undefinedMethod();
    12       }
    13   }
    14
    15  $anotherObj = new AnotherClass();
    16  $anotherObj->method();
    17
    18  // Performing an operation on a non-numeric variable
    19  $nonNumeric = 'abc';
    20  $result = $nonNumeric * 2;
    21
    22  // Using a global variable
    23  function testGlobal() {
    24      global $undefinedGlobal;
    25      echo $undefinedGlobal;
    26  }
    27
    28  testGlobal();
    29
    30  // Using a function with an inappropriate number of parameters
    31  function sum($a, $b) {
    32      return $a + $b;
    33  }
    34
    35  $result = sum(5);
    36
    37  // Accessing a non-existent element in an array
    38  $array = ['a', 'b', 'c'];
    39  echo $array[3];
    40  ?>


    After that, Run PHPStan from the command line in your project directory:

    vendor/bin/phpstan analyse

  5. Review the Output:

    PHPStan will analyze your code and provide feedback on any issues found. Review the output to identify and fix potential problems in your code.

    Note: Using configuration file /var/www/html/phpstan.neon.
     1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
     ------ ---------------------------------------------------------------------
      Line   index.php
     ------ ---------------------------------------------------------------------
      3      Variable $undefinedVariable might not be defined.
      6      Function nonExistentFunction not found.
             ? Learn more at https://phpstan.org/user-guide/discovering-symbols
      10     Method AnotherClass::method() has no return type specified.
      11     Call to an undefined method AnotherClass::undefinedMethod().
      20     Binary operation "*" between 'abc' and 2 results in an error.
      23     Function testGlobal() has no return type specified.
      31     Function sum() has no return type specified.
      31     Function sum() has parameter $a with no type specified.
      31     Function sum() has parameter $b with no type specified.
      35     Function sum invoked with 1 parameter, 2 required.
      39     Offset 3 does not exist on array{'a', 'b', 'c'}.
     ------ ---------------------------------------------------------------------
     [ERROR] Found 11 errors

Conclusion:

PHPStan is a valuable tool for any PHP developer looking to write cleaner, more reliable code. By catching errors early and providing detailed feedback, it empowers developers to build high-quality PHP applications with confidence and efficiency.

References:

View More
TECH

April 1, 2024

Twilio Video Calls with Laravel: A How-To Guide

In web development, good communication is key for any successful app. It's important for connecting users worldwide and making interactions smooth within your platform. Twilio is handy for this because it gives you tools for talking, video calls, and messages. We'll show why Twilio is great and how to make a video call feature with Laravel 10.

1, Why Twilio?

  • Reliability: Twilio boasts a highly reliable infrastructure, ensuring that your communication channels remain operational all time.
  • Scalability: With Twilio, you can easily scale your communication features to accommodate growing user demands without compromising performance.
  • Developer-Friendly: Twilio provides extensive documentation, libraries, and APIs, making it easy for developers to integrate communication features into their applications.
  • Flexibility: Beyond video calls, Twilio offers a wide range of communication tools, including voice calls, SMS, chat, and more, allowing you to create comprehensive communication solutions tailored to your needs.

2, Example: Creating a Video Call

Let's dive into a practical example of integrating Twilio's video call functionality into a Laravel application.

Step 1: Setting Up Twilio Account

First, sign up for a Twilio account and obtain your Account SID and Auth Token, which you'll need to authenticate your requests.

Step 2: Installing Twilio SDK

Install the Twilio PHP SDK via Composer by running the following command in your Laravel project directory:

composer require twilio/sdk

Step 3: Creating a Video Call

Now, let's create a simple controller method to initiate a video call:

use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VideoGrant;

public function initVideoCallTwilio(Request $request)
{
$identity = $request->user()->name; // Get user's name as identity
 
$twilioAccountSid = 'YOUR_TWILIO_ACCOUNT_SID';
$twilioApiKey = 'YOUR_TWILIO_API_KEY';
$twilioApiSecret = 'YOUR_TWILIO_API_SECRET';

$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600, // Time to live for the token
$identity // The identity to associate with the Access Token
);

$grant = new VideoGrant();
$grant->setRoom('RoomName'); // Set room's name for the video call
$token->addGrant($grant);
 
return view("twilio_video", ['token' => $token->toJWT()]);
}

This controller method generates a Twilio access token for the authenticated user, allowing them to join a video call room named 'RoomName'.

Step 4: Client-Side Integration

On the client-side (e.g., using JavaScript), utilize Twilio's SDK to connect to the video call room and display the video interface.

const Video = require('twilio-video');
const token = '{{ $token }}';

Video.connect(token, { video: true, audio: true, name: 'RoomName' }).then(room => {
console.log(`Connected to Room: ${room.name}`);

room.on('participantConnected', participant => {
console.log(`Participant "${participant.identity}" connected`);

participant.tracks.forEach(publication => {
if (publication.isSubscribed) {
const track = publication.track;
document.getElementById('video-div').appendChild(track.attach());
}
});
});
}).catch( error => {
console.error(`Unable to connect to Room: ${error.message}`);
});

This JavaScript code connects to the video call room using the access token generated by the Laravel controller and displays the remote participants' video streams.

3, Some disadvantages of Twilio with Zoom or Google Meet

  • Twilio may require more development effort for integration compared to the ready-to-use platforms like Zoom or Google Meet.
  • Zoom and Google Meet come with lots of video call features already, but Twilio might need extra changes to do exactly what you want.
  • Figuring out Twilio's pricing might be trickier than Zoom or Google Meet, so you might end up paying more for some things.
  • Users may already be familiar with Zoom or Google Meet interfaces, which could lead to a preference for these platforms over Twilio, resulting in lower adoption rates.

4, Conclusion

In conclusion, Twilio is super helpful for developers who want strong communication tools. Twilio is reliable, scalable, versatile, and easy for developers to use. It might need a bit more work to fit into your app compared to other options, but it's flexibility lets you make exactly what you need. Overall, Twilio is a great choice for making communication in your Laravel apps better and smoother.

References

View More
TECH

April 1, 2024

Form Validation In ReactJS With Yup And Formik

Form validation is an essential part of building user-friendly and robust web applications. In ReactJS, handling form validation can be complex, but fortunately, libraries like Yup and Formik provide powerful solutions. Yup offers schema-based validation, while Formik simplifies form management. In this post, we'll explore how to combine Yup and Formik to create a seamless form validation experience in ReactJS applications.

View More
1 16 17 18 19 20 25
Let's explore a Partnership Opportunity

CONTACT US



At ISB Vietnam, we are always open to exploring new partnership opportunities.

If you're seeking a reliable, long-term partner who values collaboration and shared growth, we'd be happy to connect and discuss how we can work together.

Add the attachment *Up to 10MB