Tuesday, December 10, 2019

MongoDB CRUD with Asp.Net Core Razor Pages - Simple Tutorial




This year I had the occasion to meet the MEAN stack, M coming from the Mongo DB NoSQL database. But, during my studies with Asp.Net Core, I am thinking about a database solution for future projects, outside the MS SQL realm. Might be suitable for side projects ? Who knows, I might give a try.

This is how I met Mongo DB, and produced this tutorial, with the plan that I might want to use MongoDB with .Net in the future.

Prerequisites:
1. Basic Asp.Net Core 2.2 Razor pages knowledge, check at least the first two tutorials mentioned here: https://mydev-journey.blogspot.com/2019/11/razor-pages-not-for-shaving.html
2. Check the introductory MongoDB API tutorial from Microsoft: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio
3. My tutorial is based on point 2, just that it extends also to the front-end using Razor Pages, and then adds search function.
4. Please open an account on https://cloud.mongodb.com/ - it's free!
5. Download code from: https://drive.google.com/open?id=1FeihPX-qJz7b_zXraG32uHqoJLDTRcUr
6. Application LIVE online: http://mongotutorial.azurewebsites.net/ListBooks
7. Further study with C# from Mongo cloud provider: https://www.mongodb.com/blog/post/quick-start-csharp-and-mongodb--update-operation


A. After creating an account on the mongo cloud provider, create database on the Mongo Cloud, and a collection on the database, as below:

    "BooksCollectionName": "Books",
    "DatabaseName": "BookstoreDb"

Then, get the connection string from the Mongo Cloud, from connect application in below screen:
    "ConnectionString": "mongodb+srv://username:password@clusterxxx",


Connection string is inserted in the appsettings.json file.
B. You can replicate the tutorial on point 2 by following the material from Microsoft which I highly recommend, or simply take my zipped Repo from link.

Base class is the Book class, where I added an annotation for the Price to accept only currency values.
a. install Nuget Package: MongoDB.Driver
b. Book Class looks like:
insert
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
///
public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("bookName")]
        public string BookName { get; set; }

        [BsonElement("price")]
        [DataType(DataType.Currency)]
        public decimal Price { get; set; }

        [BsonElement("category")]
        public string Category { get; set; }

        [BsonElement("author")]
        public string Author { get; set; }
    }



C. the main part here is the Services class which does the whole operation with the Mongo DB and collection, all CRUD operations. I added a search by title capability in my version.
insert: using MongoDB.Driver;
///
  public class BookService
    {
        private readonly IMongoCollection<Book> _books;

        public BookService(IBookstoreDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _books = database.GetCollection<Book>(settings.BooksCollectionName);
        }

        public List<Book> Get() =>
            _books.Find(book => true).ToList();

        public List<Book> FindByTitle(string title) =>
            _books.Find(book => book.BookName.ToLower().Contains(title.ToLower())).ToList();

        public Book Get(string id) =>
            _books.Find<Book>(book => book.Id == id).FirstOrDefault();

        public Book Create(Book book)
        {
            _books.InsertOne(book);
            return book;
        }

        public void Update(string id, Book bookIn) =>
            _books.ReplaceOne(book => book.Id == id, bookIn);

        public void Remove(Book bookIn) =>
            _books.DeleteOne(book => book.Id == bookIn.Id);

        public void Remove(string id) =>
            _books.DeleteOne(book => book.Id == id);
    }


D. My tutorial adds Razor pages to the project, which can display data, and do all the CRUD via separate pages. The Razor pages are scaffolded using a fake entity framework context, just to make the coding faster.

Basically, the CRUD Razor pages were scaffolded to Edit, Create, Delete or List all elements from the Mongo Table. Please follow the code to see the details.

E. In order to demonstrate the search capabilities of MongoDB, I added a form to search by book title,
The result of the application should look like below:

Monday, December 9, 2019

Hidden Tutorial Gems (Easy but Great Ones)





Besides the previous posts' main, impactful tutorials, I came across some nice material in slightly more hidden/unknown places.  There are authors that deserve more attention, because their content is  high quality, and even more importantly, teach the foundations of fresh developments.

A. The .NET stack
1. For me, Entity Framework was something that I wanted to learn this year. But all that I found were books and tutorials - mostly complicated and obscure, that I continuously gave up.

Until I found this simple but excellent material for EF Core, that laid down the foundation for me:
https://code-maze.com/entity-framework-core-series/

2. The Razor Pages tutorial in ASP.NET Core, a simple, yet beautiful one, which made me studying this further:
https://www.learnrazorpages.com/razor-pages/tutorial/bakery

B. The Web Stack (Angular, Firebase and Javascript.)

1. Fireship. I am amazed a little bit how posts in dev.to do not really mention this site as an excellent resource:
https://fireship.io/lessons/

Jeff Delaney, the author, is a Google Developer Expert, and the content is funny, high quality and latest technology in the Angular, Firebase, JavaScript stack. I did quite a few of those tutorials, and purchased his PDF Firebase book.

In my opinion, Firebase is a very interesting solution, and for web developers, a must to dive into. I wish I could have more time to study the material on Jeff's site above, but now I am caught in the .NET world with my current project.

2. Angular Material tutorial. This design system seems very modern and powerful, yet the knowledge requested is advanced, and the best tutorial overall which was not too basic: https://code-maze.com/angular-material-series/

3. PWA with Angular. Unfortunately I did not finish this, but I very much liked it as it combines Angular, Material Design, Firebase and PWA: https://www.pwawithangular.com/

Tuesday, December 3, 2019

