Magis Technologies Inc Logo

How to transfer all your Facebook photos and videos to Google Photos

You have probably uploaded tons of photos and videos on Facebook, and you probably have forgotten most of them until they show up as Memories. But what if you want to download all those content and store them on a free cloud storage platform like Google Photos for safekeeping? Let us show you how.

The method can be done via the web browser or from the app. But for this guide, we’re going to use the former.

Step 1: Log in to your Facebook account and go to Settings.

Step 2: Click on the ‘Your Facebook Information’ tab on the left.

Step 3: Look for ‘Transfer a Copy of Your Photos or Videos’ then click on ‘View.’

Step 4: Enter your password to continue.

Step 5: Choose a destination where a copy of your photos or videos will be transferred to. In this case, click on Google Photos.

Step 6: Choose to transfer a copy of either your photos or videos you’ve uploaded to Facebook. After selecting, click on ‘Next.’

Step 7: Log in to your Google account and give Facebook access.

Step 8: Confirm transfer.

At this point, Facebook will proceed with uploading a copy of your photos or videos to your Google Photos. The photos are organized based on the name of the albums you have on Facebook. The transfer time might take a while depending on how much photos or videos are being transferred, so check back on this later.

You can also choose to stop the transfer. Take note that it will not pause the transfer so if ever you want to resume, you’ll have to start all over again.

And that’s it. We hope that you find this guide helpful. If you have tips or recommendations, let us know in the comments below.

How to grab a web page’s data with Google Sheets

Holy sheet: Here’s how to grab a web page’s data with Google Sheets

Scraping data is all the rage nowadays. But what many don’t know is that you don’t need to be a fancy hacker to be able to collect data from websites. In fact, you don’t even need any coding skills.

A multitude of tools such as browser extensions exist to alleviate the required technical knowledge. But even if that’s one hurdle too far for you, do not worry. Google will come to the rescue. Google Sheets to be precise.

It has a nifty little formula which allows you to grab a web page’s list or table of data into your sheet of choice. It’s called importhtml, and it works as follows:

Find a website you want to pull data from

As an example, let’s go for the List of largest technology companies by revenue Wikipedia page.

Identify a table or list you want to grab

In this case, let’s go for the second table on the page, in the ‘2019 list’ section.

Now, type the following into a cell of choice, let’s say A1

=IMPORTHTML(“https://en.wikipedia.org/wiki/List_of_largest_technology_companies_by_revenue”, “table”, 2)

As you can see, you’ll have to declare three things in the formula: The url you want to grab data from, the type of data (either table or list), and the position (in this case the second table, so 2).

Hit enter, and voilà, the table appears in your sheet:

To go next level, and actually transform or clean that data, make sure that it becomes static instead of linked data first. To do so, select the table, right mouse click on cell A1, ‘Paste special’ > ‘Paste values only’.

So there you go, have fun playing with data in Google Sheets!

Hide Your Messy Background During Online Conference Even Without a Green Screen

© 2019 ESQUIREMAG.PH, ALL RIGHTS RESERVED

TECH

Hide Your Messy Background During Online Conference Even Without a Green Screen

by MARIO ALVARO LIMOS  |  23 HOURS AGOShares  

IMAGE Ira JamesADVERTISEMENT – CONTINUE READING BELOW 

Working from home in the time of lockdown has forced many of us to do virtual meetings and conference calls through various apps like Teams, Zoom, and Skype. You have probably scouted locations at home for an ideal background for the live video.

One app will help you remove, replace, or just blur your background even without a green screen. XSplit VCam hides your messy room and maintain your privacy if you don’t want others to see where you’re working from during a video conference.

You can select from XSplit’s suite of background templates which include a cool office space, a beach, and even Malacanang Palace. You may also customize your background and select from your own set of photos. In the following photo, an XSplit user Ira James used an office background to hide his room.

Spotify adds fundraising features and a COVID-19 news hub to address the health crisis

S4A_BLOGSPOT_HEADER

Spotify this morning announced a series of new initiatives to address the COVID-19 health crisis across its platform. The company is launching a financial relief effort for those in the creative community who have been heavily impacted by the virus, which includes the addition of a public donations feature on its website. The company is also working to add a new feature that will allow artists to fundraise directly from their fans via their Spotify artist profile pages. Meanwhile, for listeners, Spotify is adding a COVID-19 news and information hub in its app to help keep users informed.

The new Spotify COVID-19 Music Relief Project will recommend verified organizations that are offering financial relief to those in the music community who are in need, worldwide. At launch, Spotify is partnering with MusiCares, PRS Foundation, and Help Musicians, and says it’s planning to add more partners in time.

The company says it will also match dollar-for-dollar the public donations made through the Spotify COVID-19 Music Relief page up to a total contribution of $10 million. Industry professionals in need of financial assistance will go to the partners’ sites for information to apply for relief funds.

“While streaming still gives artists a way to connect with their fans, so many other sources of revenue have been put on hold by this crisis,” notes the company on the Relief project’s page. “To play our part, we’re working with a growing list of organizations offering financial relief to creators around the world to find ways to support our community,” it says.

And though not yet launched, Spotify says it’s working to add a new fundraising feature for artists that will allow them to drive their fans to a fundraising destination of their own choice. This would allow artists to directly fundraise for other artists in need or another separate initiative of their own choosing. This feature will be optional for the artists to use and no changes to their profile pages will occur unless the artist wants to participate. And unlike the fundraising efforts on other sites, Spotify says it won’t take a cut of the funds.

Of course, offering personal fundraisers in a time of crisis can also be problematic, as there are a number of scammers now trying to capitalize on crisis with fake fundraisers. Artists, like anyone else, could fall for these scams and then rally their fans towards the cause — potentially redirecting money away from true relief organizations at a time when it’s critical.

This is worsened by the fact that personal fundraisers generally need vetting to ensure they in and of themselves aren’t scams or engaging in some kind of fraud. Even Facebook, operating at the scale it does, is warning users that it currently has fewer people on staff to review personal fundraisers due to the coronavirus (COVID-19) outbreak. It says fundraisers may not even be able to be reviewed at all and if they are, they’ll take longer than usual. And yet Spotify is readily the rollout of fundraisers at this time when staffing reductions and disruptions to schedules are in place. The staff works from home. But COVID-19 has disrupted every business and no entity is immune from that.)

