teleren/devto huggingface dataset:
Different Ways in Error Handling In API Development Using Asp.NET Core
Tags: webdev, programming, aspdotnet, opensource
Published: 2023-06-14 14:39:37

In ASP.NET Core, there are several ways to handle errors in API development. Here are some common approaches:

1. **Use Exception Middleware**: ASP.NET Core provides a middleware pipeline that allows you to catch and handle exceptions globally. You can create a custom middleware component that catches exceptions and returns appropriate error responses. This approach centralizes error handling and keeps your controller code clean.

2.** Handle Exceptions in Controllers**: Each API endpoint can have its own error handling logic. You can use try-catch blocks within your controller actions to catch exceptions and return specific error responses. This approach gives you fine-grained control over error handling for individual endpoints.

3. **Use the `[ApiController]` Attribute**: When you decorate your controller class with the `[ApiController]` attribute, ASP.NET Core automatically handles model validation errors and returns appropriate responses. This built-in behavior helps you handle common input validation errors without writing explicit error handling code.

4. **Use Filters**: ASP.NET Core provides action filters and exception filters that can be used to handle errors. Action filters allow you to perform pre- and post-processing of action methods, while exception filters specifically catch and handle exceptions. You can create custom filters to handle various types of errors.

5. **Global Error Handling with `UseExceptionHandler`**: In the `Configure` method of your `Startup` class, you can use the `UseExceptionHandler` method to configure a global error handler. This method catches unhandled exceptions and executes a specified error handling middleware.

6. **Use Problem Details**: The ASP.NET Core framework includes the `ProblemDetails` class, which represents detailed error information in a standardized format. You can return `ProblemDetails` objects as error responses from your API, providing consistent error information to clients.

7. **Logging**: Logging is an essential part of error handling. ASP.NET Core provides a built-in logging framework that allows you to log exceptions and other relevant information. By logging errors, you can gather valuable data for troubleshooting and monitoring purposes.

These are just a few approaches to error handling in ASP.NET Core API development. The choice of error handling technique depends on the specific requirements of your application and the level of control you need over error handling.
A blog documenting my journey with Node.js
Published: 2023-06-14 14:25:59

Welcome to my Node.js journey ! In this blog, I will be documenting my learning experiences and insights as I dive into the world of Node.js.

Since nodejs is too vast and I can't possibly write down every single thing I will be learning I'll be listing down every important thing I learn or things that I am likely forget in future. Hope this series of blogs will help you in your journey of learning nodejs

The first thing one comes across while learning nodejs is modules and file systems. 

The very first module that I came across was "fs"(File Systems) module which is basically used to read and write files. Although there are many others functions of this modules but these are the two basic ones.

Suppose there is a file index.html and I have to read its content on the terminal using nodejs . First I have to import the readFile function from fs module using `import {readFile} from "fs/promises"`. The readFile is an asynchronous function which takes two arguments (exact path of the file which is to be read , the encodings of the file to be read ) . If you don't specify the any encodings it's just going to display the buffer data.Generally we use 'utf-8' as a standard value for encodings which in simple words means convert the data into string. 


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wjao6srw54srqytyawg.png)

Since I am using ES6 syntax my files are .mjs not .js, feel free to use `require()` if you are using commonJS file. If you are using ES6 syntax you won't have an access to __dirname. There are many ways to resolve this issue ,this is just one of them. Inside new URl the first argument is the file name and second argument is `import.meta.url`. This is nothing but the exact path of the file. If you run this action.mjs file in your terminal using `node action.mjs`. The result will look something like this .


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vip6mj0wrb09riwhsrgm.png)

There you go now you can read any file in the string format using the above code in your terminal . If you are curious what will be the output look like if you don't specify any encodings 


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9swz77t2cv6nm17e6srx.png)

Sure enough the code will work the same way if you just write 
`const template = await readFile('index.html','utf-8')`, but it's always a good practice to mention the exact the path using `import.meta.url`.

Now the next function is writeFile, just like the readFile writeFile is also an asynchronous function. This function is used to write the contents of some file on another or a new file .

