Dexter  Goodwin

Dexter Goodwin

1619081220

TypeScript Beginners: Here Are The 5 Areas You Must Master

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master

TypeScript is popular.

A recent survey carried out by Stack Overflow places TypeScript as the second most loved language after Rust. That’s up 8 places on the 2019 rating.

What’s more, you’re our in good company if you are using it. TypeScript is at the moment used by Microsoft, Asana, Lyft, Slack, all Angular 2+ developers, many React & Vue.js developers, and thousands of other companies, so it has been and continues to be battle-tested.

I’m a believer in the 80/20 rule and think a case can be made that having a great understanding of 20% of the language can allow you to solve 80% of the daily problems you come across.

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master that make up that 20%.

1. Nail down the Types

2. The joy of Enums

3. When you need a little more flexibility

4. Scaling our new found control

5. Bringing it all together with a look at functions

#coding #javascript #programming #typescript

What is GEEK

Buddha Community

TypeScript Beginners: Here Are The 5 Areas You Must Master

Migrating From Jira Server: Guide, Pros, And Cons

February 15, 2022 marked a significant milestone in Atlassian’s Server EOL (End Of Life) roadmap. This was not the final step. We still have two major milestones ahead of us: end of new app sales in Feb 2023, and end of support in Feb 2024. In simpler words, businesses still have enough time to migrate their Jira Server to one of the two available products – Atlassian Cloud or Atlassian DC. But the clock is ticking. 

Jira Cloud VS Data Center

If we were to go by Atlassian numbers, 95% of their new customers choose cloud. 

“About 80% of Fortune 500 companies have an Atlassian Cloud license. More than 90% of new customers choose cloud first.” – Daniel Scott, Product Marketing Director, Tempo

So that’s settled, right? We are migrating from Server to Cloud? And what about the solution fewer people talk about yet many users rely on – Jira DC? 

Both are viable options and your choice will depend greatly on the needs of your business, your available resources, and operational processes. 

Let’s start by taking a look at the functionality offered by Atlassian Cloud and Atlassian DC.

FeatureAtlassian CloudAtlassian Data Center
Product PlansMultiple plansOne plan
BillingMonthly and annualAnnual only
Pricing modelPer user or tieredTiered only
SupportVarying support levels depending on your plan: Enterprise support coverage is equivalent to Atlassian’s Data Center Premier Support offeringVarying support levels depending on the package: Priority Support or Premier Support (purchased separately)
Total Cost of OwnershipTCO includes your subscription fee, plus product administration timeTCO includes your subscription fee and product administration time, plus: costs related to infrastructure provisioning or IaaS fees (for example, AWS costs) planned downtime time and resources needed for software upgrades
Data encryption services✅❌
Data residency services✅❌
Audit loggingOrganization-level audit logging available via Atlassian Access (Jira Software, Confluence) 

Product-level audit logs (Jira Software, Confluence)
Advanced audit logging
Device securityMobile device management support (Jira Software, Confluence, Jira Service Management)

Mobile application management (currently on the roadmap)
Mobile device management support (Jira Software, Confluence, Jira Service Management) 
Content security✅❌
Data Storage limits2 GB (Free)

250 GB (Standard)

Unlimited storage (Premium and Enterprise)
No limits
PerformanceContinuous performance updates to improve load times, search responsiveness, and attachments

Cloud infrastructure hosted in six geographic regions to reduce latency
 
Rate limitingCDN supports Smart mirrors and mirror farms (Bitbucket)
Backup and data disaster recoveryJira leverages multiple geographically diverse data centers, has a comprehensive backup program, and gains assurance by regularly testing their disaster recovery and business continuity plans. 

Backups are generated daily and retained for 30 days to allow for point-in-time data restoration
❌
Containerization and orchestration✅Docker images

Kubernetes support (on the roadmap for now)
Change management and upgradesAtlassian automatically handles software and security upgrades for you Sandbox instance to test changes (Premium and Enterprise) 

Release track options for Premium and Enterprise (Jira Software, Jira Service Management, Confluence)
❌
Direct access to the databaseNo direct access to change the database structure, file system, or other server infrastructure

Extensive REST APIs for programmatic data access
Direct database access
Insights and reportingOrganization and admin insights to track adoption of Atlassian products, and evaluate the security of your organization.Data Pipeline for advanced insightsConfluence analytics

Pros and cons of Jira Cloud

