Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

How to add\pre-fill https://www. to input fields with type URL?

This is quick post for something I had to implement today. It's related to input fields with type="url".

What did I do?

Opened Visual Studio Code on the Views folder of a large ASP.NET MVC project and then searched for asp-for=(.*)URL using Regular Expression. That linked me to all the places (Razor .cshtml views) which had a @model (Model\ViewModel) class which happens to have an URL property.

Some of those Model\ViewModel properties didn't have the [Url] data annotation. I proceeded to add it to properties where it was missing. This data annotation is responsible for correctly generating the <input type="url" ... > on the HTML when using Razor's html helpers like this for example:

<input asp-for="Organization.URL" class="form-control">
It'll generate this HTML code:

<input class="form-control"
type="url"
data-val="true"
data-val-url="The URL field is not a valid fully-qualified http, https, or ftp URL."
id="Organization_URL"
name="Organization.URL"
value="">
With that in place I crafted some jQuery\JavaScript code that does the magic:

/**
* For all inputs with type URL and which are empty,
* we add https://www. when the input has focus.
*/
function addHttpsWwwToInputTypeUrl() {
$("input[type='url'][value='']").focus(function () {
$(this).val('https://www.')
});
}
The code is self-explanatory. It selects all inputs with type="url" and which are empty. Once the input gets focus, https://www. is added automatically to the input's value. The user now only has to complete the URL address. No more typing https://www. everytime.

The only thing necessary now is to call this JavaScript function in a central place so that it can be applied everywhere in your project.

That's it... a simple but nice user experience to have in your app. Hope it helps.

Creating a ReactJS To Do application with user Authentication\Authorization [ Introduction ] - part 1

This is going to be a series of posts in which I'll show how I managed to get a simple yet functional ReactJS application working. I plan to write 1 blog post per major component detailing how it works and integrates into the app.

This was my start with ReactJS and I worked in this application for almost 1 month as seen by the git commits here. I went from 0% ReactJS knowledge to to some % knowledge of how things work in this UI\presentation framework.

Motivation

The motivation to learn it is that it's mainstream nowadays. ReactJS is also used to develop mobile apps... besides that, for a job application test I had to develop a To Do application with a set of requirements.

Requirements

Programming assignment for web development candidates

You can choose any programming language and web development framework, database, and web server you like. The web application you need to build is a basic todo list application with the following requirements:

- Users can view their todo list;
- Users can add, remove, modify and delete todo entries;
- Each todo entry includes a single line of text, due date and priority;
- Users can assign priorities and due dates to the entries;
- Users can sort todo lists using due date and priority;
- Users can mark an entry as completed;
- You don't need to spend time on UI/UX design, if you do, it will be a bonus;
- Provide a RESTful API which will allow a third-party application to trigger actions on your app (same actions available in the app);
- Provide authentication and authorization service for both the app and the API;
- As complementary item to the last requirement, you should be able to create users in the system via an interface, eg a signup/register screen.

Web Tech Stack

I took the challenge! Developed a SPA - Single Page Application using ReactJS. Why not!? I also used Visual Studio Code as the IDE in tandem with the web tech stack in which I'm experienced with: C#, ASP.NET Core Web API, SQL Server, etc.

The App

The following is the app's homepage:

Figure 1 - App home page

The left side menu when clicked gives access to the Todos form and grid.


Figure 2 - Left side menu

The right side menu allows the user to login\logout and check their profile.


Figure 3 - Right side menu

In order to be able to access the Todos form\grid the user must be authenticated.

Figure 4 - Todo form + grid

Database

Everything was developed in Mac OS and as such the database that stores todo data is an SQL Server container image running in Docker.

Figure 5 - SQL Server database image running in Docker

Web API

The Web API was implemented using an ASP.NET Core Web API project. There's also a Swagger protected help page configured.

Figure 6 - Web API Swagger help page

Source code structure

The following screenshots show how the code is structured:

Figure 7 - App structure in Visual Studio Code Explorer window

- src folder holds all the source code files for the ReactJs app.

- TodoApi holds the source code files for an ASP.NET Web API project.