PivotTable.js in .Net Core Razor Pages - Tutorial (With Some More Javascript)



Being a former accountant, and my current projects also serving business processes, I find that Pivot Tables are a must in any application of this kind. I struggled without them but now I found a solution, using an Open Source Javascript Library.

I already implemented some of the functionality in one of my projects, but I have to admit that it was a little bit hard, that's why I want to help by showing this example.

Prerequisites for this tutorial:
1. intermediate javascript;
2. basic .Net Core Razor pages knowledge (recommended reading list: https://mydev-journey.blogspot.com/2019/11/razor-pages-not-for-shaving.html
3. study briefly the documentation of pivottable.js, take the simple one: https://pivottable.js.org/examples/simple_ui.html;
4. clone the official repo https://github.com/nicolaskruchten/pivottable
5. my previous tutorial on ChartJS, has a very similar approach and result, and might be a learning step towards this more advanced tutorial: https://mydev-journey.blogspot.com/2019/12/chartjs-tutorial-with-aspnet-core-22.html
6. Repo on Github for this project, to try it:
https://github.com/zoltanhalasz/PivotTableJS

Steps to follow if you want to do it yourself:

A. Create .Net Core Web App (default, razor pages)

B. download pivot table repository from point 4.
Then take the pivot.js and pivot.css files and copy them under the newly created pivot folder in wwwroot.

C. take my _LayoutPivot file and use it instead of the default generated _Layout file from Shared. My _LayoutPivot file will contain all proper references to jquery and pivot.js. Then include it in the _ViewStart file, like :     Layout = "_LayoutPivot";

D. Create InvoiceModel Class, with Json Properties Annotation, this is the main entity for the listing.


E. Create InvoiceService Class which will be injected in the constructor of Index page class. (and set up in Startup.cs).


F. The index cshtml page will just iterate through the list of invoices retrieved by the service and display them.
The backend part in PageModel class will be comprised of:
1. the OnGet function - prepare the data to display
2. the other function - OnGetInvoicePivotData - will pass the JSON array to the javascript fetch in the page.


G. The scripts in the index.cshtml page: below the list of invoices you can find:
1. the pivot - javascript code - retrieving the list using fetch and then giving it to pivotUI function, as per documentation mentioned above.
2. an export to excel (code from stack overflow- how to export an html table to excel from javascript), tailored to export our pivot table.


H. Final result should display as below, showing the list and the pivot table also, together with the Export button:




Monday, December 2, 2019

ChartJS Tutorial With ASP.NET Core 2.2 Razor Pages


In my first project realized in .NET Core Razor pages, I began experimenting with Chart JS, which is a Javascript library for generating charts.
That's how I ended up writing this tutorial, which needs the following prerequisites:
1. beginner level .Net Core Razor pages
2. intermediate Javascript
3. download https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.bundle.min.js and place it into wwwroot folder, js subfolder
4. you can download source code: https://github.com/zoltanhalasz/ChartJSTutorial
5. I suggest you check the tutorials for Razor pages before. See resources:
https://mydev-journey.blogspot.com/2019/11/razor-pages-not-for-shaving.html

The application is live under: https://chartjstutorial.zoltanhalasz.net/


Steps for the application:

A. Create a new Web Application (.Net Core 2.2, Razor Pages Type)
This is the default type web application, and we will use this due to its simplicity. There will be only one page, Index, which is by created default.
B. Create the class of InvoiceModel
This is the main model, the entity for list of invoices. The second class there will be used to provide data to the Chart, is see point E below.
C. Create Service that loads data in Invoice Model
We will not spend time to use a database, but instead, load manually some data into the list.
Then, insert the service into Startup.cs
D. Index page - lists all invoices from above list
Index page - draws the chart using Javascript
If you check the code above, you can see the canvas with the chart. Then there is the Javascript code, that uses the Chart.js mechanism.
E. Code behind, backend for Index page:

OnGet method - loads the invoice list to be displayed in the page
OnGetInvoiceChartData method - is the backend for the fetch at point D in the JavaScript Code. It will provide JSON data in order to be displayed with the list.
I hope you liked this tutorial, please ask me if something needs to be clarified.

Friday, November 29, 2019

The Tutorials With Most Impact in 2019

After relating about tutorial hell in my previous posts, I wanted to present a short list with the most important tutorials of 2019, that impacted my developer life significantly. In total, I might have done maybe a hundred tutorials in this transition year, but some of them were so far - reaching, that they are the backbone of my current projects.


1. introduction to Dapper ORM: https://www.youtube.com/watch?v=Et2khGnrIqc
additional materials were:
Advanced Dapper: https://www.youtube.com/watch?v=eKkh5Xm0OlU&t=3s
Stored Procedures: https://www.youtube.com/watch?v=Sggdhot-MoM
LINQ: https://www.youtube.com/watch?v=yClSNQdVD7g

2. Asp.Net Core - the basics
a. general introduction with MVC: https://code-maze.com/asp-net-core-mvc-series/
b. Entity Framework Core: https://code-maze.com/entity-framework-core-series/
c. Microsoft Razor Pages Tutorial: https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-2.2&tabs=visual-studio
d. A bit more advanced tutorial for Razor Pages: https://www.learnrazorpages.com/razor-pages/tutorial/bakery

3. Angular/Material Design/Firebase
https://angular-templates.io/tutorials/about/angular-crud-with-firebase

My applications in 2019 are very much dependent on the ideas and technologies mentioned in these tutorials. Of course, I studied additional techniques and ideas to fulfill my work, but these were the most interesting and impactful ones for me in 2019.

What are your main tutorials for 2019 or recent years?