When talking about pros and cons, there’s always a chance that a competitive advantage for some is a dealbreaker for others. That’s why I decided to talk about pros and cons in matching pairs. 

Pro: Scalability is one of the primary reasons businesses are choosing Jira Cloud. DC is technically also scalable, but you’ll need to scale on your own whereas the cloud version allows for the infrastructure to scale with your business. 

Con: Despite the cloud’s ability to grow with your business, there is still a user limit of 35k users. In addition to that, the costs will grow alongside your needs. New users, licenses, storage, and computing power – all come at an additional cost. So, when your organization reaches a certain size, migrating to Jira DC becomes more cost-efficient.

Pro: Jira takes care of maintenance and support for you.

Con: Your business can suffer from unpredicted downtime. And there are certain security risks.  

Pro: Extra bells and whistles: 

  • Sandbox: Sandbox is a safe environment system admins can use to test applications and integrations before rolling them out to the production environment. 
  • Release tracks: Admins can be more flexible with their product releases as they can access batch and control cloud releases. This means they’ll have much more time to test existing configurations and workflows against a new update. 
  • Insight Discovery: More data means more ways you can impact your business or product in a positive, meaningful way. 
  • Team Calendars: This is a handy feature for synchronization and synergy across teams. 

Con: Most of these features are locked behind a paywall and are only available to either Premium and Enterprise or only Enterprise licenses (either fully or through addition of functionality. For example, Release tracks are only available to Enterprise customers.) In addition, the costs will grow as you scale the offering to fit your growing needs. 

Pros and cons of Jira Data Center

I’ll be taking the same approach to talking about the pros and cons as I did when writing about Atlassian Cloud. Pros and cons are paired. 

Pro: Hosting your own system means you can scale horizontally and vertically through additional hardware. Extension of your systems is seamless, and there is no downtime (if you do everything correctly). Lastly, you don’t have to worry about the user limit – there is none. 

Con: While having more control over your systems is great, it implies a dedicated staff of engineers, additional expenses on software licensing, hardware, and physical space. Moreover, seamless extension and 0% downtime are entirely on you.

Pro: Atlassian has updated the DC offering with native bundled applications such as Advanced Roadmaps, team calendars and analytics for confluence, insight asset management, and insight discovery in Jira Service Management DC.

Con: Atlassian has updated their pricing to reflect these changes. And you are still getting fewer “bells and whistles” than Jira Cloud users (as we can see from the feature comparison). 

Pro: You are technically safer as the system is supported on your hardware by your specialists. Any and all Jira server issues, poor updates, and downtime are simply not your concern.
 

Con: Atlassian offers excellent security options: data encryption in transit and rest, to mobile app management, to audit offerings and API token controls. In their absence, your team company has to dedicate additional resources to security. 

Pro: Additional benefits from Atlassian, such as the Priority Support bundle (all DC subscriptions have this option), and the Data center loyalty discount (more on that in the pricing section.)

The Pricing

Talking about pricing of SaaS products is always a challenge as there are always multiple tiers and various pay-as-you go features. Barebones Jira Cloud, for instance, is completely free of charge, yet there are a series of serious limitations. 

Standard Jira Cloud will cost you an average of $7.50 per user per month while premium cranks that price up to $14.50. The Enterprise plan is billed annually and the cost is determined on a case-by-case basis. You can see the full comparison of Jira Cloud plans here. And you can use this online calculator to learn the cost of ownership in your particular case.

50 UsersStandard (Monthly/Annually)Premium (Monthly/Annually)
Jira Software$387.50 / $3,900$762.50 / $7,650
Jira Work Management$250 / $2,500❌
Jira Service Management$866.25 / $8,650$2,138.25 / $21,500
Confluence$287.50 / $2,900$550 / $5,500
100 UsersStandard (Monthly/Annually)Premium (Monthly/Annually)
Jira Software$775 / $7,750$1,525 / $15,250
Jira Work Management$500 / $5,000❌
Jira Service Management$1,653.75 / $16,550$4,185.75 / $42,000
Confluence$575 / $5,750$1,100 / $11,000
500 UsersStandard (Monthly/Annually)Premium (Monthly/Annually)
Jira Software$3,140 / $31,500$5,107.50 / $51,000 
Jira Work Management$1,850 / $18,500❌
Jira Service Management$4,541.25 / $45,400$11,693.25 / $117,000
Confluence$2,060 / $20,500$3,780 / $37,800