The ReactJS project skeleton was created\bootstrapped with Create React App as described in the README file.

Expanding the src folder we have this:

Figure 8 - ReactJS SPA app source code files

Expanding the TodoApi folder we have this:

Figure 9 - Todo ASP.NET Web API source code files

App dependencies

The ReactJS app uses the following dependencies as listed in package.json:

"dependencies": {
"@auth0/auth0-spa-js": "^1.6.3",
"@date-io/date-fns": "^1.3.13",
"@material-ui/core": "^4.9.1",
"@material-ui/icons": "^4.9.1",
"@material-ui/pickers": "^3.2.10",
"@testing-library/jest-dom": "^5.1.1",
"@testing-library/react": "^9.4.0",
"@testing-library/user-event": "^8.1.0",
"axios": "^0.19.2",
"date-fns": "^2.9.0",
"formik": "^2.1.4",
"moment": "^2.24.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "^3.3.1",
"react-toastify": "^5.5.0",
"yup": "^0.28.1"
},

Git history

The git history is a nice way to remember what I did along the way:

Git History on master by all authors

Adding Auth0 placeholders...
340657a (HEAD -> master, origin/master) by Leniel Macaferi , Sat May 02 2020 (54 minutes ago)
1 file changed, 2 insertions(+), 2 deletions(-)

Small fixes...
5b98458 by Leniel Macaferi , Fri Feb 21 2020 (2 months ago)
2 files changed, 3 insertions(+), 3 deletions(-)

- Added Roles claim... it's retrieved from Auth0 access_token; - Improved footer; - Added missing toastify messages; - Improved Profile.
2cd5cd3 by Leniel Macaferi , Tue Feb 11 2020 (3 months ago)
5 files changed, 84 insertions(+), 19 deletions(-)

- Added Bearer token support to Swagger so that it's now possible to authorize with a token prior to testing the Web API endpoints; - In TodoItemsController the current user is now extracted while getting Todos so that the user can only retrieve their todos; - Added User property to TodoItem model; - Externalized getUser from Auth0 so that it can be called from stateful ReactJS components like Todo.js; - Made use of getUser() on Todo component; - Beautified Profile component.
b704348 by Leniel Macaferi , Mon Feb 10 2020 (3 months ago)
8 files changed, 122 insertions(+), 19 deletions(-)

- Added scopes and protected Get Todos Web API call with read:todos scope. https://auth0.com/docs/quickstart/backend/aspnet-core-webapi/01-authorization#validate-access-tokens - Added Profile component
13a8675 by Leniel Macaferi , Sun Feb 09 2020 (3 months ago)
13 files changed, 173 insertions(+), 62 deletions(-)

- Made Get Todos protected by using [Authorize] attribute; - Added JwtBearer support to the ASP.NET Core Web API; - Moved BrowserRouter to index.js so that the works as expected. More info here: https://stackoverflow.com/q/60123391/114029 - Externalized getTokenSilently in Auth.js to be able to pass it to axios request interceptor.
ab74c14 by Leniel Macaferi , Sat Feb 08 2020 (3 months ago)
12 files changed, 182 insertions(+), 51 deletions(-)

Added Auth0 to be able to authenticate and authorize users. https://auth0.com/
7ab2538 by Leniel Macaferi , Fri Feb 07 2020 (3 months ago)
9 files changed, 892 insertions(+), 170 deletions(-)

- Added search todo functionality; - Improved the todos table by adding Table pagination actions and made the header sticky; - Improved todo form by disabling the save button when there are errors or when the form is not dirty yet, that is, the user has not changed anything yet; - Added global error message with the help of toastify;
2d59cf4 by Leniel Macaferi , Thu Feb 06 2020 (3 months ago)
5 files changed, 190 insertions(+), 44 deletions(-)

- Commented out InMemoryDatabase in the Web API project and started using a full featured SQL Server database with UseSqlServer. Accomplished that on Mac OS side using Docker and a Developer version of SQL Server 2017; More info here: https://database.guide/how-to-install-sql-server-on-a-mac/ https://stackoverflow.com/a/60080206/114029 - Added Swagger to the Web API project; https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio - Changed Web API default port from 7777 to 8888; - Improved global Progress bar. Set its position to absolute so that it won't push content down when it is displayed; - Moved todo related components to their own folder.
581da74 by Leniel Macaferi , Wed Feb 05 2020 (3 months ago)
16 files changed, 72 insertions(+), 29 deletions(-)

