Monday, 2 May 2022

Get started with Swashbuckle and ASP.NET Core

https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-6.0&tabs=visual-studio

  • Swagger
  • SwaggerGen
  • SwaggerUI


SwaggerUI 

https://localhost:7147/swagger




SwaggerEndpoint
https://localhost:7147/swagger/v1/swagger.json







Package installation
Install the package on the exiting TodoAPI project



API info and description

By changing Program.cs, you can make root url to point to Swagger.

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty;
    });
}

BEFORE:



AFTER:



XML Comments etc seems not working when I tried.




Tutorial: Call an ASP.NET Core web API with JavaScript

https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-6.0

Some quotes from the tutorial page

How to call an ASP.NET Core web API with JavaScript, using the Fetch API.

The fetch function returns a Promise object, which contains an HTTP response represented as a Response object. 

A common pattern is to extract the JSON response body by invoking the json function on the Response object.


Get a list

const uri = 'api/todoitems';

let todos = [];


function getItems() {

    fetch(uri)

        .then(response => response.json())

        .then(data => _displayItems(data))

        .catch(error => console.error('Unable to get items.', error));

}


By changing launchSettings.json >> launchUrl remove, the project chagnes from API project to js html project.

Before :



After:


Add an item

fetch(uri, {

    method: 'POST',


Update

fetch(`${uri}/${itemId}`, {

  method: 'PUT',

Sunday, 1 May 2022

Tutorial: Create a web API with ASP.NET Core

 https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio

  • Create a web API with controllers - TodoContext.cs added, Scaffold controller added
  • Create a minimal web API
  • Web API with MongoDB
  • Web API with JavaScript
  • Backend for mobile
  • Publish to Azure API Management

Create with controller

httprepl supports debugging.


After posting an item, you can see it.


After posting another item, you can see the Location header.

TodoItemsController.cs >> return CreatedAtAction() returns this response with Location header.


Prevent over-posting - interesting,  The subset of a model is usually referred to as a Data Transfer Object (DTO), input model, or view model.


When using httprepl, make sure you connect first. Otherwise PUT operation does not work.
PUT Success - 204 no content



PUT Error - 405 method not allowed

PUT Error - 400 bad request




Before DTO (Data Transfer Object)

Before DTO (Data Transfer Object)


How to update code to use DTO

        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItemDTO>>> GetTodoItems()
        {
            //return await _context.TodoItems.ToListAsync();
            return await _context.TodoItems
                .Select(x => ItemToDTO(x))
                .ToListAsync();
        }


Friday, 29 April 2022

ASP.Net model to winhost prod database

The tutorial ASP.NET Core MVC has content:

  • Get started
  • Add a controller
  • Add a view
  • Add a model - scaffold movie pages (updates/creates files)
  • Work with a database
  • Controller actions and views
  • Add search
  • Add a new field
  • Add validation
  • Examine Details and Delete

 https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio

Add a model

Below codes create database table based on model

Add-Migration InitialCreate

Update-Database







Make sure appsetrtings.json has correct connection string to winhost to create / update table.


After running localhost, Program.cs run code block and inserts default 4 records into database.


using (var scope = app.Services.CreateScope())

{

    var services = scope.ServiceProvider;

    SeedData.Initialize(services);

}

Add a new field 

Add-Migration Rating

Update-Database


<questions>

        private readonly MvcMovieContext _context;

q. when this context is setup?

ans. Controller >> right click >> add >> New scaffolded item ...

<next>

How to deploy

https://stackify.com/how-to-deploy-asp-net-core-to-iis/

What's ASP.NET Core?

https://stackify.com/asp-net-core-features/


Local database

Use ServerName = (LocalDb)\MSSQLLocalDB

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b75bef7e-13f3-4658-8d43-9df12ab4c320/connecting-localdb-using-sql-server-management-studio-express?forum=sqlexpress


Friday, 17 September 2021

Axios POST not working for image upload

I found that this guy had also $_FILES['image'][tmp_name] empty issue:

https://stackoverflow.com/questions/62604318/files-is-empty-when-sending-a-post-request-using-axios-in-reactjs

In my case, it was 2MB upload_max_filesize in php.ini. Please see PHP - empty $_POST and $_FILES - when uploading larger files I pulled out my hair for 2 hours. Nothing wrong with Axios. I didn't need to specify headers.















Thursday, 16 September 2021

Sunday, 29 August 2021

Image Uploader - React

I'm trying  to upload image with React. Source code copied from:

https://www.geeksforgeeks.org/file-uploading-in-react-js/

Image upload required post API call eg, App.js#line39

axios.post("http://localhost:8000/api/imageupload", formData).then(resp => {
console.log(resp.data);
});

API is Lumen. Source code is named scr-webservice.

  • source code directory: ~/my/scr-webservice.
  • source code tool: phpstorm
  • url: http://localhost:8000/
  • Database is currently (29/8/21) pointing to winhost by ~/my/scr-webservice/.env
  • database tool: phpstorm


Post call:

http://localhost:8000/api/imageupload


There is a very good video of image upload using React.js:

https://www.youtube.com/watch?v=XeiOnkEI7XI

Talks about axios post call at video 4:20, but using Firebase, which takes another learning time.

Found another good site talking about React and Lumen connection:



Made it work to return result from API call.





I could xdebug as well. But only from Postman. I couldn't make XDebug work ...
  • From: react website localhost:3000
  • To: API localhost:8000 (LUmen)





XDEBUG from react site to API code didn't work. (in spite of correct settings)




Image passed from Postman.


Saved in uploads folder. and shows correctly!