Please note that these prices were calculated without any apps included. 

Jira Data Center starts at $42,000 per year and the plan includes up to 500 users. If you are a new client and are not eligible for any discounts*, here’s a chart that should give you an idea as to the cost of ownership of Jira DC. You can find more information regarding your specific case here.

UsersCommercial Annual PlanAcademic Annual Plan
1-500USD 42,000USD 21,000
501-1000USD 72,000USD 36,000
1001-2000USD 120,000USD 60,000
Confluence for Data Center  
1-500USD 27,000USD 13,500
501-1000USD 48,000USD 24,000
1001-2000USD 84,000USD 42,000
Bitbucket for Data Center  
1-25USD 2,300USD 1,150
26-50USD 4,200USD 2,100
51-100USD 7,600USD 3,800
Jira Service Management for Data Center  
1-50USD 17,200USD 8,600
51-100USD 28,600USD 14,300
101-250USD 51,500USD 25,750

*Discounts:

  • Centralized per-user licensing allows users access all enterprise instances with a single Enterprise license.
  • There’s an option for dual licensing for users who purchase an annual cloud subscription with 1,001 or more users. In this case, Atlassian extends your existing server maintenance or Data Center subscription for up to one year at a 100% discount.
  • There are certain discounts for apps depending on your partnership level.
  • Depending on your situation, you may qualify for several Jira Data Center discount programs:

What should be your User Migration strategy?

Originally, there were several migration methods: Jira Cloud Migration Assistant, Jira Cloud Site Import, and there was an option to migrate via CSV export (though Jira actively discourages you from using this method). However, Jira’s team has focused their efforts on improving the Migration Assistant and have chosen to discontinue Cloud Site Import support.

Thanks to the broadened functionality of the assistant, it is now the only go-to method for migration with just one exception. If you are migrating over 1000 users and you absolutely need to migrate advanced roadmaps – you’ll need to rely on Site Import. At least for now, as Jira is actively working on implementing this feature in their assistant.

Here’s a quick comparison of the options and their limitations.

 FeaturesLimitations
Cloud Migration AssistantApp migration

Existing data on a Cloud Site is not overwritten

You choose the projects, users, and groups you want to migrate

Jira Service Management customer account migration

Better UI to guide you through the migration

Potential migration errors are displayed in advance

Migration can be done in phases reducing the downtime

Pre- and post-migration reports
You must be on a supported self-managed version of Jira
Site ExportCan migrate Advanced RoadmapsApp data is not migrated

Migration overrides existing data on the Cloud site

Separate user importUsers from external directories are not migrated

No choice of data you want or don’t want migrated

There’s a need to split attachments into up to 5GB chunks

Higher risks of downtime due to the “all or nothing” approach

You must be on a supported self-managed version of Jira

Pro tip: If you have a large base of users (above 2000), migrate them before you migrate projects and spaces. This way, you will not disrupt the workflow as users are still working on Server and the latter migration of data will take less time. 

How to migrate to Jira Cloud

Now that we have settled on one particular offering based on available pricing models as well as the pros and the cons that matter the most to your organization, let’s talk about the “how”. 

How does one migrate from Jira Server to Jira Cloud?

Pre-migration checklist

Jira’s Cloud Migration Assistant is a handy tool. It will automatically review your data for common errors. But it is incapable of doing all of the work for you. That’s why we – and Atlassian for that matter – recommend creating a pre-migration checklist.   

Smart Checklist will help you craft an actionable, context-rich checklist directly inside a Jira ticket. This way, none of the tasks will be missed, lost, or abandoned. 

Below is an example of how your migration checklist will look like in Jira. 

Feel free to copy the code and paste it into your Smart Checklist editor and you’ll have the checklist at the ready. 