- Added cancel button to todo form. This is useful when the user is editing a todo and wants to cancel the action; - Implemented an improved version of todo form using the HOC [Higher Order Component] withFormik; this allowed passing a parent component [Todo] function down to the child component EnhancedTodoForm which is hooked to the the TodoForm component; Amazing stuff! :-) https://jaredpalmer.com/formik/docs/api/withFormik - route icons are now dynamically retrieved; - Added react-toastify libray to be able to show customized messages to user. https://github.com/fkhadra/react-toastify
469e858 by Leniel Macaferi , Tue Feb 04 2020 (3 months ago)
12 files changed, 328 insertions(+), 100 deletions(-)

- Added request and response interceptors to axios: https://github.com/axios/axios#interceptors ... this will allow a hooking place to display toasts (messages) to the user. This is one of the next thing to be added; - Added a menu tp AppBar using a Drawer component" https://material-ui.com/components/drawers/; - Started using react-router: https://github.com/ReactTraining/react-router; - routes are exported from routes.js; - Added About and Home pages.
7412ec3 by Leniel Macaferi , Mon Feb 03 2020 (3 months ago)
17 files changed, 3682 insertions(+), 3186 deletions(-)

- Got editTodo working; - Improved themes; - Removed unused npm packages.
4afd71e by Leniel Macaferi , Sat Feb 01 2020 (3 months ago)
8 files changed, 158 insertions(+), 866 deletions(-)

- Delete todo(s) done; - WIP Edit todo; - Added axiosInterceptor which handles  the animation when any Web API is called. It shows a Material-UI ; - Externalized custom styles in themes.js; - Many improvements in Todos table.
9d3e032 by Leniel Macaferi , Fri Jan 31 2020 (3 months ago)
13 files changed, 236 insertions(+), 139 deletions(-)

Handling setSelected after deletion happens...
9be189f by Leniel Macaferi , Thu Jan 30 2020 (3 months ago)
1 file changed, 8 insertions(+), 3 deletions(-)

Added delete todo functionality with a gotcha: https://stackoverflow.com/a/33846760/114029
5ad3cbd by Leniel Macaferi , Thu Jan 30 2020 (3 months ago)
7 files changed, 77 insertions(+), 52 deletions(-)

Added material UI Table component to be able to better visualize and operate on Todos. https://material-ui.com/components/tables/
febb4b3 by Leniel Macaferi , Thu Jan 30 2020 (3 months ago)
3 files changed, 371 insertions(+), 17 deletions(-)

- Created a global theme with createMuiTheme; - Improved AppBar - Got addTodo POST call to Web API working and TodoList updating as expected.
6f8a5fb by Leniel Macaferi , Thu Jan 30 2020 (3 months ago)
8 files changed, 700 insertions(+), 174 deletions(-)

Styled App structure and TodoForm with Material UI components.
38f169d by Leniel Macaferi , Wed Jan 29 2020 (3 months ago)
8 files changed, 357 insertions(+), 196 deletions(-)

Got Formik form fields working with material-ui https://material-ui.com/.
b309899 by Leniel Macaferi , Wed Jan 29 2020 (3 months ago)
10 files changed, 1027 insertions(+), 246 deletions(-)

- Added formik, yup and react-formik-ui. - Created a Todo form with formik.
bd8b355 by Leniel Macaferi , Mon Jan 27 2020 (3 months ago)
7 files changed, 771 insertions(+), 60 deletions(-)

Started integrating UI with Web API...
614c68e by Leniel Macaferi , Sun Jan 26 2020 (3 months ago)
9 files changed, 243 insertions(+), 83 deletions(-)

- Added ASP.NET Core 3.1 Todo Web API https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio-code
06ce6d3 by Leniel Macaferi , Sun Jan 26 2020 (3 months ago)
15 files changed, 409 insertions(+), 4 deletions(-)