In addition, Spotify is adding a new feature to connect listeners with news and information about COVID-19. Through a new in-app hub, the company is pointing users to news and podcasts from the media, including ABC News, BBC World Service, CNN, Foreign Policy, and NPR.

And, like most companies, Spotify is also offering advertising space to governments and nonprofits for health information and PSAs.

The new COVID-19 Music Relief Project and COVID-19 hub are live today. Artists fundraisers are in the works.

IBM and The Weather Channel launch detailed local COVID-19 maps and data tracking

IBM+Cognos+Analytics+Dashboard_County+Level_2

There are already a number of resources available for mapping the spread of confirmed COVID-19 cases both in the U.S. and globally, but IBM  and its subsidiary The Weather Company  have launched new tools that bring COVID-19 mapping and analysis to more people via their Weather Channel mobile app and weather.com.

Existing tools are useful, but come from fairly specialized sources including the World Health Organization (WHO) and Johns Hopkins University. This new initiative combines data fro these same sources, including global confirmed reported COVID-19 cases, as well as reported data from sources at both the state and county level. This is collected on a so-called “incident map” that displays color-coded reported case data for states and counties, as well as on state-wide trend graphs and through reporting of stats including relative percentage increase of cases week-over-week.

On top of these sections built into the core, consumer-facing Weather.com products, IBM has also launched a more in-depth analytics reporting dashboard, providing views of global reported COVID-19 cases, as well as rate of spread based on available data, county-by-county stats and more.

This information from IBM, which runs on its Watson  and Cognos Analytics tools, are intended for use by both researchers and public officials – but they’re also meant for general public consumption. IBM is also providing resources including fact-checking resources and practical guidance for both COVID-19 patients and the general public, to help not only inform people about the spread of the virus, but also the steps they can take to protect themselves and others.

One of the key elements of COVID-19 mitigation is making sure that the average American has access to reliable and accurate information, including the most up-to-date guidelines about social distancing and isolation from trusted experts, including the WHO and the Centers for Disease Control and Prevention  (CDC). That makes this a key resource in the ongoing efforts to curb the spread of the coronavirus, since it resides in an app that is among the most popular pieces of software available for smartphones. There are around 45 million or so monthly active users of the Weather Channel app, which means that this information will now be readily accessible by a large percentage of the U.S. population.

Bootstrap 5 release date and what’s new about it

Bootstrap 5 Release Date

The alpha version of Bootstrap 4 has been released on the 19th of August 2015 and it brought a lot of improvements such as flexbox, a better grid system, cards, improved navbars and switching Sass over Less. Additionally it took more than 2 years to bring it to a stable version on January 18th, 2018.

With that being said let’s analyze everything we know about Bootstrap 5’s release date and improvements.

Bootstrap 5 release date

Progress is looking really good on the official Github project tracking board with 686 tasks being shipped and roughly 35 more pending or being in review. Taking in consideration that they’re already working on the alpa-2 and alpha-3 versions, we can expect Bootstrap 5 to be released in late spring this year.

What’s new?

Some of the major changes will be removing jQuery altogether as a dependency, adding back custom icons powered by SVG (which they already launched last year), some CSS & Javascript simplifications, fixes and improvements and removing support for IE 10. 

Here’s a list of all the expected changes:

  • Removing jQuery
  • Dropping support for IE 10
  • Custom SVG icon library
  • Switching to Hugo from Jekyll
  • Major Javascript updates
  • Minor CSS and class updates and fixes

Removing jQuery 😱

This shouldn’t be a surprise as jQuery has been losing ground in times when frameworks such as React.js, Vue.js and Angular.js are being used by an increasing amount of developers across the world. Additionally many of jQuery’s querying features can be done by just writing vanilla Javascript query selector nowadays.

I believe this is a good time to do it as jQuery has served its purpose for a long time. Removing this dependency will lighten the project’s size considerably.

Dropping IE 10 support 📺

Internet Explorer 10 accounts for less than 1% of global browser usage and considering that since 2016 Microsoft ended support for version older and including 10 this is an understandable change.