import the function first using `import {writeFile} from "fs/promises" `


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pttfqb2oz1bcmp3pl08u.png)

On running this script a new `template.html` file will be created and all the contents stored inside template variable will be written inside template.html.

This is just a start there will be many posts regarding nodejs following from here.

That's all for this blog post.And a big thanks to whoever is reading till this point.
Remove Entry and Picker borders in .NET MAUI
Tags: dotnet, dotnetmaui, ios, android
Published: 2023-06-14 14:24:30

If you are developing a .NET MAUI app that uses form elements such as entries and pickers, you might want to apply a custom design for those fields. However, by default Android & iOS make the form fields display the form elements UI following their platform design guidelines. In this post, I will show you how to remove those borders for Android & iOS using a simple custom handler and some native code. Let’s get started!

**Update:** This article has been updated to support .NET MAUI 8+.

---

### Create a static class FormHandler
```csharp
using Microsoft.Maui;
using System.Drawing;

#if IOS
using UIKit;
using Foundation;
#endif

#if ANDROID
using Microsoft.Maui.Controls.Compatibility.Platform.Android;
#endif

namespace DemoApp.Handlers;

public static class FormHandler
{
    public static void RemoveBorders()
    {
        Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("Borderless", (handler, view) =>
        {
#if ANDROID
            handler.PlatformView.Background = null;
            handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
            handler.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
#elif IOS
            handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
            handler.PlatformView.Layer.BorderWidth = 0;
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
        });

        Microsoft.Maui.Handlers.PickerHandler.Mapper.AppendToMapping("Borderless", (handler, view) =>
        {
#if ANDROID
            handler.PlatformView.Background = null;
            handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
            handler.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
#elif IOS
            handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
            handler.PlatformView.Layer.BorderWidth = 0;
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
        });
    }
}

```

> On the code shared above, in addition to remove the borders, I set the background color of the form elements to transparent on both platforms, so you get the freedom to style them as needed. 



#### Register the handler
On the MauiProgram.cs file register the handler
`FormHandler.RemoveBorders();`

### Conclusion
In .NET MAUI it is really cool how easy you can implement a static method that allows to execute code based on each platform. Of course if you prefer to avoid the declarative conditionals you can always use the _.ios.cs_ and _.android.cs_ file class naming convention.