# Create a user migration plan #must
> Please keep in mind that Jira Cloud Migration Assistant migrates all users and groups as well as users and groups related to selected projects
- Sync your user base
- Verify synchronization
- External users sync verification
- Active external directory verification
## Check your Jira Server version #must
- Verify via user interface or Support Zip Product Version Verification
> Jira Migration Assistant will not work unless Jira is running on a supported version
## Fix any duplicate email addresses #must
- Verify using SQL
> Duplicate email addresses are not supported by Jira Cloud and therefore can't be migrated with the Jira Cloud Migration Assistant. To avoid errors, you should find and fix any duplicate email addresses before migration. If user information is managed in an LDAP Server, you will need to update emails there and sync with Jira before the migration. If user information is managed locally, you can fix them through the Jira Server or Data Center user interface.
## Make sure you have the necessary permissions #must
- System Admin global permissions on the Server instance
- Exists in the target Cloud site
- Site Administrator Permission in the cloud
## Check for conflicts with group names #must
- Make sure that the groups in your Cloud Site don't have the same names as groups in Server
> Unless you are actively trying to merge them
- Delete or update add-on users so not to cause migration issues
- Verify via SQL
## Update firewall allowance rules #must
- None of the domains should be blocked by firewall or proxy
## Find a way to migrate apps #must
- Contact app vendors
## Check public access settings #must
- Projects
- Filters
- Filters
- Boards
- Dashboards
## Review server setup #mst
- at least 4gb Heap Allocation
- Open Files limit review
- Verify via support zip
## Check Server timezone #must for merging Cloud sites
- Switch to UTC is using any other timezone
> Add a system flag to the Jira Server instance -Duser.timezone=UTC as outlined in this article about updating documentation to include timezone details.
## Fix any duplicate shared configuration
## Storage limits
## Prepare the server instance
- Check data status
- All fields have value and are not null
-Any archived projects you wish to migrate are activated
## Prepare your cloud site
- Same Jira products enabled
- Same language
- User migration strategy
## Data backup
- Backup Jira Server site
- Backup Cloud site
## Run a test migration
- Done
## Notify Jira support
- Get in touch with Jira migration support

Use backups

On the one hand, having all of your Jira products on a server may seem like a backup in and of itself. On the other hand, there are data migration best practices we should follow even if it’s just a precaution. No one has ever felt sorry for their data being too safe. 

In addition, there are certain types of migration errors that can be resolved much faster with having a backup at hand. 

  1. Jira Server Database backup: this step creates a DB backup in an XML format.
    1. Log in with Jira System Admin permissions
    2. Go to system -> Import and Export -> Backup Manager -> Backup for server.
    3. Click the create Backup for server button. 
    4. Type in the name for your backup. 
    5. Jira will create a zipped XML file and notify you once the backup is ready. 

  1. Jira Cloud Backup: This backup also saves your data in an XML format. The process is quite similar to creating a Jira Server backup with the only difference taking place on the Backups page.
    1. Select the option to save your attachments, logos, and avatars.
    2. Click on the Create backup button. 

  1. As you can see, the Cloud backup includes the option to save attachments, avatars, and logos. This step should be done manually when backing up Server data.
    1. Create a Zip archive for this data
    2. Make sure it follows the structure suggested by Atlassian

Migrating your Jira instance to the cloud via the Jira Migration Assistant

Jira Cloud Migration Assistant is a free add-on Atlassian recommends using when migrating to the cloud. It accesses and evaluates your apps and helps migrate multiple projects. 

Overall, the migration assistant offers a more stable and reliable migration experience. It automatically checks for certain errors. It makes sure all users have unique and valid emails, and makes sure that none of the project names and keys conflict with one another. 

This is a step-by-step guide for importing your Jira Server data backup file into Jira Cloud.

  1. Log into Jira Cloud with admin permissions
  2. Go to System -> Import and Export -> External System Import
  3. Click on the Jira Server import option

  1. Select the backup Zip you have created 
  2. Jira will check the file for errors and present you with two options: enable or disable outgoing mail. Don’t worry, you will be able to change this section after the migration process is complete. 
  3. Then you will be presented with an option to merge Jira Server and Jira Cloud users
    1. Choosing overwrite will replace the users with users from the imported files
    2. The merge option will merge groups with the same name
    3. Lastly, you can select the third option if you are migrating users via Jira’s assistant
  4. Run the import

How do you migrate Jira Server into Jira DC?

Before we can proceed with the migration process, please make sure you meet the following prerequisites:

  1. Make sure you are installing Jira on one of the supported platforms. Atlassian has a list of supported platforms for Jira 9.1.
  2. Make sure the applications you are using are compatible with Jira DC. You will be required to switch to datacenter-compatible versions of your applications (they must be available). 
  3. Make sure you meet the necessary software and hardware requirements:
    1. You have a DC license
    2. You are using a supported database, OS, and Java version
    3. You are using OAuth authentication if your application links to other Atlassian products