Custom SVG icon library 🚀

Personally I was a bit disappointed with the lack of an integrated icon library for the 4th version. We usually use Font Awesome or custom SVG icons in our products, but we may soon change that. 

With the 5th version there’s a brand new SVG powered icon library coming created by Mark Otto. What’s even better is that it has already been released in December and you can use them in your projects right now!

Switching to Hugo from Jekyll 🔝

Jekyll has been around for a long time as a very popular Static Site Generator, however in recent years Hugo has been deemed to be the fastest and most recommended one. We see this change similar to what they did with the 4th version of Bootstrap by switching from Less to Sass.

Javascript & CSS

We expect huge changes to the core Javascript file as jQuery will no longer be part of the project. Expect going through a new documentation regarding event listeners and options. Regarding the CSS there are no major changes but we assume there will be some optimizations, class updates and general fixes.

In conclusion Bootstrap 5 should be faster, simpler and better looking. Don’t expect huge changes in terms of the base set of components, but rather appreciate the time it will save you developing beautiful user interfaces and the shorter loading time for the users.

“Bachelor of Science in Esports” could soon be an actual college degree in Philippines.

Image result for future is here gif
Banner credit: ggscore.com

Tier One Entertainment’s Tryke Gutierrez recently shared that he’s been working with Lyceum of the Philippines University (LPU) in creating a curriculum for ‘Bachelor of Science in Esports.’ – a 4-year college program focused solely on the study of Esports.

Per the Esports agency CEO, the curriculum is ‘80% done‘ and future enrollees can choose from its 2 tracks of Game Design or Esports Management.

Bachelor of Science in Esports!! We are weeks away from reaching one of the biggest milestone in Philippine esports…

Posted by TryQ on Wednesday, 19 February 2020

Tryke has yet to share the full program list, but he mentioned that the decision for the program stems from PH being one of the largest Esports markets in Asia. He furthered that other countries like U.S, Singapore, and China are already offering Esports programs.

‘This is a dream come true for me as I personally believe that a proper support system is one of the strongest foundations for success.’ he shared.

‘Once the academe finally accepts this industry, I truly believe that the support from families of gamers will follow.’

With other Esports programs usually offered through vocational programs or training camps, Tryke further emphasized the need for a degree in the budding field.

‘I’ve been in this industry for too long to understand that it takes more than passion in order to achieve what you want to achieve [in Esports].’

‘You need hard work, sacrifice, skills, professionalism and many more.’

There’s no say when the course will officially start preparation though, as Tryke’s team is still set to send the curriculum for CHED approval on March 4.

The idea isn’t so far-fetched when you consider that PH’s very own Esports team ‘Sibol‘ brought the country pride when they bagged 3 gold medals in the 2019 SEA Games – bringing a whole new definition to ‘kaka-kompyuter mo yan‘.

One could question the need for a college program, but with entirely new digital career fields slowly but surely thriving through the years, this could be a game-changer in how we see non-traditional degrees.

aspnet

Understanding Dependency Injection in .NET Core

Learn what Dependency Injection and IoC are and what .NET Core provides you to support them.

Dependency Injection is one of the most known techniques that help you to create more maintainable code. .NET Core provides you with extensive support to Dependency Injection, but it may not always be clear how to apply it. This tutorial will try to clarify the various Dependency Injection concepts and will introduce you to the support provided by .NET Core.

The Dependency Problem

Have you ever had to change a lot of code because of a new simple requirement? Have you ever had a hard time trying to refactor part of an application? Have you ever been in trouble writing unit tests because of components that required other components?

If you answered yes to any of these questions, maybe your codebase suffers from dependency. It’s a typical disease of the code of an application when its components are too coupled. In other words, when a component depends on another one in a too-tight way. The main effect of component dependency is the maintenance difficulty of the code, which, of course, implies a higher cost.

A dependency example

Take a look at a typical example of code affected by dependency. Start by analyzing these C# classes:

using System;
using System.Collections.Generic;

namespace OrderManagement
{
    public class Order
    {
        public string CustomerId { get; set; }
        public DateTime Date { get; set; }
        public decimal TotalAmount { get; set; }
        public List<OrderItem> Items { get; set; }

        public Order()
        {
            Items = new List<OrderItem>();
        }
    }

    public class OrderItem
    {
        public string ItemId { get; set; }
        public decimal Quantity { get; set; }
        public decimal Price { get; set; }
    } 
}

This code defines two classes, Order and OrderItem, that represent the order of a customer. The orders are managed by the OrderManager class implemented as follows:

using System.Threading.Tasks;

namespace OrderManagement
{
    public class OrderManager
    {
        public async Task<string> Transmit(Order order)
        {
            var orderSender = new OrderSender();

            return await orderSender.Send(order);
        }
    }
}

The OrderManager class implements the Transmit() method, which sends the order to another service to process. It relies on the OrderSender class to actually send the order received as an argument.

