teleren/devto huggingface dataset:
Laravel Vite avec Bootstrap 5 sur nouvelle app
Published: 2023-07-04 19:27:38

**Installez Boostrap et ses dépendances**
`npm i --save-dev sass bootstrap @popperjs/core`

**Configurer Vite**
Modifiez le fichier **_vite.config.js_** à la racine de votre App comme suit :
```
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
  plugins: [
    laravel({
      input: [
        'resources/sass/app.scss',
        'resources/js/app.js',
      ],
      refresh: true,
    }),
  ],
});
```

**Importer Bootstrap**
Supprimez le dossier **_resources/css/app.css_** installé par défaut.
Créez le dossier **_resources/sass_**, puis créez le fichier **_resources/sass/app.scss_** et éditez le comme suit :
`@import "bootstrap/scss/bootstrap";`

Editez **_resources/js/bootstrap.js_** comme suit :
(PopperJs sera importé automatiquement)
```
import * as bootstrap from 'bootstrap'
window.bootstrap = bootstrap; 
```

**Compiler**
La compilation se fait comme sous Laravel-mix :
`npm run dev`

Pour la mise en production
`npm run build`

Le mode "dev" génère un fichier "hot" dans /Public 
Le mode "build" génèrera les éléments dans /public/build pour la mise en production du site.

**Importer les "assets" CSS/JS dans les vues avec la directive Blade @vite**

`@vite(['resources/sass/app.scss', 'resources/js/app.js'])`

_Bien sûr, il est préférable de ne l'importer qu'une seule fois dans un fichier "Layouts"_

**Pour finir**
Et un petit coup de nettoyage pour bien repartir :
```
php artisan clear-compiled &&
php artisan auth:clear-resets &&
php artisan cache:clear &&
php artisan config:clear &&
php artisan route:clear &&
php artisan view:clear
composer dump-autoload
```
Unintended updates in mvc With Example
Tags: webdev, programming, aspdotnet
Published: 2023-07-04 19:14:56

In MVC, unintended updates can occur when binding user-submitted data to a model without properly validating and restricting the properties that can be updated. This can lead to potential security risks, such as over-posting attacks or unintended modifications of sensitive data.

To prevent unintended updates, you should implement measures to validate and restrict the properties that can be updated. One common approach is to use view models that only contain the properties specifically required for editing, instead of binding directly to the actual model.

Here's an example to illustrate the issue and the solution:

Assume you have a `Person` model with properties such as `Id`, `Name`, `Age`, and `IsAdmin`.

```csharp
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsAdmin { get; set; }
}
```

Consider a scenario where you have an edit form for updating the person's name and age. Without proper precautions, a malicious user could modify the HTML form and include an additional field for the `IsAdmin` property, thereby attempting to grant themselves administrative privileges.

To mitigate this risk, you can use a view model that includes only the properties that should be updated.

```csharp
public class PersonEditViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
```

Then, modify the controller to use the view model:

```csharp
public class PersonController : Controller
{
    // GET: /Person/Edit/{id}
    public ActionResult Edit(int id)
    {
        var person = GetPersonById(id);

        // Map the relevant properties from the model to the view model
        var viewModel = new PersonEditViewModel
        {
            Id = person.Id,
            Name = person.Name,
            Age = person.Age
        };

        return View(viewModel);
    }

    // POST: /Person/Edit/{id}
    [HttpPost]
    public ActionResult Edit(PersonEditViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            var person = GetPersonById(viewModel.Id);

            // Update only the properties that should be allowed
            person.Name = viewModel.Name;
            person.Age = viewModel.Age;

            // Save the changes to the database

            return RedirectToAction("Details", new { id = person.Id });
        }

        // If there are validation errors, redisplay the edit form
        return View(viewModel);
    }
}
```

By using a view model, you limit the properties that can be updated to only those explicitly defined in the view model. This prevents unintended updates of sensitive properties like `IsAdmin`. When mapping the view model back to the actual model, you update only the allowed properties.

Using this approach ensures that only the intended properties can be modified, reducing the risk of unintended updates and potential security vulnerabilities.
Meetup #53: "Hablemos de Excepciones"
Tags: android, meetup
Published: 2023-07-04 18:58:21