Once you are certain you are ready to migrate your Jira Server to Jira Data Center, you can proceed with an installation that’s much simpler than one would expect.

  1. Upgrade your apps to be compatible with Jira DC
  2. Go to Administration -> Applications -> Versions and licenses
  3. Enter your Jira DC License Key
  4. Restart Jira

That’s it. You are all set. Well, unless your organization has specific needs such as continuous uptime, performance under heavy loads, and scalability, in which case you will need to set up a server cluster. You can find out more about setting up server clusters in this guide.  

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Dexter  Goodwin

Dexter Goodwin

1619081220

TypeScript Beginners: Here Are The 5 Areas You Must Master

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master

TypeScript is popular.

A recent survey carried out by Stack Overflow places TypeScript as the second most loved language after Rust. That’s up 8 places on the 2019 rating.

What’s more, you’re our in good company if you are using it. TypeScript is at the moment used by Microsoft, Asana, Lyft, Slack, all Angular 2+ developers, many React & Vue.js developers, and thousands of other companies, so it has been and continues to be battle-tested.

I’m a believer in the 80/20 rule and think a case can be made that having a great understanding of 20% of the language can allow you to solve 80% of the daily problems you come across.

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master that make up that 20%.

1. Nail down the Types

2. The joy of Enums

3. When you need a little more flexibility

4. Scaling our new found control

5. Bringing it all together with a look at functions

#coding #javascript #programming #typescript

TypeScript Beginners: Here Are The 5 Areas You Must Master

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master

TypeScript is popular.

A recent survey carried out by  Stack Overflow places TypeScript as the second most loved language after Rust. That’s up 8 places on the 2019 rating.

What’s more, you’re our in good company if you are using it. TypeScript is at the moment used by Microsoft, Asana, Lyft, Slack, all Angular 2+ developers, many React & Vue.js developers, and  thousands of other companies, so it has been and continues to be battle-tested.

I’m a believer in the 80/20 rule and think a case can be made that having a great understanding of 20% of the language can allow you to solve 80% of the daily problems you come across.

Together, with some help from our favourite heroes and villains in the Marvel Universe let’s look at the 5 key areas to master that make up that 20%.

1. Nail down the Types

2. The joy of Enums

3. When you need a little more flexibility

4. Scaling our new found control

5. Bringing it all together with a look at functions

#coding #javascript #programming #typescript

Saul  Alaniz

Saul Alaniz

1659727800

Hangfire en ASP.NET Core 3.1

En este artículo, aprendamos sobre Hangfire en ASP.NET Core 3.1 y cómo integrarlo con sus aplicaciones principales. Una tarea de programación común a la que nos enfrentamos regularmente es ejecutar trabajos en segundo plano. Y ejecutar estos trabajos correctamente sin estropear su código no es una tarea fácil, pero tampoco es difícil. Solía ​​trabajar con los servicios de Windows para programar varias tareas dentro de mi aplicación C#. Luego, me encontré con esta biblioteca casi increíble: Hangfire, y nunca me fui.

Trabajos en segundo plano en ASP.NET Core

Básicamente, los trabajos en segundo plano son aquellos métodos o funciones que pueden tardar mucho tiempo en ejecutarse (cantidad de tiempo desconocida). Estos trabajos, si se ejecutan en el subproceso principal de nuestra aplicación, pueden o no bloquear la interacción del usuario y puede parecer que nuestra aplicación .NET Core se ha bloqueado y no responde. Esto es bastante crítico para las aplicaciones orientadas al cliente. Por lo tanto, tenemos trabajos en segundo plano, similares a los subprocesos múltiples, estos trabajos se ejecutan en otro subproceso, lo que hace que nuestra aplicación parezca bastante asíncrona.

También deberíamos tener la posibilidad de programarlos en un futuro cercano para que esté completamente automatizado. La vida de un desarrollador sería muy dura sin estas increíbles posibilidades.

¿Qué es Hangfire?

Hangfire es una biblioteca de código abierto que permite a los desarrolladores programar eventos en segundo plano con la mayor facilidad. Es una biblioteca altamente flexible que ofrece varias funciones necesarias para hacer que la tarea de programación de trabajos sea pan comido. Hangfire en ASP.NET Core es la única biblioteca que no puede perderse.

Integración de Hangfire en ASP.NET Core 3.1