Thanks for reading! Follow me on Twitter **[@ivictorhugo](https://twitter.com/ivictorhugo)**
dbForge Edge Review 2023: Will this Save You from Mixed SQL Database Headaches?
Tags: database, dbforge, dbforgeedge, dbforgestudio
Published: 2023-06-14 14:18:09

dbForge Edge is a unique set of comprehensive database IDEs. Let's find out more about its functionality, features and benefits - https://www.opengeocode.org/2023/05/30/dbforge-edge-review-2023-will-this-save-you-from-mixed-sql-database-headaches/

![dbforge-edge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nn5dgfpu5dvnl6j9hhc3.jpg)
json-service-editor
Tags: javascript, node, express, editor
Published: 2023-06-14 14:00:11

If you are planning to create a front-end DEMO for demonstration, but do not have support from server personnel; If you are developing a front-end page but the server is not well developed; So `json-service-editor` is a good choice!

git: [https://github.com/zhuqingyv/json-service-editor](https://github.com/zhuqingyv/json-service-editor)
npm: [https://www.npmjs.com/package/json-service-editor](https://www.npmjs.com/package/json-service-editor)

**Quick Start**
``` shell
npm install json-service-editor -g
```

`.json-service.json`

``` json

{
  "url": "src/demo.json",
  "port": 3000
}
```
run 
``` shell
json-service-editor
```
Now you have started a local JSON read and write service with port 3000.

## Interface

Here are the most basic read and write interfaces get and set


Get JSonValue

``` typescript
fetch('http://localhost:3000/get/demo.json', {
  method: 'GET',
})
```

Set JSonValue

``` typescript
fetch('http://localhost:3000/set/demo.json', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ message: 'hello world!' }),
})
```
## Options

There are two types of configuration files provided here, one is. json service. json and the other is. json service. js. If both js and json configurations exist in the running directory, the js script takes precedence.



|  Option |  .json-service.js   | .json-service.json | description |
|  ----  | ----  | ----  | ----  |
|  url | ✅ | ✅ | File relative path |
| port  | ✅ | ✅ | Service port |
| service  | ✅ | ❌ | Custom Service Configuration |

Here are some code demonstrations:
``` js
module.exports = () => {
  const url = "src/demo.json";
  const port = 3110;
  return {
    url,
    port,
    service: {
      '/post': {
        methods: 'post',
        handle: ({ json, params, res, req }) => {
          res.json(200, { message: 'pass!' });
        }
      },

      '/get': {
        methods: 'get',
        handle: ({ json, params, res, req }) => {
          res.json(200, { message: 'pass!' });
        }
      }
    }
  }
};
```

## Simpler Browser API (Base on [FetchAPI](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API))


First:
``` npm install json-service-editor ```

Code:

``` typescript
import JsonServiceEditorCore from 'json-service-editor';

const serviceSDK = new JsonServiceEditorCore({
  baseUrl: 'http://localhost:3000',
  fileName: 'demo.json'
});

const { getValue, setValue } = serviceSDK;

getValue(
  // success callback
  () => {},
  // fail callback
  () => {}
)

```
"Surviving Cancer, Building Code, Thriving in Tech": CodeNewbie Podcast S24E6
Tags: codenewbie, career, podcast, beginners
Published: 2023-06-14 14:00:00

In S24E6 of the CodeNewbie Podcast, @saronyitbarek talks with software engineer, [Stacey Graham](https://twitter.com/Staceyluvstech), about leveling up in your career after facing a major life hardship.

{% embed https://www.codenewbie.org/podcast/surviving-cancer-building-code-thriving-in-tech %}

Stacey fell in love with technology in the 7th grade in her first computer class and from there, her curiosity for technology began. She is passionate about coding and loves learning and problem-solving collaboratively in teams. Stacey enjoys building high-quality applications in JavaScript, React, and Angular and enjoys working with RESTful APIs, Node.js, and Express.js. Stacey gets most excited about being challenged while coding and believes there is always something new to learn in web development.

- [Listen on Apple Podcasts](https://podcasts.apple.com/us/podcast/codenewbie/id919219256?i=1000616965153)

- [Listen on Spotify](https://open.spotify.com/episode/4FN0BPF2eqd9AQckt6mehO?si=af582b356c514650)

Or, listen wherever you normally get your podcasts!

***

**Make sure to subscribe to the CodeNewbie podcast if you haven't yet!**

Happy coding!💜
Conda equivalent of `pipenv run`
Tags: conda, python, cli, pipenv
Published: 2023-06-14 13:54:24


If you wish to run a single command using a Python environment created with `conda` (i.e., you don't want to `activate` the environment first), you can use the following command:

```
conda run -n your_env_name some_command
```

E.g.:

```
conda run -n webprojects python --version
```

or:

```
conda run -n datascience jupyter lab
```

Make sure that you are using the `-n` argument; `pipenv` does not require specifying an "optional" argument, hence it took me some time to get this working (i.e., it works just like `pipenv run jupyter lab`).

References:

- https://docs.conda.io/projects/conda/en/latest/commands/run.html

- https://stackoverflow.com/questions/57327966/what-is-the-syntax-for-invoking-conda-run-from-an-anaconda-installation-on-win

---

Cover Photo by <a href="https://unsplash.com/@thomasoldenburger?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Thomas Oldenburger</a> on <a href="https://unsplash.com/photos/TeOc4DVDsH4?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
API Versioning In ASP.NET Core With Three Different Ways
Tags: webdev, programming, aspdotnet, javascript
Published: 2023-06-14 13:49:31

In ASP.NET Core, there are multiple ways to handle API versioning. Here are three commonly used approaches:

1. URL-based Versioning:
   With this approach, the version number is included in the URL of the API endpoint. For example:
   ```
   https://api.example.com/v1/products
   https://api.example.com/v2/products
   ```
   You can achieve URL-based versioning by configuring the routing system in ASP.NET Core to include the version in the route template. This can be done using the `MapRoute` or `MapControllerRoute` methods in the `Startup.Configure` method.

2. Query Parameter-based Versioning:
   In this approach, the version number is specified as a query parameter in the API URL. For example:
   ```
   https://api.example.com/products?version=1
   https://api.example.com/products?version=2
   ```
   To implement query parameter-based versioning, you can use the `ApiVersion` attribute on your controllers or actions and configure the routing system to include the version as a query parameter.

3. Header-based Versioning:
   This approach involves specifying the version number in a custom header of the HTTP request. For example:
   ```
   GET /products HTTP/1.1
   Host: api.example.com
   X-API-Version: 1
   ```
   To implement header-based versioning, you can create a custom versioning policy and apply it to your controllers or actions using attributes like `ApiVersion` and `ApiVersionReader`.

It's important to note that these are just a few approaches to API versioning in ASP.NET Core, and there are other techniques available as well. The choice of versioning strategy depends on your specific requirements and preferences.
The MySQL Pivot Table Hero Guide to Simple Pivots
Tags: mysql, pivottable, dbforge, dbforgestudio
Published: 2023-06-14 13:48:22

Get ready to unleash the MySQL Pivot Table hero in you! In this article, we tried to keep the code examples as simple as possible. And if you're in a hurry, we'll show you a tool that will help you pivot data at lightning speed - https://technoroll.org/the-mysql-pivot-table-hero-guide-to-simple-pivots/

![mysql pivot table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2au23j1npp116gdgk4v.jpg)
CS50: Semana 7 | Lab: Músicas
Tags: braziliandevs, sql
Published: 2023-06-14 13:39:24

Retornando com o laboratório de SQL do CS50.

## Semana 7: SQL

Um dos motivos que eu considero o CS50 um curso bem completo, principalmente para quem está começando é por conta desta semana.

Se você estiver procurando formas de estudar SQL, provavelmente vai encontrar pela internet diversos locais oferecendo caminhos turvos demais pra algo que poderia ser de forma mais simples e é exatamente isso que essa semana faz. Te dá algo simples, mas poderoso e a partir daí, só tende a crescer conforme a prática.

## Laboratório: Songs

É uma atividade onde você vai praticar o uso do banco de dados SQLite e a partir do conhecimento adquirido na aula ira escrever queries SQL para responder diferentes perguntas pedindo para filtrar e selecionar diferentes tipos de dados em uma ou mais tabelas.

## Resolução

### 1.Escreva uma query SQL para retornar uma lista com todas as músicas presentes no banco de dados.

```sql
SELECT name FROM songs;
```

### 2.Escreva uma query SQL para retornar uma lista com as músicas em ordem de tempo.

```sql
SELECT name FROM songs ORDER BY tempo;
```

### 3.Escreva uma query SQL para retornar uma lista com o top 5 em termos de duração, em ordem decrescente.

```sql
SELECT name FROM songs ORDER BY tempo DESC LIMIT 5;
```

### 4.Escreva uma query SQL que retorne uma lista que tenha os termos "danceability", "energy", e "valence" maior que 0.75

```sql
SELECT name FROM songs
WHERE (danceability > 0.75
AND energy > 0.75
AND valence > 0.75);
```

### 5.Escreva uma query SQL que retorne a média de energia de todas as músicas

```sql
SELECT AVG(energy) FROM songs;
```

### 6.Escreva uma query SQL que retorne a lista com todas as músicas que são do Post Malone

```sql
SELECT songs.name FROM songs JOIN artists ON songs.artists_id = artists.id WHERE artists.name = 'Post Malone';
```

### 7.Escreva uma query SQL que retorne a média de energia das músicas que são do Drake.

```sql
SELECT AVG(songs.energy) FROM songs
JOIN artists
ON songs.artist_id = artist.id
WHERE artist.name = 'Drake';
```

### 8.Escreva uma query SQL que retorne as músicas que incluem participações de outros artistas.

```sql
SELECT name FROM songs WHERE name LIKE '%feat%';
```

## Conclusão

Esse laboratório é bem simples e muito divertido de se fazer, é quase um trabalho de investigação e obter o resultado pretendido traz uma satisfação enorme de entender como algo tão simples também é tão poderoso.

Se estiver com dúvidas, só deixar seu comentário aí embaixo.

Até a próxima!
🌟 AI TOOLS TO GENERATE YOUR NEXT BUSINESS IDEA WORTH $100K 🌟
Tags: beginners, discuss, productivity, career
Published: 2023-06-14 13:30:00

🌟 Start your business in next 24 hours 🌟

Wanna skip the long blog?
VISIT THE TOOLS
[Business AI](https://www.aiforme.wiki/ai/tools/Business%20Idea%20Generator%20AI)
[Business Idea Generator](https://www.aiforme.wiki/ai/tools/Business%20Idea%20Generator)
[Dime A Dozen](https://www.aiforme.wiki/ai/tools/Dime%20A%20Dozen)

1️⃣ Business Idea Generator AI - Unleash the power of AI to generate your next winning business idea. Customize your business model, revenue model, technology, and industry preferences, and let the AI generate personalized ideas that have the potential to reach $100K in value. 💡🚀💼

2️⃣ Business Idea Generator - Get personalized business ideas in seconds with the help of AI. This tool leverages AI algorithms to provide you with unique and tailored business ideas that align with your interests, skills, and market trends. 🌟💼💡

3️⃣ Dime A Dozen - Validate Your Business Idea In Seconds
Dime A Dozen uses AI to instantly analyze and validate your business idea, providing insights on its potential for success and highlighting areas to watch out for. Benefit from AI-driven market research, launch and scaling strategies, and even receive guidance on raising capital. 💰🚀🔍

VISIT THE TOOLS
[Business AI](https://www.aiforme.wiki/ai/tools/Business%20Idea%20Generator%20AI)
[Business Idea Generator](https://www.aiforme.wiki/ai/tools/Business%20Idea%20Generator)
[Dime A Dozen](https://www.aiforme.wiki/ai/tools/Dime%20A%20Dozen)

Discover your next business idea worth $100K with the help of these remarkable AI tools. 

Explore more about each tool in the comments and embark on your entrepreneurial journey! 

#AItools #BusinessIdeation #Entrepreneurship 🌟💡💼
Node.js VS Deno.js, Which one is better
Tags: node, deno, javascript, backend
Published: 2023-06-14 13:18:39

Node.js and Deno are both JavaScript runtime environments that allow you to run JavaScript code outside of a web browser. However, they have some differences in terms of their design, features, and usage. Here's an overview of Node.js and Deno:

Node.js:

- Node.js is a mature and widely adopted JavaScript runtime built on the Chrome V8 JavaScript engine.
- It provides an event-driven, non-blocking I/O model that makes it well-suited for building scalable and efficient server-side applications.
- Node.js has a large and active ecosystem of packages and libraries available through its package manager, npm.
- It has been around since 2009 and has gained significant popularity for developing web servers, APIs, command-line tools, and other server-side applications.
- Node.js uses CommonJS modules for organizing and importing code modules.

**Deno:**

- Deno is a newer JavaScript runtime created by the same individual who created Node.js (Ryan Dahl).
- It aims to provide a secure and modern runtime environment for JavaScript and TypeScript.
- Deno has built-in support for TypeScript, allowing developers to write and run TypeScript code without additional setup.
- It provides a more secure default environment by strictly controlling file system access, network access, and other permissions.
- Deno has its own package manager called Deno Registry, which allows you to import modules directly from URLs.
- It also supports ES modules (ECMAScript modules) for importing code modules.
- Deno places a strong emphasis on simplicity, developer productivity, and modern JavaScript/TypeScript features.


Both Node.js and Deno have their own strengths and use cases. Node.js has a mature ecosystem, extensive community support, and is well-suited for building scalable server-side applications. On the other hand, Deno offers a more secure and modern runtime environment with built-in TypeScript support and a focus on developer productivity. The choice between Node.js and Deno depends on your specific requirements and preferences.