🗣️ Expositor: **David Hackro** 🇲🇽 (síguelo en [Twitter](https://twitter.com/davidHackro))
🗒️ Tema: "**Hablemos de Excepciones**" ([video](https://www.youtube.com/live/m_4dBs28aYI?feature=share&t=250) | [diapositivas](https://docs.google.com/presentation/d/1XNk8HOEK-L-KSQy8Ro_MrCL-5McwfDZSNEXdKYu7Xtk))

Como suele ocurrir en el mundo del software, ciertas funcionalidades de un lenguaje pueden ser beneficiosas o causar problemas, dependiendo de cómo y cuándo las uses. Y las _excepciones_ no son la excepción. En este meetup, David nos responde preguntas como:

- ¿Cuál es la diferencia entre un Error y una Excepción?
- ¿Evitar o propagar excepciones?
- ¿Cuales son errores comunes al momento de propagar excepciones?

Mira la grabación en nuestro canal de Youtube:

{% embed https://www.youtube.com/live/m_4dBs28aYI?feature=share&t=250 %}

| | |
|-|-|
|![David preparándose para la charla](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5rirj6i6bh8mkq5352j.jpeg)|![El equipo solucionando problemas técnicos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/givivgj5ul5b3tws6aji.jpeg)|

## Links relevantes

- [Diapositivas](https://docs.google.com/presentation/d/1XNk8HOEK-L-KSQy8Ro_MrCL-5McwfDZSNEXdKYu7Xtk)
- Artículos:
  - [Resilient Use Cases with kotlin.Result, Coroutines, and Annotations](https://www.droidcon.com/2022/04/06/resilient-use-cases-with-kotlin-result-coroutines-and-annotations/)
  - [Diferencia entre Throwable y Excepcion](https://github.com/Kotlin/kotlinx.coroutines/issues/1814
https://stackoverflow.com/questions/2274102/difference-between-using-throwable-and-exception-in-a-try-catch/2274116#2274116)
  - [Art of Clean Code Handling](https://blog.devgenius.io/art-of-clean-code-error-handling-7951587eac98)
  - [Diferencia entre error y excepción](https://www.differencebetween.com/difference-between-exception-and-vs-error/)
  - [Clean Code and the art of exception handling](https://www.toptal.com/abap/clean-code-and-the-art-of-exception-handling)
Should I use .io or .dev for my first web development portfolio website?
Tags: help, webdev, beginners
Published: 2023-07-04 18:55:25

Title is self explanatory but I'm building my first full stack web developer portfolio and I can't decide whether I should use .io or .dev. Maybe it's worth mentioning that .io costs 3x as much as .dev, but I'd pay for it if it makes sense to do so.

Which one is the best (if there is such thing) and why?

Also, .com is already taken so I cant use it.
A Deep Dive article into React form validation using a popular library 'Formik"
Tags: react, reactjsdevelopment, javascript
Published: 2023-07-04 18:53:48

Formik is a popular form library for React that provides a convenient way to handle form validation. While Yup is often used as the validation schema with Formik, it is not a strict requirement. You can perform form validation without Yup by leveraging Formik's validation capabilities and custom validation logic.

Check out my article on hashnode to get a basic understanding of how to work with formik

https://duke.hashnode.dev/a-deep-dive-article-into-react-form-validation-using-a-popular-library-formik
How To Combine Coverage From Cypress (E2E And Component Test) And Jest In An Nx Project
Tags: angular, nx, testing, cypress
Published: 2023-07-04 18:49:06

Coverage helps us see what part of our app is covered with tests and can help us determine if new code is covered in pull requests with tools such as SonarQube or Coveralls. My recommended testing strategy for testing Angular apps is to focus on covering the use cases with Cypress component tests and add some unit tests around edge cases and calculation while having a few e2e tests as a smoke test thus needing to combine test coverage from all these different sources to get a clear picture of what code is tested.

Getting coverage for Jest comes out of the box but setting up coverage with Cypress E2E and component tests and merging the coverage results all together requires more manual intervention and this blog post is covering how to get coverage from the different testing techniques and combine the coverage results into one report in an Nx project.

You can read the post [here](https://christianlydemann.com/how-to-combine-coverage-from-cypress-e2e-and-component-test-and-jest-in-an-nx-project/).
Difference between updatemodel and tryupdatemodel with Example
Tags: webdev, programming, aspdotnet, productivity
Published: 2023-07-04 18:44:52

In ASP.NET MVC, both `UpdateModel` and `TryUpdateModel` are used to update the model object with the values submitted from a form or user input. However, there is a crucial difference between them.

1. `UpdateModel`:
The `UpdateModel` method binds the incoming data to the model object and throws an exception if there are any model binding errors. This means that if there are validation errors or if the model properties cannot be successfully bound, it will result in an exception, potentially leading to an unhandled error.

Example of using `UpdateModel`:

```csharp
public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        var person = GetPersonById(id);

        // Update the model object with the form values using UpdateModel
        UpdateModel(person, form);

        // Perform any necessary operations (e.g., saving to the database)

        // Redirect to a different action or view
        return RedirectToAction("Details", new { id = person.Id });
    }
}
```

2. `TryUpdateModel`:
The `TryUpdateModel` method is an improvement over `UpdateModel` as it does not throw an exception in case of model binding errors. Instead, it returns a boolean value indicating whether the model binding was successful or not. If there are errors, you can handle them explicitly in your code without causing an unhandled exception.

Example of using `TryUpdateModel`:

```csharp
public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        var person = GetPersonById(id);

        // Try to update the model object with the form values
        if (TryUpdateModel(person, form))
        {
            // Model binding succeeded, perform any necessary operations (e.g., saving to the database)

            // Redirect to a different action or view
            return RedirectToAction("Details", new { id = person.Id });
        }
        else
        {
            // Model binding failed, handle the errors
            // You could show an error message or render the form view again with validation messages.
            // For example:
            ModelState.AddModelError("", "Error: Failed to update the person details.");
            return View("Edit", person);
        }
    }
}
```

In this example, if the model binding using `TryUpdateModel` fails, we add a model-level error to the `ModelState` using `ModelState.AddModelError`, and then we return the "Edit" view, showing the form with the error message.

Using `TryUpdateModel` is generally considered safer than `UpdateModel`, as it helps prevent unhandled exceptions caused by model binding errors. Always prefer `TryUpdateModel` (or its asynchronous counterpart, `TryUpdateModelAsync`) over `UpdateModel` when updating models from user input.
{Day1} function
Tags: javascript, beginners, codenewbie
Published: 2023-07-04 18:35:00

Dear Dev,


Today I learned about functions in JavaScript. It's still a bit confusing, but I'll try to explain what I understood.

In JavaScript, a function is a block of code that performs a specific task.

It can be reused multiple times throughout a program.
 
Functions are defined using the function keyword followed by a name and a set of parentheses.

Any parameters that the function requires are listed inside the parentheses.


***I tried to build a calculator!***


```javascript
let num1 = prompt("Choose a first number");
num1 = parseInt(num1);
document.getElementById("num1-el").textContent = num1;
```
I started by creating a variable num1, assigned a prompt with the question 'Choose a first number,' and then converted the var num1 to a number.
Then came the discovery of document.getElementById!
Wow, I was so excited to learn how to communicate with the DOM!

So, I assigned the content of num1 to the element #num1-el.

Then I did the same thing for the var num2.

```javascript
let num2 = prompt("Choose a second number");
num2 = parseInt(num2);
document.getElementById("num2-el").textContent = num2;
```

This is html for num1 and num2

```html
    <span id="num1-el">0</span>
    <span id="num2-el">0</span>
```

Next, I created buttons in my HTML for addition, subtraction, division, and multiplication.

```html
   <div class="box-btn">
       <button onclick="add()">Add</button>
       <button onclick="subtract()">Subtract</button>
       <button onclick="divide()">Divide</button>
       <button onclick="multiply()">Multiply</button>
   </div>
```

I have already inserted the name of my function in the onclick.

```javascript
function add() {
  let result = num1 + num2;
  sumEl.textContent = num1 + " + " + num2 + " = " + result;
}
```

It was so simple! I remember during my lessons, I used to wonder, 'What is the real purpose of a function?'
I didn't understand... 
But now, with this simple project, I am finally starting to understand the importance of functions

---

I finally understood how DOM elements communicate with my JavaScript script.

I can finally see the light at the end of the tunnel!

So, I'm going to improve my code and build simple little projects, like a quote generator! Because I can see in my mind how it's possible to do it :)

And all of this thanks to the resources available online on the internet!


There are plenty of courses, videos, tutorials accessible for free or at a cost.
But yes, if we have motivation, anything is possible :)


I feel a little embarrassed to show my project (but I'll still share the link :p) because it's a 'newbie project,' but one day I will be capable of creating beautiful projects in JavaScript

My Calculator:

https://github.com/Lysdora/TurtleCalc-Express



I'm also going to write a fiction story featuring a World of Warcraft hero and functions, similar to this story (my first story) :

https://murloc-craft.medium.com/murloc-the-noob-vs-the-variable-f2506812a0cf
Updatemodel function in MVC with example
Tags: webdev, programming, productivity, aspdotnet
Published: 2023-07-04 18:32:20

In the context of the Model-View-Controller (MVC) design pattern, the `UpdateModel` function is used to update the model object with the values submitted from a form or user input. It is typically used in the controller to bind the incoming data to the model.

Here's an example of how the `UpdateModel` function can be used in an MVC application:

Let's assume we have a simple model called `Person` with two properties: `Name` and `Age`.

```csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
```

In the controller, you might have an action method to handle a form submission:

```csharp
public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        // Get the person object from the database using the provided ID
        var person = GetPersonById(id);

        // Update the model object with the form values using UpdateModel
        UpdateModel(person, form);

        // At this point, the person object will have its properties updated
        // with the values submitted from the form.

        // Perform any necessary operations (e.g., saving to the database)

        // Redirect to a different action or view
        return RedirectToAction("Details", new { id = person.Id });
    }
}
```

In the above example, the `Edit` action method receives the form values as a `FormCollection` object, which contains all the submitted data. The `UpdateModel` function is called with the `person` object and the `form` collection.

The `UpdateModel` function will match the keys in the `form` collection with the properties in the `person` object based on their names and update the corresponding property values. This binding process is performed automatically by the MVC framework.

After the `UpdateModel` function call, the `person` object will have its properties updated with the submitted values. You can then perform any necessary operations (e.g., saving the changes to the database) and redirect to a different action or view.

Note: In newer versions of ASP.NET MVC, the `UpdateModel` method has been deprecated in favor of the `TryUpdateModel` or `TryUpdateModelAsync` methods, which provide better control over the binding process and protect against over-posting attacks.
Mapping asp.net request data to controller action simple parameter types
Tags: webdev, programming, aspdotnet, devops
Published: 2023-07-04 18:26:22

In ASP.NET, you can map incoming request data to controller action parameters in several ways, depending on the parameter type. Here are some common parameter types and how you can map them:

1. Simple Types (e.g., int, string):
   For simple types, ASP.NET automatically maps query string or form data values with matching parameter names. For example, if your action method has a parameter named "id" of type int, ASP.NET will automatically map the value of "id" from the query string or form data to that parameter.

   Example:
   ```csharp
   public IActionResult MyAction(int id)
   {
       // Use the 'id' parameter value
       return View();
   }
   ```

2. Model Binding:
   ASP.NET provides model binding to automatically map complex types from request data. Model binding can be used for parameters of custom types or complex objects. It maps request data based on parameter names and property names in the object.

   Example:
   ```csharp
   public IActionResult MyAction(MyModel model)
   {
       // Use properties of the 'model' object
       return View();
   }
   ```

3. FromQuery Attribute:
   You can use the `[FromQuery]` attribute to explicitly indicate that a parameter should be bound from the query string, even for simple types.

   Example:
   ```csharp
   public IActionResult MyAction([FromQuery] string name)
   {
       // Use the 'name' parameter value from the query string
       return View();
   }
   ```

4. FromForm Attribute:
   The `[FromForm]` attribute allows you to explicitly indicate that a parameter should be bound from form data, even for simple types.

   Example:
   ```csharp
   public IActionResult MyAction([FromForm] int age)
   {
       // Use the 'age' parameter value from the form data
       return View();
   }
   ```

These are some common ways to map request data to controller action parameters in ASP.NET. You can choose the appropriate method based on the parameter type and the source of the data (query string, form data, etc.).
Form Collection in Asp.net with View Examples
Tags: aspdotnet, webdev, programming, assembly
Published: 2023-07-04 18:11:51


1. Create a new ASP.NET MVC project in Visual Studio.

2. In the `HomeController`, add an action method to handle the form submission:

```csharp
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult SubmitForm(FormCollection form)
    {
        // Access form values using the FormCollection
        string name = form["Name"];
        string email = form["Email"];

        // Do something with the form values

        return View("Result");
    }
}
```

3. In the `Views` folder, create a new folder called `Home` and add a new view file called `Index.cshtml` inside it. Update the view file with the following code:

```html
@{
    ViewBag.Title = "Form Collection Example";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Form Collection Example</title>
</head>
<body>
    <h2>Submit Form</h2>
    @using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post))
    {
        <div>
            <label>Name:</label>
            <input type="text" name="Name" />
        </div>
        <div>
            <label>Email:</label>
            <input type="email" name="Email" />
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    }
</body>
</html>
```

4. Create another view file called `Result.cshtml` inside the `Home` folder. Update the view file with the following code:

```html
@{
    ViewBag.Title = "Form Submitted";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <title>Form Submitted</title>
</head>
<body>
    <h2>Form Submitted Successfully</h2>
    <p>Name: @ViewBag.Name</p>
    <p>Email: @ViewBag.Email</p>
</body>
</html>
```

In this example, the `Index` action method renders the `Index.cshtml` view, which contains a form with two input fields for name and email. When the form is submitted, the `SubmitForm` action method is called, and the form values are captured using the `FormCollection` object. You can access individual form values using their names as keys in the `form` collection.

After processing the form values, the action method returns the `Result` view, passing the values through `ViewBag` for display.

Note: Using the `FormCollection` object directly is not the recommended approach for form processing. It's better to use model binding with strongly typed models. However, this example demonstrates the usage of the `FormCollection` object specifically, as requested.