Para este tutorial, tengamos un escenario específico para que podamos explicar Hangfire y su potencial completo. Digamos que estamos desarrollando una API que se encarga de enviar correos al Usuario para diferentes escenarios. Tiene más sentido explicar Hangfire de esta manera. Hangfire es una de las bibliotecas más fáciles de adaptar, pero también muy poderosa. Es uno de los paquetes que ayuda por completo a crear aplicaciones de forma asíncrona y desacoplada.

Como mencioné anteriormente, Hangfire usa una base de datos para almacenar los datos del trabajo. Usaremos la base de datos del servidor MSSQL en esta demostración. Hangfire crea automáticamente las tablas requeridas durante la primera ejecución.

Configuración del proyecto ASP.NET Core

Comenzaremos creando un nuevo proyecto ASP.NET Core con la plantilla API seleccionada. Ahora cree un controlador de API vacío. Llamémoslo HangfireController. Estoy usando Visual Studio 2019 Community como mi IDE y POSTMAN para probar las API.

Instalación de los paquetes Hangfire

Instalando el único paquete que necesitarías para configurar Hangfire.

Install-Package Hangfire

Configuración de Hangfire

Una vez que haya instalado el paquete, ahora estamos listos para configurarlo para que sea compatible con nuestra aplicación ASP.NET Core API. Este es un paso bastante sencillo, además, una vez que instale el paquete, se le mostrará un Léame rápido que le muestra el paso para completar la configuración.

Navigate to Startup.cs / ConfigureServices so that it looks like the below code snippet.
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(x => x.UseSqlServerStorage("<connection string>"));
services.AddHangfireServer();
services.AddControllers();
}

Explicación.
Línea #3 Agrega el servicio Hangfire a nuestra aplicación. También hemos mencionado el almacenamiento que se utilizará, el servidor MSSQL, junto con la cadena/nombre de conexión.
La línea n.º 4 en realidad enciende el servidor Hangfire, que es responsable del procesamiento de trabajos.

Una vez hecho esto, vayamos al método Configurar y agregue la siguiente línea.

app.UseHangfireDashboard("/mydashboard");

Explicación.
Lo que hace esta línea es que nos permite acceder al panel de hangfire en nuestra aplicación ASP.NET Core. El tablero estará disponible yendo a /URL de mi tablero. Iniciemos la aplicación.

Esquema de la base de datos Hangfire

Cuando inicia su aplicación ASP.NET Core por el momento, Hangfire verifica si tiene un esquema de Hangfire asociado disponible en su base de datos. Si no, creará un montón de tablas para ti. Así es como se vería su base de datos.

hangfire dbschema Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Panel de Hangfire

Después de cargar la aplicación, vaya a <localhost>/mydashboard. Podrá ver el panel de control de Hangfire.

Hangfire en ASP.NET Core

Desde el tablero podrás monitorear los trabajos y sus estados. También le permite activar manualmente los trabajos disponibles. Esta es la característica ÚNICA que diferencia a Hangfire de otros programadores. Tablero incorporado. ¿Cuan genial es eso? La captura de pantalla anterior es la de la descripción general del panel. Exploremos también las otras pestañas.

Pestaña de trabajos.

Todos los trabajos que están disponibles en el almacén de datos (nuestro servidor MSSQL) se enumerarán aquí. Obtendrá una idea completa del estado de cada trabajo (En cola, Exitoso, Procesando, Fallido, etc.) en esta pantalla.

trabajos hangfire Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Pestaña Reintentos.

Los trabajos tienden a fallar de vez en cuando debido a factores externos. En nuestro caso, nuestra api intenta enviar un correo al usuario, pero hay un problema de conexión interna, lo que hace que el trabajo no se ejecute. Cuando falla un trabajo, Hangfire continúa intentándolo hasta que pasa. (configurable)

hangfire vuelve a intentar Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Pestaña de trabajos recurrentes.

¿Qué sucede si necesita enviar por correo el uso de su factura mensualmente? Esta es la característica principal de Hangfire, trabajos recurrentes. Esta pestaña le permite monitorear todos los trabajos configurados.

hangfire recurrente Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Pestaña Servidores.

Recuerde, al configurar Hangfire en la clase Startup.cs, lo hemos mencionado. services.AddHangfireServer().. Esta es la pestaña donde muestra todos los Hangfire Server activos. Estos servidores son responsables de procesar los trabajos. Digamos que no ha agregado los servicios. AddHangfireServer() en la clase de inicio, aún podría agregar trabajos Hangfire a la base de datos, pero no se ejecutarán hasta que inicie un servidor Hangfire.