- Added handleChange event handler to todo-item component; - Handled todo complete state with setState; - Added Bootstrap: https://getbootstrap.com/
c15ff51 by Leniel Macaferi , Sat Jan 25 2020 (3 months ago)
8 files changed, 147 insertions(+), 38 deletions(-)

Converted some functional components to ES6 classes.
64dad12 by Leniel Macaferi , Sat Jan 25 2020 (3 months ago)
3 files changed, 53 insertions(+), 30 deletions(-)

- Got todo items displayed from a todo list JSON file. - Used array.map to create a React TodoItem component dynamically avoiding code repetition.
84cf3fc by Leniel Macaferi , Sat Jan 25 2020 (3 months ago)
5 files changed, 94 insertions(+), 25 deletions(-)

Created basic components and applied some styles including dynamic styling with JavaScript.
90ac727 by Leniel Macaferi , Sat Jan 25 2020 (3 months ago)
6 files changed, 128 insertions(+), 18 deletions(-)

Added .eslintrc.json and modified app name.
f1953ac by Leniel Macaferi , Fri Jan 24 2020 (3 months ago)
4 files changed, 14480 insertions(+), 1 deletion(-)

Initial commit from Create React App
04291f4 by Leniel Macaferi , Fri Jan 24 2020 (3 months ago)
18 files changed, 9789 insertions(+)

Source code

GitHub repository: https://github.com/leniel/ReactToDo


Figure 10 - GitHub repo with % of source code by type


Next

So stay tuned because in the next part I'll start covering the components in a top down approach, that is, we'll start looking at the index.js file where everything gets hooked up.


NPOI 2.0 - Converting Excel XLS documents to HTML format

This is the 4th post of a series of posts about NPOI 2.0.

This time we’re gonna see how easy it is to grab a .XLS file and then have it converted to HTML code.

Note: in NPOI 2.0.6 only XLS format is supported. XLSX support is coming in a future release (maybe 2.1) because it still needs more testing.

Enough said Winking smile, let’s get to the code:

using NPOI.HSSF.Converter;
using NPOI.HSSF.UserModel;
using System;
using System.IO;

namespace NPOI.Examples.ConvertExcelToHtml
{
    class Program
    {
        static void Main(string[] args)
        {
            HSSFWorkbook workbook;
            // Excel file to convert
            string fileName = "19599-1.xls";
            fileName = Path.Combine(Environment.CurrentDirectory, fileName);
            workbook = ExcelToHtmlUtils.LoadXls(fileName);


            ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();

            // Set output parameters
            excelToHtmlConverter.OutputColumnHeaders = false;
            excelToHtmlConverter.OutputHiddenColumns = true;
            excelToHtmlConverter.OutputHiddenRows = true;
            excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = false;
            excelToHtmlConverter.OutputRowNumbers = true;
            excelToHtmlConverter.UseDivsToSpan = true;

            // Process the Excel file
            excelToHtmlConverter.ProcessWorkbook(workbook);

            // Output the HTML file
            excelToHtmlConverter.Document.Save(Path.ChangeExtension(fileName, "html"));
        }
    }
}

The code above was taken from ConvertExcelToHtml sample project.

Here’s the sample spreadsheet open in Excel for Mac that was used as input:

Figure 1 - Excel spreadsheet to be converted to HTML code
Figure 1 - Excel spreadsheet to be converted to HTML code

This is the HTML generated:

Figure 2 - HTML output code generated from the conversion
Figure 2 - HTML output code generated from the conversion

Note that I used a screenshot above but it depicts the .html file (check the browser’s address bar).

Enjoy and have fun!

Delete Blogger Navbar section/widget from your blog template code

In the past I used to just hide Blogger’s navbar widget with some CSS code but it was still there being loaded in the HTML code. This approach is inefficient because I really don’t want the navbar. So why should it still be there in the code taking some precious time to load and impacting the user experience?

Blogger navbarFigure 1 - Blogger navbar