This is the code implementing the OrderSender class:

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace OrderManagement
{
    public class OrderSender
    {
        private static readonly HttpClient httpClient = new HttpClient();

        public async Task<string> Send(Order order)
        {
            var jsonOrder = JsonSerializer.Serialize<Order>(order);
            var stringContent = new StringContent(jsonOrder, UnicodeEncoding.UTF8, "application/json");

            //This statement calls a not existing URL. This is just an example...
            var response = await httpClient.PostAsync("https://mymicroservice/myendpoint", stringContent);

            return response.Content.ReadAsStringAsync().Result;

        }
    }
}

As you can see, the Send() method of this class serializes the order and send it via HTTP POST to a hypothetical microservice that will process it.

The code shown here is not meant to be realistic. It is just a rough example.

What happens if you need to change the way of sending an order? For example, suppose you also want to send orders via e-mail or to send them to another microservice that uses gRPC instead of HTTP. Also, how comfortable do you feel to create a unit test for the OrderManager class?

Since OrderManager depends on OrderSender, you will be forced to change in some way both classes to support multiple sender types. Changes in the lower-level component (OrderSender) may affect the higher-level component (OrderManager). Even worse, it will be almost impossible to automatically test the OrderManager class without risking to mess your code.

This is just a simple study case. Think of the impact that dependency may have in a more complex scenario with many dependent components. That could really become a huge mess.

The Dependency Inversion Principle

The last of the SOLID principles proposes a way to mitigate the dependency problem and make it more manageable. This principle is known as the Dependency Inversion Principle and states that:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions
  • Abstractions should not depend on details. Details should depend on abstractions.

You can translate the two formal recommendations as follows: in the typical layered architecture of an application, a high-level component should not directly depend on a lower-level component. You should create an abstraction (for example, an interface) and make both components depend on this abstraction.

Translated in a graphical way, it appears as shown by the following picture:

Dependency Inversion Principle Diagram

Of course, all of this may seem too abstract. Well, this article will provide you with examples to clarify the concepts about dependency and the techniques to mitigate it. While the general concepts are valid for any programming language and framework, this article will focus on the .NET Core framework and will illustrate the infrastructure it provides you to help in reducing component dependency.

A trip in the dependency lingo

Before exploring what .NET provides you to fight the dependency disease of your code, it’s necessary to put some order in the terminology. You may have heard many terms and concepts about code dependency, and some of them seem to be very similar and may have been confusing. Well, here is an attempt to give a proper definition of the most common ones:

  • Dependency Inversion Principle: it’s a software design principle; it suggests a solution to the dependency problem but does not say how to implement it or which technique to use.
  • Inversion of Control (IoC): this is a way to apply the Dependency Inversion Principle. Inversion of Control is the actual mechanism that allows your higher-level components to depend on abstraction rather than the concrete implementation of lower-level components.Inversion of Control is also known as the Hollywood Principle. This name comes from the Hollywood cinema industry, where, after an audition for an actor role, usually the director says, don’t call us, we’ll call you.
  • Dependency Injection: this is a design pattern to implement Inversion of Control. It allows you to inject the concrete implementation of a low-level component into a high-level component.
  • IoC Container: also known as Dependency Injection (DI) Container, it is a programming framework that provides you with an automatic Dependency Injection of your components.

Dependency Injection approaches

Dependency Injection is maybe the most known technique to solve the dependency problem.

You can use other design patterns, such as the Factory or Publisher/Subscriber patterns, to reduce the dependency between components. However, it mostly derives on the type of problem your code is trying to solve.

As said above, it is a technique to providing a component with its dependencies, preventing the component itself from instantiating by themselves. You can implement Dependency Injection on your own by creating instances of the lower-level components and passing them to the higher-level ones. You can do it using three common approaches:

  • Constructor Injection: with this approach, you create an instance of your dependency and pass it as an argument to the constructor of the dependent class.
  • Method Injection: in this case, you create an instance of your dependency and pass it to a specific method of the dependent class.
  • Property Injection: this approach allows you to assign the instance of your dependency to a specific property of the dependent class.

.NET Core and the Dependency Injection

You can implement Dependency Injection manually by using one or more of the three approaches discussed before. However, .NET Core comes with a built-in IoC Container that simplifies Dependency Injection management.

The IoC Container is responsible for supporting automatic Dependency Injection. Its basic features include:

  • Registration: the IoC Container needs to know which type of object to create for a specific dependency; so, it provides a way to map a type to a class so that it can create the correct dependency instance.
  • Resolution: this feature allows the IoC Container to resolve a dependency by creating an object and injecting it into the requesting class. Thanks to this feature, you don’t have to instantiate objects manually to manage dependencies.
  • Disposition: the IoC Container manages the lifetime of the dependencies following specific criteria.

You will see these features in action in a while. But before this, some basic information is needed.

The .NET Core built-in IoC Container implements the IServiceProvider interface. So if for some reason, you want to create your own IoC Container, you should implement this interface. In .NET Core, the dependencies managed by the container are called services. You have two types of services:

  • Framework services: these services are part of the .NET Core framework; some examples of framework services are IApplicationBuilderIConfigurationILoggerFactory, etc.
  • Application services: these are the services that you create in your application; since the IoC doesn’t know them, you need to register them explicitly.

Dealing with Framework Services