servidor hangfire Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Protección del panel Hangfire

Esta es una característica bastante obvia. Dado que el tablero puede exponer datos muy confidenciales como nombres de métodos, valores de parámetros, ID de correo electrónico, es muy importante que protejamos/restringamos este punto final. Hangfire, listo para usar, hace que el tablero sea seguro al permitir solo solicitudes locales. Sin embargo, puede cambiar esto implementando su propia versión de IDashboardAuthorizationFilter . Si ya implementó la Autorización en su API, puede implementarla para Hangfire. Consulte estos pasos para asegurar el tablero.

Tipos de trabajo en Hangfire

Los trabajos en segundo plano en ASP.NET Core (o digamos cualquier tecnología) pueden ser de muchos tipos según los requisitos. Repasemos los tipos de trabajo disponibles con Hangfire con la implementación adecuada y la explicación en nuestro proyecto ASP.NET Core API. Vamos a codificar.

Despedir y olvidar trabajos

Los trabajos de disparar y olvidar se ejecutan  solo una vez  y casi  inmediatamente  después de la creación. Crearemos nuestro primer trabajo de fondo. Abre el controlador Hangfire que habíamos creado. Crearemos un punto final POST que dé la bienvenida a un usuario con un correo electrónico (idealmente). Añade estos códigos.

[HttpPost]
[Route("welcome")]
public IActionResult Welcome(string userName)
{
var jobId = BackgroundJob.Enqueue(() => SendWelcomeMail(userName));
return Ok($"Job Id {jobId} Completed. Welcome Mail Sent!");
}

public void SendWelcomeMail(string userName)
{
//Logic to Mail the user
Console.WriteLine($"Welcome to our application, {userName}");
}

Explicación.
La línea #5 almacena JobId en una variable. Puede ver que en realidad estamos agregando un trabajo en segundo plano representado por una función ficticia SendWelcomeMail. El JobId se vuelve a publicar más tarde en el Panel de control de Hangfire. Cree la aplicación y ejecútela. Vamos a probarlo con Postman.

hangfire faf postman Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Tenga en cuenta la URL y cómo estoy pasando el nombre de usuario al controlador. Una vez que lo ejecute, obtendrá nuestra respuesta requerida. “Id. de trabajo 2 completado. ¡Correo de bienvenida enviado!”. Ahora veamos el tablero de Hangfire.

hangfire faf dash Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

En la pestaña Correcto, puede ver el recuento de trabajos completados. También puede ver los detalles de cada trabajo, similar a la captura de pantalla anterior. Todos los parámetros y nombres de funciones se exponen aquí. ¿Quiere volver a ejecutar este trabajo con los mismos parámetros? Presiona el botón Volver a poner en cola. Vuelve a agregar su trabajo en la cola para que Hangfire lo procese. Sucede casi de inmediato.

Trabajos retrasados

Ahora, qué pasa si queremos enviar un correo a un usuario, no inmediatamente, sino después de 10 minutos. En tales casos, utilizamos trabajos retrasados. Veamos su implementación, después de lo cual lo explicaré en detalle. En el mismo controlador, agregue estas líneas de código. Es bastante similar a la variante anterior, pero le introducimos un factor de retraso.

[HttpPost]
[Route("delayedWelcome")]
public IActionResult DelayedWelcome(string userName)
{
var jobId = BackgroundJob.Schedule(() => SendDelayedWelcomeMail(userName),TimeSpan.FromMinutes(2));
return Ok($"Job Id {jobId} Completed. Delayed Welcome Mail Sent!");
}

public void SendDelayedWelcomeMail(string userName)
{
//Logic to Mail the user
Console.WriteLine($"Welcome to our application, {userName}");
}

Explicación.
La línea #5 programó el trabajo en un período de tiempo definido, en nuestro caso son 2 minutos. Eso significa que nuestro trabajo se ejecutará 2 minutos después de que Postman haya llamado a la acción. Abramos Postman de nuevo y probemos.

hangfire retrasó al cartero Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Puede ver que recibimos la respuesta esperada de Postman. Ahora. vuelva rápidamente al Panel de control de Hangfire y haga clic en la pestaña Trabajos/programados. Diría que el trabajo se ejecutará en un minuto. Ahí estás para. Ha creado su primer trabajo programado usando Hangfire con facilidad.