In my case when I looked at the Layout section of my blog in Blogger dashboard I saw that the navbar section was locked (see the locked=’true’ in Figure 2) which means I could not delete it in the Layout screen. So there’s only one option to really get rid of it and it is through the widget code.

If you look carefully you’ll note that the navbar’s code loads some JavaScript files as the Google Plus One plusone.js file. This is impacting my page load speed because I’m already loading the plusone script somewhere else since I have a customized template. This leads to duplicate requests for the same JavaScript file. This is really really bad. There’s no need for it.

So I was after a way of removing the navbar forever; not just hiding it with CSS. I then found a way of doing it but it didn’t work for me. Blogger redesigned its interface and maybe this is the problem.

Then I just thought: what if I try to select the navbar section code and delete it and hit save on the HTML template – who knows… this can work out. What’s the result: it does work out.

How to do it? Follow these 10 simple steps…

1 - First save a backup copy of your blog template for the case where something goes wrong;

2 - Go to Blogger dashboard and select Template in the menu on the left;

3 - Hit the Backup / Restore button at the screen top right and save a backup copy of your layout;

4 - In the Template screen, click Edit HTML button;

5 - Click the checkbox Expand Widget Templates;

6 - Hit Ctrl + F and find the string ‘navbar’;

7 - Select the section code like the one shown in the following screenshot:

Selecting the navbar section/widget code while editing the blog’s template HTML codeFigure 2 - Selecting the navbar section/widget code while editing the blog’s template HTML code

8 - Hit delete on the keyboard;

9 - Click the Save template button in orange. You should get this message:

Warning message informing that deleting the navbar widget cannot be undoneFigure 3 - Warning message informing that deleting the navbar widget cannot be undone

10 - Click Delete widgets button and you’re done. Smile

Now your page will load a bit faster and this is pretty nice for the user visiting your blog.

Hide table column and colorize rows based on value with jQuery

This is a handy piece of code that I used last year in one of my projects. I had scheduled to post it but it was just after I saw this question at StackOverflow that I decided to write about it. So here it is…

Let’s say you want a nice UI experience and to achieve that you wanna colorize/highlight a table row according to a given value present in a column of this row.
This is a simple task when we use jQuery.

I use the WebGrid that comes with ASP.NET MVC to display data on a web page using an HTML <table> element. It’s available in the namespace System.Web.Helpers. The approach described in this post is useful not only with the WebGrid but with any framework/language you use to output HTML code since the manipulation is done on the client side with jQuery.

Take this screen as an example:

HTML table with last column Active to be hidden displaying values Yes and NoFigure 1 - HTML table with last column Active to be hidden displaying values Yes and No

We want hide the last column “Active” and color the row which has a value Yes in this same column.

The above statement can be accomplished with the following code:

(function ($)
{ hideColumnColorRow = function (column)
{ $(
'td:nth-child(' + column + '),th:nth-child( ' + column + ')').hide(); $('tr').find('td:nth-child(' + column + '):contains(Yes)').parent().css('backgroundColor', 'LightGreen'); // Could be an hexadecimal value as #EE3B3B };
})(jQuery);

The hideColumnColorRow function* takes the column number as a parameter. It hides the column <td> and its header <th> using jQuery’s supper useful nth-child selector. Then for each table row <tr> it traverses the row’s columns and looks at the value of each column using :contains selector. If it finds a value = ‘Yes’ it’ll assign a background color to the column’s parent, that in this case is the <tr> (the row) using its CSS backgroundColor property.

So, taking Figure 1 as an example, the above code can be used in an ASP.NET MVC view this way:

<script type="text/javascript">

    $(document).ready(function ()
{
hideColumnColorRow(5); // Hiding the 5th column and colorizing the row for which this column has a value = Yes
});
</script>

* I’ve placed the jQuery/JavaScript function inside a file named custom.js. It resides inside the Scripts folder of the sample app available here. There’s no need to reference this script file in the view page because with the introduction of ASP.NET 4.5 we now have an all new Bundling and Minification Support for CSS and JavaScript files.

When the the app is run, this is the result:

HTML table with column Active hidden and highlighted rows based on its valueFigure 2 - HTML table with column Active hidden and highlighted rows based on its value

This is a really interesting requirement that one can implement in no time thanks to the power of jQuery. jQuery is one of the most fascinating things when we talk about software development. Its creator “John Resig” should be awarded a Computer Science Nobel Prize if that existed. Well it could be the Turing Award.

Anyone should take a look at jQuery and start using it as early as possible. It’s a must have today. I simply love it! Coração vermelho

Source code
I’ve put together a sample ASP.NET MVC 4 (uses NET Framework 4.5) so that you can try this out. You can run the app using the recently launched Visual Studio 11 Beta. You can download the free Visual Studio 11 Express Beta for Web here and the app code here.

Hope it helps.

Backup blogger posts with Blogger Backup

If you want to use Blogger’s built in function take a look in this question at StackOverflow.
Updated on 08-10-2010

I just wanted to backup my blogger posts. I searched for a tool that could automate the process and fortunately I found a pretty good piece of software that does just that. Its name is Blogger Backup Utility.

The software enables you to backup your posts with a high degree of customization. You can backup all the blogs you have. Each one will have its own backup settings.

You can choose if you want to save posts' comments, in what format (one Atom XML file per post or all the posts in a single file) to save the posts, if you want only the most recent posts or the ones included in the specified data range.

See the screenshot of the main window bellow:

BloggerBackUpUtilityMainWindow

Clicking on the button Backup File Naming you'll have the chance of specifying the naming options for the backup files.

There are to configurable options: Folder Name Options and Post File Name Options.

In Folder Name Options you can configure the directory structure in which your posts will be saved.

In Post File Name Options you can configure the name of each post.

In both Folder Name and Post File Name, you can chose from a diverse array of patterns to form the name of the directory structure and posts.

See the screenshot of the Backup File Naming Options:

BloggerBackUpUtilityNamingOptions

After setting up your blog configurations you can click the button Backup Post in the Main Window.

A progress bar on the status bar and list of processed posts will show you the backup process.

The inverse process is also possible, that is, to restore your blog posts, just click on Restore Posts in the Main Windows.

It's really simple, fast and efficient. It does what it's meant to do.

The app only backups in the Atom file format that is an XML file.

Bellow is the structure of the XML that represents the backup copy of this post:

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Backup blogger posts with Blogger Backup</title>
  <id>tag:blogger.com,1999:blog-4926735770070291800.post-7337460476756797508</id>
  <link href="http://lenielmacaferi.blogspot.com/2008/05/backup-blogger-posts-with-blogger.html" rel="alternate" type="text/html" title="Backup blogger posts with Blogger Backup" />
  <link href="http://www.blogger.com/comment.g?blogID=4926735770070291800&amp;postID=7337460476756797508" rel="replies" type="text/html" title="0 Comments" />
  ...
<author> <name>Leniel Macaferi</name> <email>noreply@blogger.com</email> <uri>http://www.blogger.com/profile/17950821674268154143</uri> </author> <category term="Blogger" scheme="http://www.blogger.com/atom/ns#" /> ...
<content type="html"> ...
</content> <updated>2008-05-15T03:45:31-03:00</updated> <published>2008-05-15T03:08:00-03:00</published> </entry>

I wondered how I could extract only the content that interested me and present it in a different format as HTML.

In a next post I'll show you how to transform the XML returned by Blogger Backup into an HTML file. To that end I'll use a XSLT file.

Where to download Blogger Backup Utility?
You can find Blogger Backup at CodePlex at the following address:
http://www.codeplex.com/bloggerbackup

It is developed by only one guy named Greg.

This is the definition given by the author:

The Blogger Backup utility is intended to be a simple utility to backup to local disk your Blogger posts.

Using the GData C# Library, the utility will walk backward in time, from your latest post to your last, saving each post to a local Atom/XML file.

I congratulated him and wrote on the project's page at CodePlex that the addition of the HTML format when saving the posts would be a good feature in case someone wanted to save the posts in an HTML fashion instead of XML.

For more screenshots with descriptions, follow this link:
http://www.codeplex.com/bloggerbackup/Wiki/View.aspx?title=Screenshots&referringTitle=Home