As a .NET Core developer, you’ve already used the built-in IoC Container to inject framework services. Indeed, .NET Core heavily relies on it. For example, the Startup class in an ASP.NET application uses Dependency Injection extensively:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
            // ... code ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
            // ... code ...
    }

        // ... code ...
}

In this example, the Startup() constructor requires a configuration parameter implementing the IConfiguration type. Since IConfiguration is one of the framework service types, the IoC Container knows how to create an instance of it and inject it into the Startup class applying the Constructor Injection approach. The same applies to the Configure() method. Keep in mind, however, that only the following framework service types can be injected in the Startup() constructor and in the Configure() method of a standard ASP.NET application: IWebHostEnvironmentIHostEnvironment, and IConfiguration. This is a special case for framework services because you don’t need to register them.

Registering framework services

In general, you have to register services needed by your ASP.NET application in the ConfigureServices() method of the Startup class. This method has an IServiceCollection parameter representing the list of services your application depends on. Practically, the collection represented by this parameter allows you to register a service in the IoC Container. Consider the following example:

public class Startup
{
         // ... code ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });
    }

        // ... code ...
}

Here, you are registering a dependency for managing authentication for your application. In this specific case, you are using the extension methodAddAuthentication() with the parameters describing the authentication type you want to use. The framework provides extension methods to register and configure dependencies for the most common services. It also provides the Add() method to register generic dependencies, as in the following example:

public class Startup
{
         // ... code ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.Add(new ServiceDescriptor(typeof(ILog), new MyLogger()));  
    }

        // ... code ...
}

In this case, you are registering a log service implementing the ILog interface. The second parameter of the Add() method is an instance of the MyLogger class you have implemented in your project. As you may guess, this registration creates a singleton service, i.e., a single instance of the MyLogger class that will fulfill any requests coming from your application.

Service lifetimes

This single instance of your dependency will live for the entire lifetime of your application. This may be suitable for a service like a logger, but it is unacceptable for other services. The IoC Container allows you to control the lifetime of a registered service. When you register a service specifying a lifetime, the container will automatically dispose of it accordingly. You have three service lifetimes:

  • Singleton: this lifetime creates one instance of the service. The service instance may be created at the registration time by using the Add() method, as you saw in the example above. Alternatively, the service instance can be created the first time it is requested by using the AddSingleton() method.
  • Transient: by using this lifetime, your service will be created each time it will be requested. This means, for example, that a service injected in the constructor of a class will last as long as that class instance exists. To create a service with the transient lifetime, you have to use the AddTransient() method.
  • Scoped: the scoped lifetime allows you to create an instance of a service for each client request. This is particularly useful in the ASP.NET context since it allows you to share the same service instance for the duration of an HTTP request processing. To enable the scoped lifetime, you need to use the AddScoped() method.

Choosing the right lifetime for the service you want to use is crucial both for the correct behavior of your application and for better resource management.

Managing Application Services

Most of the concepts you learned from framework services are still valid for your application services. However, framework services are already designed to be injectable. The classes you define in your application need to be adapted to leverage Dependency Injection and integrate with the IoC Container.

To see how to apply the Dependency Injection technique, recall the order management example shown early in this article and assume that those classes are within an ASP.NET application. You can download the code of that application from this GitHub repository by typing the following command in a terminal window:

git clone -b starting-point --single-branch https://github.com/sniper57/dependency-injection-dotnet-core

This command will clone in your machine just the branch starting-point of the repository. After cloning the repository, you will find the dependency-injection-dotnet-core folder on your machine. In this folder, you have the OrderManagementWeb subfolder containing the ASP.NET Core project with the classes shown at the beginning of this article. In this section, you are going to modify this project to take advantage of the Dependency Injection and the built-in IoC Container.

Defining the abstractions

As the Dependency Inversion Principle suggests, modules should depend on abstractions. So, to define those abstractions, you can rely on interfaces.

Add a subfolder to the OrderManagementWeb folder and call it Interfaces. In the Interfaces folder, add the IOrderSender.cs file with the following content:

// OrderManagementWeb/Interfaces/IOrderSender.cs

using System.Threading.Tasks;
using OrderManagement.Models;

namespace OrderManagement.Interfaces
{
    public interface IOrderSender
    {
        Task<string> Send(Order order);
    }
}

This code defines the IOrderSender interface with just one method, Send(). Also, in the same folder, add the IOrderManager.cs file with the following interface definition:

// OrderManagementWeb/Interfaces/IOrderManager.cs

using System.Threading.Tasks;
using OrderManagement.Models;

namespace OrderManagement.Interfaces
{
    public interface IOrderManager
    {
        public Task<string> Transmit(Order order);
    }
}

The above code defines the IOrderManager interface with the Transmit() method.

Depending on the abstractions

Once defined the abstractions, you have to make your classes depending on them instead of the concrete class instances. As a first step, you need to redefine the OrderSender class so that it implements the IOrderSender interface. You also rename the class into HttpOrderSender to point out that this implementation sends the order via HTTP. So, open the OrderSender.cs file in the Managers folder and replace its content with the following:

// OrderManagementWeb/Managers/OrderSender.cs

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement
{
    public class HttpOrderSender : IOrderSender
    {
        private static readonly HttpClient httpClient = new HttpClient();

        public async Task<string> Send(Order order)
        {
            var jsonOrder = JsonSerializer.Serialize<Order>(order);
            var stringContent = new StringContent(jsonOrder, UnicodeEncoding.UTF8, "application/json");

            //This statement calls a not existing URL. This is just an example...
            var response = await httpClient.PostAsync("https://mymicroservice.lan/myendpoint", stringContent);

            return response.Content.ReadAsStringAsync().Result;

        }
    }
}

Now, you need to redefine also the OrderManager class so that it implements the IOrderManager interface. Open the OrderManager.cs file in the Managers folder and replace its content with the following:

// OrderManagementWeb/Managers/OrderManager.cs

using System.Threading.Tasks;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement
{
    public class OrderManager : IOrderManager
    {
        private IOrderSender orderSender;

        public OrderManager(IOrderSender sender)
        {
            orderSender = sender;
        }

        public async Task<string> Transmit(Order order)
        {
            return await orderSender.Send(order);
        }
    }
}

You may notice that, differently from the previous version of the class, the Transmit() method no longer creates an instance of the OrderSender class. The dependency is now accessed via the class constructor.

With these changes, you broke the dependency between the OrderManager and the HttpOrderSender classes. Now, the OrderManager depends on the IOrderSender interface, i.e., its abstraction.

Registering the dependencies

Now you need to tell the IoC Container how to manage the dependencies based on the abstraction you have defined. In other words, you need to register the dependencies. As said, this registration happens in the Startup class of the project. So, open the Startup.cs file and replace the ConfigureServices() method with the following:

// OrderManagementWeb/Startup.cs

public class Startup
{
    // ...code ...

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped<Interfaces.IOrderSender, HttpOrderSender>();
            services.AddScoped<Interfaces.IOrderManager, OrderManager>();
        }

    // ...code ...

}

As you can see, you registered the dependencies by using the generic version of the AddScoped() method. Here you are asking the IoC Container to create an instance of the HttpOrderSender class whenever a request for the IOrderSender type is detected. Similarly, it should create an instance of the OrderManager class when theIOrderManager type is requested.

Note that even the AddController() method is an extension method provided by Microsoft.Extensions.DependencyInjection library that registers services for the Web API controllers.

Injecting the dependencies

Now it’s time to actually use all these dependencies. So, open the OrderController.cs file in the Controllers folder and replace its content with the following code:

// OrderManagementWeb/Controllers/OrderController.cs

using Microsoft.AspNetCore.Mvc;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagement.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private IOrderManager orderManager;

        public OrderController(IOrderManager orderMngr)
        {
            orderManager = orderMngr;
        }

        [HttpPost]
        public ActionResult<string> Post(Order order)
        {
            return Ok(orderManager.Transmit(order));
        }
    }
}

The new version of the Web API controller defines a private orderManager variable. Its value represents the instance of a service implementing the IOrderManager interface. The value of this variable is assigned in the constructor, which has an IOrderManager type parameter. With this parameter, the constructor is requesting the IoC Container a service instance of that type. The IoC Container searches in its service collection a registration that can satisfy this request and passes such an instance to the controller. But that’s not all. The IoC Controller also looks for other indirect dependencies and resolve them. This means that while creating the instance of the OrderManager class, the IoC Container also resolves its internal dependency on the IOrderSender abstraction. So you don’t have to worry about indirect dependencies: they are all resolved under the hood simply because the Web API controller declared to need a registered service.

As you noticed in these examples, the Constructor Injection is the default approach used by the IoC Container to inject dependencies in a class. If you want to use the Method Injection approach, you should request it explicitly by using the FromServices attribute. This example shows how you could use this attribute:

[HttpPost]
public ActionResult<string> Post([FromServices]IOrderManager orderManager)
{
    return Ok(orderManager.Transmit(order));
}

The third injection approach, the Property Injection, is not supported by the built-in IoC Container.

Dependency Injection in a Console Application

In the previous section, you implemented Dependency Injection for an ASP.NET Web application. You followed a few steps to register and get your dependencies automatically resolved by the built-in IoC Container. However, you may still feel something magic in the way it happens since the ASP.NET Core infrastructure provides you with some implicit behaviors. However, the Dependency Injection mechanism provided by the IoC Container is not just for Web applications. You can use it in any type of application.

In this section, you will learn how to leverage the IoC infrastructure in a console application, and some behaviors that may still look obscure will be hopefully clarified. So, move in the dependency-injection-dotnet-core folder you created when cloned the ASP.NET application and run the following command in a terminal window:

dotnet new console -o OrderManagementConsole

This command creates an OrderManagementConsole folder with a basic console application project. Now, copy in the OrderManagementConsole folder the InterfacesManagers, and Models folders from the ASP.NET project you modified in the previous section. Basically, you are reusing the same classes related to the order management process you defined in the ASP.NET project.

After this preparation, the first step to enable your console application to take advantage of the IoC Container is to add the Microsoft.Extensions.DependencyInjection package to your project with the following command:

dotnet add package Microsoft.Extensions.DependencyInjection

Then, you have to write some code to set up the IoC Container in your console application. Open the Program.cs file and replace its content with the following:

// OrderManagementConsole/Program.cs