hangfire retraso dash Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

trabajos recurrentes

Nuestro Cliente tiene una suscripción a nuestro servicio. Obviamente, tendríamos que enviarle un recordatorio sobre el pago o la factura en sí. Esto llama la necesidad de un trabajo recurrente, donde puedo enviar correos electrónicos a mis clientes mensualmente. Esto es compatible con Hangfire mediante el programa CRON.
¿Qué es CRON? CRON es una utilidad basada en el tiempo que puede definir intervalos de tiempo. Veamos cómo lograr tal requisito.

[HttpPost]
[Route("invoice")]
public IActionResult Invoice(string userName)
{
RecurringJob.AddOrUpdate(() => SendInvoiceMail(userName), Cron.Monthly);
return Ok($"Recurring Job Scheduled. Invoice will be mailed Monthly for {userName}!");
}

public void SendInvoiceMail(string userName)
{
//Logic to Mail the user
Console.WriteLine($"Here is your invoice, {userName}");
}

La línea #5 establece claramente que estamos tratando de agregar/actualizar un trabajo recurrente, que llama a una función tantas veces como lo define el esquema CRON. Aquí enviaremos la factura al cliente mensualmente el primer día de cada mes. Ejecutemos la aplicación y cambiemos a Postman. Estoy ejecutando este código el 24 de mayo de 2020. Según nuestro requisito, este trabajo debe despedirse el 1 de junio de 2020, que es dentro de 7 días. Vamos a ver.

hangfire cartero recurrente Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Entonces, esto funcionó. Pasemos a Hangfire Dashboard y vayamos a la pestaña Trabajos recurrentes.

hangfire recurrente dash Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

¡Perfecto! Funciona como excepción. Puede pasar por varios esquemas CRON aquí que pueden coincidir con sus requisitos. Aquí hay una pequeña documentación agradable para comprender cómo se usan varias expresiones CRON.

Continuaciones

Este es un escenario más complicado. Permítanme tratar de mantenerlo muy simple. Un usuario decide darse de baja de su servicio. Después de que confirme su acción (tal vez haciendo clic en el botón para cancelar la suscripción), nosotros (la aplicación) tenemos que cancelar la suscripción del sistema y enviarle un correo de confirmación después de eso también. Entonces, el primer trabajo es realmente cancelar la suscripción del usuario. El segundo trabajo es enviar un correo confirmando la acción. El segundo trabajo debe ejecutarse solo después de que el primer trabajo se haya completado correctamente. Obtener el escenario?

[HttpPost]
[Route("unsubscribe")]
public IActionResult Unsubscribe(string userName)
{
var jobId = BackgroundJob.Enqueue(() => UnsubscribeUser(userName));
BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine($"Sent Confirmation Mail to {userName}"));
return Ok($"Unsubscribed");
}

public void UnsubscribeUser(string userName)
{
//Logic to Unsubscribe the user
Console.WriteLine($"Unsubscribed {userName}");
}

Explicación.
Línea #5 El primer trabajo que realmente contiene lógica para eliminar la suscripción del usuario.
Línea #6 Nuestro segundo trabajo que continuará después de que se ejecute el primer trabajo. Esto se hace pasando el Id. de trabajo del trabajo principal a los trabajos secundarios.

Iniciemos la aplicación y vayamos a Postman.

hangfire coont postman Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

hangfire coont dash Hangfire en ASP.NET Core 3.1 - Trabajos en segundo plano simplificados

Ahora, vaya al Tablero y verifique el trabajo exitoso. Verá 2 nuevos trabajos ejecutados en el orden exacto que queríamos. Eso es todo por este tutorial. Espero que tengan claro estos conceptos y les resulte fácil integrar Hangfire en las aplicaciones ASP.NET Core.

Resumen

En esta guía detallada, hemos repasado los conceptos de trabajos en segundo plano, características e implementación de Hangfire en aplicaciones ASP.NET Core y varios tipos de trabajos en Hangfire. El código fuente utilizado para demostrar este tutorial está publicado en GitHub. Te dejo el enlace a continuación para que lo consultes. ¿Tienes experiencia con Hangfire? ¿Tienes alguna consulta/sugerencia? Siéntase libre de dejar a continuación en la sección de comentarios. ¡Feliz codificación!

Fuente: https://codewithmukesh.com/blog/hangfire-in-aspnet-core-3-1/

#aspdotnet #hangfire