using System;
using Microsoft.Extensions.DependencyInjection;
using OrderManagement;
using OrderManagement.Interfaces;
using OrderManagement.Models;

namespace OrderManagementConsole
{
    class Program
    {
        private static IServiceProvider serviceProvider;

        static void Main(string[] args)
        {
            ConfigureServices();

            var orderManager = serviceProvider.GetService<IOrderManager>();
            var order = CreateOrder();

            orderManager.Transmit(order);
        }

        private static void ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddTransient<IOrderSender, HttpOrderSender>();
            services.AddTransient<IOrderManager, OrderManager>();

            serviceProvider = services.BuildServiceProvider();
        }

        private static Order CreateOrder()
        {
            return new Order {
                CustomerId = "12345",
                Date = new DateTime(),
                TotalAmount = 145,
                Items = new System.Collections.Generic.List<OrderItem>
                {
                    new OrderItem {
                        ItemId = "99999",
                        Quantity = 1,
                        Price = 145
                    }
                }
            };
        }
    }
}

You see that the first operation in the Main() method of the Program class is configuring the services. Taking a look at the ConfigureServices() method, you see that this time you have to create the services collection explicitly. Then, you register your services with the transient lifetime: the dependencies should live just the time needed to manage the order. Finally, you get the service provider by using the BuildServiceProvider() method of the services collection and assign it to the serviceProvider private variable.

You use this service provider to get an instance of a registered service. For example, in the Main() method, you get an instance of the IOrderManager service type by using the GetService<IOrderManager>() method. From now on, you can use this instance to manage an order. Of course, as in the ASP.NET case, the orderManager instance has any indirect dependency resolved.

Finally, the CreateOrder() method just creates a dummy order to be passed to the Transmit() method of the order manager.

Summary

This article tried to clarify some concepts related to the Dependency Injection design pattern and focused on the infrastructure provided by .NET Core to support it. After introducing a few general definitions, you learned how to configure an ASP.NET Core application to use the built-in IoC container and register framework services. Then, you adapted the classes of an ASP.NET application to apply the Dependency Inversion Principle and discovered how to register your dependency in the IoC Container specifying the desired lifetime. Finally, you saw how to use the IoC Container even in a console application.

You can find the full source code discussed in this article in this GitHub repository.

Samsung gives foldables another go with the Galaxy Z Flip

Samsung Z Flip1

Samsung did a surprisingly good job keeping the Galaxy Fold under wraps, surprising the world with its first foldable this time last year during the Galaxy S10 unveil. When it came to the Galaxy Z Flip, on the other hand, the company just went ahead and showed the whole thing off during an Oscar ad buy. (Not to mention numerous Samsung employees playing around with the handsets in their seats this morning, ahead of unveil). Crazy world, these mobile phones.

Of course, that’s not to say we haven’t know about the Flip for a while now. Samsung teased out the Moto Razr-style form factor before it even officially announced the Fold. Samsung wanted to make it perfectly clear that the foldable wasn’t just a one and done situation for the company.

The company kicked today’s event off by unveiling the new foldable, which it claims is “like nothing you’ve ever seen before.” Which, well, isn’t exactly true.

Certainly the Z Flip form factor seems a more logical one, harkening back to pre-smartphone days of clamshell devices. Of course, the Razr has been running into its own issues after its recent release. Between that and — even more notable — the Fold’s myriad problems, the Z Flip will no doubt been under as much scrutiny as any handset in recent memory.

When opened, the screen is 6.7 inches, with a hole punch camera up top. When closed, there isn’t much of a display, beyond a quick bar that offers time, notifications and battery life. Users can also snap selfies with the case closed. The clam shell comes in three colors: black, purple and gold.

One assumes that Samsung learned plenty of lessons the original Fold, after having to go back to the drawing board when multiple reviewers wound up with broken units. Samsung claims the device can handle 200,000 flips, courtesy of foldable glass — which should give it some extra durability.

Samsung claims the device can handle 200,000 flips, courtesy of foldable glass — which should give it some extra durability. In an offhanded reference to earlier issues, the company noted that the hinge is designed to keep debris out, one of the major downfalls of the first gen Fold, which allowed dust and particles behind the screen, damaging it when users pressed down. The new phone has a kind of brush system inside to keep stuff out.

Obviously we can’t quite speak to durability just yet (though I, for one, am excited to get my hands on the thing), but at $1,380, it’s priced — well, it’s less expensive than the $2,000 Galaxy Fold, at least. That puts it more in line with the new Razr, not to mention, Samsung’s just now introduced Galaxy S20 Ultra.

The Flip will be available on Valentine’s Day.

A Thom Browne Edition, meanwhile, will bring the iconic designer’s touch to the device, which will be highlighted in more detail at a special event tomorrow in New York as part of Fashion Week. 

Joins in SQL – Inner, Outer, Left and Right Join

Here you will get detailed information about joins in SQL.

Join is a very basic concept in SQL which can be confusing at times. The joins are used when we need to find out the solution to a query involving the attributes of more than one table which have at least one attribute in common. Hence the need of join is pretty much clear in itself. There are different types of join which are used for different purposes.

Joins in SQL

Let’s say we have two tables, a table named STUDENT and the other table named TEACHER.

The first table “STUDENT” stores the reference details of the student and the second table “TEACHER” stores the details of the teachers who are in the school and the class they are teaching.

STUDENT

ClassIDNameHouse address
101Johnxyz
201Davidbyc
301Victorabc
401Patrickdef

TEACHER

Teacher idClass nameClassID
1First101
2Second201
3Third301
4Fourth401

In the second table, the “ClassID” is a foreign key which is used as a reference of the first table in the second one.

Now, if we want to find out the name of the student whose teacher id is 1; we need to find the join of the above mentioned tables since it requires us to gather the information of both the tables. Hence, the joins are only used where both the tables have at least one attribute (here ClassID) in common and we need to find the solution to a query which involves the attributes from both the tables.

Types of Join

Basically there are four types of joins namely, inner join, left join, right join, full outer join. The explanation of each one of the mentioned joins is as given below.

1. Inner Join

Let us consider the following two tables, the first table’s name is Country (saves the id of different countries) and the other table’s name is State (saves the various states in those countries).

COUNTRY

CountryIdCountryName
1China
2PH
3USA

STATE

StateIdCountryIdStateName
012 PASAY
022 MAKATI
035 NAVOTAS
046 PATEROS
select * from COUNTRY

inner join STATE

on COUNTRY.CountryId=STATE.CountryId

The above mentioned command applies an inner join on the two table, since the common attribute is Country id, we have applied the join on the same.

The inner join returns all the matching values from both the tables. Here, in table State, since the only matching CountryId value in the country table is {CountryId = 2}, as a result of the inner join we will get the following result:

CountryIdCountryNameStateIdStateName
2 PH 01 PASAY
2 PH 02 MAKATI

2. Right Join

The  right (or right outer join) on the other hand, displays the data which is common in both the tables, as well as the data which is present in the right table (exclusively).

This basically means that the entire right table’s data would be displayed on application of a right join.

When there is no match in the Left Table, it displays NULL.

Example:

COUNTRY

CountryIdCountryName
1China
2 PH
3USA

STATE

StateIdCountryIdStateName
012 PASAY
022 MAKATI
035 NAVOTAS
046 PATEROS
select * from COUNTRY

right  join STATE

on COUNTRY.CountryId=STATE.CountryId

The above mentioned command applies a right join on the two tables, since the common attribute is CountryId; we have applied the join on CountryId itself.

The right table is the second table we refer to.

We would get the following table as a result of the application of the right join:

CountryIdCountryNameStateIdStateName
2 PH 01 PASAY
2 PH 02 MAKATI
5NULL03 NAVOTAS
6NULL04 PATEROS

In the result, it is clearly depicted that the values in the Left Table which have absolutely no matching values in the Right one are not being displayed. Only those values of the Left Table are displayed which have common attributes with the Right one. Whereas all the values in the Right Table are displayed. The rows in the Right Table with no match in the Left Table are displayed as NULL (Empty).

3. Left Join

The left join (or left outer join) on the other hand, displays the data which is common in both the tables, as well as the data which is present in the left table (exclusively).

This basically means that the entire Left Table’s data would be displayed on application of a Left Join.

When there is no match in the Left Table, it displays NULL.

COUNTRY

CountryIdCountryName
1China
2 PH
3USA

STATE

StateIdCountryIdStateName
012 PASAY
022 MAKATI
035 NAVOTAS
046PATEROS
select * from COUNTRY

left join STATE

on COUNTRY.CountryId =STATE.CountryId

The above mentioned command applies a Left Join on the two tables, since the common attribute is CountryId; we have applied the join on Countryid itself.

The Left Table is the first table we refer to.

We would get the following table as a result on application of left join:

CountryIdCountryNameStateidStatename
1ChinaNULLNULL
2 PH 01 PASAY
2 PH 02MAKATI
3USANULLNULL

In the result, it is clearly depicted that the values in the right column which have absolutely no matching values in the left one are not being displayed. Only those attributes of the right column are displayed which have common attributes with the left one. Whereas all the values in the Left Table are displayed. The rows in the Left Table with no match in the Right Table are displayed as NULL (Empty)

4. Full Outer Join

The Full Outer Join, as the name suggests, shows all the content of both the tables. The Full Outer Join returns all matching records from both the tables whether the other table matches or not.

COUNTRY

CountryIdCountryName
1China
2 PH
3USA

STATE

StateIdCountryIdStateName
012 PASAY
022 MAKATI
035 NAVOTAS
046QUEZON
select * from COUNTRY

full outer join STATE

on COUNTRY.CountryId=TEACHER.CountryId

The above mentioned command applies a Full Outer Join on the two tables, since the common attribute is CountryId; we have applied the join on Countryid itself.

We would get the following table as a result on application of Full Outer Join:

CountryIdCountryNameStateidStatename
1ChinaNULLNULL
2 PH 01PASAY
2 PH 02MAKATI
3USANULLNULL
NULLNULL03NAVOTAS
NULLNULL04 PATEROS

This Join results in all the rows. We get NULL (Empty), when there is no match.

Joins are essentially important to work with tables in SQL and the above mentioned description genuinely elaborate the usage of each one of them.