My registration view doesnt post the input

I'm trying to do a login and register view with c#, html and MVC. First of all, I have a table in my database called "Usuarios" with columns like: Username, Contrasena (Password), Email, etc). When i fill all the text boxes to test if my controller update my database (adding the new user) it doesnt work.

I'm trying to do a login and register view with c#, html and MVC. First of all, I have a table in my database called "Usuarios" with columns like: Username, Contrasena (Password), Email, etc). When i fill all the text boxes to test if my controller update my database (adding the new user) it doesnt work.

My RegisterClient() method in ClientController:

[HttpPost]
        [AllowAnonymous]
        public ActionResult RegisterClient(RegisterViewModel model)
        {
        if(ModelState.IsValid)
        {
            Cliente Client = new Cliente(model.NombreUsuario, model.Password, model.Nombre, model.Apellido, model.Domicilio, model.TipoDoc, model.NumeroDoc, model.Telefono);

            using (var db = new ContextoDB())
            {

                if (db.Usuarios.Any(u => u.NombreUsuario == Client.NombreUsuario))
                {
                    ViewBag.DuplicateMessage = "Nombre de usuario en uso.";
                    return View("RegisterClient", model);
                }

                db.Usuarios.Add(Client);
                db.SaveChanges();
            }
            ModelState.Clear();
            ViewBag.SuccessMessage = "Registado excitosamente!";

            return RedirectToAction("RegistrationSuccess", "Account");
        } else
        {
            return View(model);
        }


    }

The RegisterClient View:

<div class="register-box">
<h4 class="h4-header">Registro paso 2 de 2 </h4>

        @Html.ValidationSummary(true, "Register failed. Check your login details.")
        &lt;fieldset class="fieldset-box client-field"&gt;

            &lt;div class="user-info-box"&gt;
                &lt;h3&gt; Datos de la cuenta&lt;/h3&gt;
                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.NombreUsuario, new { Class = "YourBackgroundClass", Placeholder = "Usuario" })
                    @Html.ValidationMessageFor(model =&gt; model.NombreUsuario, "", new { @class = "text-danger" })
                &lt;/div&gt;

                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.Email, new { Class = "YourBackgroundClass", Placeholder = "Email" })
                    @Html.ValidationMessageFor(model =&gt; model.Email, "", new { @class = "text-danger" })
                &lt;/div&gt;

                &lt;div class="editor-field"&gt;
                    @Html.PasswordFor(model =&gt; model.Password, new { Class = "YourBackgroundClass", Placeholder = "Contraseña" })
                    @Html.ValidationMessageFor(model =&gt; model.Password, "", new { @class = "text-danger" })
                &lt;/div&gt;

                &lt;div class="editor-field"&gt;
                    @Html.PasswordFor(model =&gt; model.ConfirmPassword, new { @class = "YourBackgroundClass", Placeholder = "Confirmar contraseña" })
                    @Html.ValidationMessageFor(model =&gt; model.ConfirmPassword, "", new { @class = "text-danger" })
                &lt;/div&gt;

            &lt;/div&gt;

            &lt;div class="personal-info-box"&gt;
                &lt;h3&gt; Datos personales&lt;/h3&gt;
                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.Nombre, new { Class = "YourBackgroundClass", Placeholder = "Nombre" })
                &lt;/div&gt;

                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.Apellido, new { Class = "YourBackgroundClass", Placeholder = "Apellido" })
                &lt;/div&gt;
                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.Domicilio, new { Class = "YourBackgroundClass", Placeholder = "Domicilio" })
                &lt;/div&gt;
                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.Telefono, new { Class = "YourBackgroundClass", Placeholder = "Telefono" })
                &lt;/div&gt;

                &lt;div class="editor-field"&gt;
                    @Html.TextBoxFor(model =&gt; model.NumeroDoc, new { Class = "YourBackgroundClass", Placeholder = "Numero de documento" })
                &lt;/div&gt;
            &lt;/div&gt;

        &lt;/fieldset&gt;

        &lt;form action="" method="post"&gt;
            &lt;input type="submit" class="but-next next round" name="upvote" value="&amp;#8250;" /&gt;
        &lt;/form&gt;

        &lt;a href="#" class="but-next next round"&gt;&amp;#8250;&lt;/a&gt;
    &lt;/div&gt;

When i fill all the boxes, it triggers the validation messages.

Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn? In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?

In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?
Limited Offer! Join the Full Node.js Course at 90% off: http://bit.ly/2O0oN6c
Exclusive Discount also available for these courses:

  • React.js: http://bit.ly/36Qm6ww
  • Angular: http://bit.ly/2X0yLZc
  • Vue.js: http://bit.ly/32xDUcj
  • MongoDB: http://bit.ly/34MsB1y
  • CSS: http://bit.ly/2NXtbCZ

How to Validate Phone Number with Javascript

How to Validate Phone Number with Javascript

The validating phone number is an important point while validating an HTML form. In this post we have discussed how to validate a phone number (in different format) using JavaScript

The validating phone number is an important point while validating an HTML form. In this page we have discussed how to validate a phone number (in different format) using JavaScript :

At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. Here is the function.

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript phone validation-1

To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
use the following code.

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-2

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code.


function phonenumber(inputtxt)
{
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-3

Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

CSS Code

 li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

Validate a 10 digit phone number

At first we validate a phone number of 10 digit. For example 1234567890, 0999990011, 8888855555 etc.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head><body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxxxxxxxxx] and Submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-all-numeric-validation.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if(inputtxt.value.match(phoneno))
  {
      return true;
  }
  else
  {
     alert("Not a valid Phone Number");
     return false;
  }
  }

Flowchart:

Flowchart : JavaScript - phone validation 10 digit

Validate North American phone numbers

Now, let's see how to validate a phone number, either in 222-055-9034, 321.789.4512 or 123 256 4587 formats.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxx-xxx-xxxx, xxx.xxx.xxxx, xxx xxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;      
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Flowchart:

Flowchart : JavaScript - phone validation North America

Validate an international phone number with country code

Now, let's see how to validate a phone number with country code, either in +24-0455-9034, +21.3789.4512 or +23 1256 4587 format.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>

<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[+xx-xxxx-xxxx, +xx.xxxx.xxxx, +xx xxxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-+international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Thank you for visiting and reading !

Create a desktop app with Electron, React and C#

Create a desktop app with Electron, React and C#

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

First years in my software craftsmanship started with Delphi 7. It was amazing, it was time when the internet was semi-empty. It was hard to find examples, ask help, basically, you were on your own. Ohh good old times, I wouldn’t change that experience, but I wouldn’t want to do that again.

Time goes on, everything evolves, new technologies come in play. Time to time, I stop and look at what has been changed. And that is so cool, always there is something new to look into. To change my own biases, yes painful, but the world isn’t stuck in time warp.

Ladies and gentlemen I bring to you my experience with Electron.

What is an Electron

An Electron is a framework to create native desktop applications for Windows, MacOS, and Linux. And what is the wow part in it, you can use vanilla javascript or any other javascript framework for building UI.

This is amazing, you can be a web app developer and by reusing the same skillset you can build a desktop app.

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.### The project

Let us create an empty npm project

npm init --yes

Add Electron stuff and start command

npm i -D electron

Add start script inside package.json

"start":"electron ."
{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "electron": "^4.0.6"
  }
}

If we execute the npm start, we should get a popup error from Electron. That is ok, this only means that Electron is alive and we don’t know how to boot it.

The main and renderer process

Before we dive into coding, it is important to understand the basics of Electrons architecture.

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.
My oversimplified explanation would be. There is a main process which creates a window and that window is a Chromium. Where Chromium is a process by itself aka renderer.

Typescript

Starting from the 1 June of the year 2017, Electron supports Typescript. Good, let’s use it.

npm i -D typescript
npm i -D tslint
npm i -D prettier

Add tslint.jsonin the project root

{
  "extends": "tslint:recommended",
  "rules": {
    "max-line-length": {
      "options": [
        120
      ]
    },
    "new-parens": true,
    "no-arg": true,
    "no-bitwise": true,
    "no-conditional-assignment": true,
    "no-consecutive-blank-lines": false
  },
  "jsRules": {
    "max-line-length": {
      "options": [
        120
      ]
    }
  }
}

Add tsconfig.json in the root of the project

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

For typescript compilation, tsc could be used, but as the end game is to use React and manipulate with templates. Webpack is the way to go this time.

Web pack

Setup for the web pack

npm i -D webpack webpack-cli
npm i -D html-webpack-plugin
npm i -D @babel/cli @babel/core @babel/preset-env babel-loader @babel/plugin-proposal-class-properties @babel/plugin-transform-arrow-functions
npm i -D @babel/preset-typescript



Add .babel.rc in the root of the project

{
  "presets": [
    "@babel/env",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

So far so good, now let us create a main process of Electron and say hello to Mom!

Create a folder src

Add main.ts file in src folder

const url = require("url");
const path = require("path");

import { app, BrowserWindow } from "electron";

let window: BrowserWindow | null;

const createWindow = () => {
  window = new BrowserWindow({ width: 800, height: 600 });

  window.loadURL(
    url.format({
      pathname: path.join(__dirname, "index.html"),
      protocol: "file:",
      slashes: true
    })
  );

  window.on("closed", () => {
    window = null;
  });
};

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (window === null) {
    createWindow();
  }
});

line 8 creating a window and loading index.html into window aka Chromium.

Add index.html to the src folder

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hi mom</title>
  </head>
  <body>
    <h1>Hi mom!</h1>
  </body>
</html>

Add webpack.config.js in the root. Instruction for the web pack how to handle Electrons main process build. Important target:"electron-main"

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html",
  inject: false
});

const config = {
  target: "electron-main",
  devtool: "source-map",
  entry: "./src/main.ts",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  node: {
    __dirname: false,
    __filename: false
  },
  plugins: [htmlPlugin]
};

module.exports = (env, argv) => {
  return config;
};

Adjust a bit package.json

{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build": "webpack --mode development",
    "start": "electron ./dist/main.js"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-typescript": "^7.3.3",
    "babel-loader": "^8.0.5",
    "electron": "^4.0.6",
    "html-webpack-plugin": "^3.2.0",
    "prettier": "^1.16.4",
    "tslint": "^5.13.1",
    "typescript": "^3.3.3333",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  }
}

Execute commands

npm run build
npm run start

And here it is. A fully functional desktop application. Which is saying hi to mom.

And this is actually the place where your front end developer skills kick in. As it is a Chromium you can use any kind of frontend technology, React, Vue, Angular, plain javascript.

The React

React will live in Electrons renderer process for that reason we will have to create a separate web pack build configuration. And teach babel to use react loader

npm i -D @babel/preset-react
npm i -S react react-dom
npm i -D @types/react @types/react-dom

Adjust.babelrc

{
  "presets": [
    "@babel/env",
    "@babel/preset-typescript",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Adjust webpack.config.js by removing the responsibility of index.html template generation. It is the responsibility of the renderer build process.

const path = require("path");

const config = {
  target: "electron-main",
  devtool: "source-map",
  entry: "./src/main.ts",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  node: {
    __dirname: false,
    __filename: false
  }
};

module.exports = (env, argv) => {
  return config;
};

Add new web pack config file webpack.react.config.js . This configuration is responsible for compiling react stuff and making sure that compiled result is injected insideindex.html

const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");

const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});

const config = {
  target: "electron-renderer",
  devtool: "source-map",
  entry: "./src/app/renderer.tsx",
  output: {
    filename: "renderer.js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  plugins: [htmlPlugin]
};

module.exports = (env, argv) => {
  return config;
};

Adjust index.html so that it contains a container where React can place its component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Hi mom</title>
  </head>
  <body>
    <div id="renderer"></div>
  </body>
</html>

Create a folder app inside src and create renderer.tsx

import * as ReactDOM from 'react-dom';
import * as React from 'react';
import {Dashboard} from "./components/Dashboard";

ReactDOM.render(<Dashboard />, document.getElementById('renderer'));

Now let’s say Hello mom again, only now we will use a React to do so.

Create a folder components inside app and create Dashboard.tsx

import * as React from 'react';

export const Dashboard = () => {
    return <div>Hello Mom!</div>;
};

Adjust the package.json and add a new command so we can compile the renderer.

{
  "name": "electron-demo",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "build:react": "webpack --mode development --config webpack.react.config.js",
    "build": "webpack --mode development",
    "start": "electron ./dist/main.js"
  },
  "keywords": [],
  "author": "Kristaps Vītoliņš",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "@babel/preset-typescript": "^7.3.3",
    "@types/react": "^16.8.6",
    "@types/react-dom": "^16.8.2",
    "babel-loader": "^8.0.5",
    "electron": "^4.0.6",
    "html-webpack-plugin": "^3.2.0",
    "prettier": "^1.16.4",
    "tslint": "^5.13.1",
    "typescript": "^3.3.3333",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3"
  },
  "dependencies": {
    "react": "^16.8.3",
    "react-dom": "^16.8.3"
  }
}
npm run build:react
npm run build
npm run start

Now, this is something I don’t see every day. A native desktop app running React inside of it. Well maybe I do, I just don’t know it as Electron is a popular framework and is used all over the place. For example, Visual Studio code, try to guess what is powering it ;).

The C# what?

A blog post by Rui Figueiredo ignited my interest in Electron.

Electron using C#. That is an interesting synergy going on here. And as it is C# core, it is cross-platform as well.

Cross-platform desktop app powered by Electron using React for UI and extended functionality by C# goodness. And now not only you can use your frontend skills, but backend as well.

Install new package for npm project

npm i -D electron-cgi

Adjust main.ts for a test run, we will send Mom to C# console app and it will return Hello Mom back. And we will console log that.

const { ConnectionBuilder } = require("electron-cgi");

...

let connection = new ConnectionBuilder()
  .connectTo("dotnet", "run", "--project", "./core/Core")
  .build();

connection.onDisconnect = () => {
  console.log("lost");
};

connection.send("greeting", "Mom", (response: any) => {
  console.log(response);
  connection.close();
});

Create a simple dotnet C# core console app. Add ElectronCgi.DotNet nuget.

using ElectronCgi.DotNet;

namespace Core
{
    class Program
    {
        static void Main(string[] args)
        {
            var connection = new ConnectionBuilder()
                .WithLogging()
                .Build();
            
            connection.On<string, string>("greeting", name => "Hello " + name);
            
            connection.Listen();    
        }
    }
}
npm run build
npm run start

Amazing isn’t it? Rui did go an extra mile and added this to C# as well

connection.OnAsync();

Now we are talking serious stuff. Imagen what possibilities this opens? Async communication to a database, to Rest API, to Queues, all nice packages for clouds, Amazon, Azure etc. All the good stuff from C# at your fingertips.

And it is not limited only to sending strings, it can be strongly typed object in C#.

Here is how

If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.> If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.
Heavy use of stdout. Which isn’t necessarily something bad, for example, php.exe and the frameworks which surround it ;).

I generally like the approach, clean, smart and innovating. I do endorse read a full blog post of Rui.

Extra mile with React and C#

Let’s make this even interesting, send the message to React from C#.

For that make changes in renderer by changing the Dashboard functional component to a component with the state.

import * as React from "react";
import { ipcRenderer } from "electron";

interface IState {
  message: string;
}

export class Dashboard extends React.Component<{}, IState> {
  public state: IState = {
    message: ""
  };

  public componentDidMount(): void {
    ipcRenderer.on("greeting", this.onMessage);
  }

  public componentWillUnmount(): void {
    ipcRenderer.removeAllListeners("greeting");
  }

  public render(): React.ReactNode {
    return <div>{this.state.message}</div>;
  }

  private onMessage = (event: any, message: string) => {
    this.setState({ message: message });
  };
}

What is going there? We subscribe to the channel greeging and upon receiving a message from the main process we put the message into the state. And from that point React takes ower, notices the state changes and renders the message.

Changes in the main process by sending received message from C# to React

const url = require("url");
const path = require("path");
const { ConnectionBuilder } = require("electron-cgi");

import { app, BrowserWindow } from "electron";

...

connection.send("greeting", "Mom from C#", (response: any) => {
  window.webContents.send("greeting", response);
  connection.close();
});

Create a legit EXE file

Add package

npm i -D electron-packager

Adjust the package.json file by adding package-win command and point main to dist folder file main.js.

Tutorial for all platform build commands here.

{
  "main": "dist/main.js",
  "scripts": {
    "package-win": "electron-packager . electron-demo --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron-demo\""
  }
}
npm run package-win

Copy C# folder “core” into “release-builds\electron-demo-win32-ia32” and run the electron-demo.exe

The end

This journey of mine from Delphi 7 to React, Electron, C# is awesome. As I said before, nothing is stuck in time, every day new technologies pop up which makes us better and breaks our personal biases.

To stay open minded is our biggest challenge.

Sourcecode of demo in GitHub

How to export Angular page content to PDF with Kendo UI

How to export Angular page content to PDF with Kendo UI

In this tutorial, learn how to easily export pages with HTML content within your Angular application. This should be a complex task, but thanks to a Kendo UI component it is easy

If you've found yourself looking for an easy solution to smoothly export the HTML content from your Angular application to a PDF, then this is the appropriate post for you. We may need to export HTML content to PDF for several reasons, ranging from sharing it with others without necessarily accessing the internet to saving it just for documentation purposes.

Building a solution for a component like this could be time-consuming if you are building all by yourself. In this post, I will show you how to easily achieve this by leveraging the PDF export component provided by Kendo UI.

We will build an Angular application with some dummy content and add a Kendo UI button to export the content directly to PDF as shown here:

Install Angular CLI

Before creating an Angular application, you need to first install the Angular CLI if it doesn’t already exist on your machine. Open up a terminal and run the following command for that purpose:

npm install -g @angular/cli 

This will add the Angular CLI globally on your machine.

Creating Angular Application

You can now proceed to create a new app for the purpose of this post by running the command below to generate an application with the name kendo-angular-export-pdf:

ng new kendo-angular-export-pdf

Once the installation process is complete, change directory into the newly created project as shown below and start the application:

// change directory
cd kendo-angular-export-pdf
   
// start the application
ng serve

You may experience an error with the message below in your console:

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.

This is a known issue on GitHub and it’s due to lack of compatibility between the current version of TypeScript on your machine and rxjs. The quick way to fix this is to delete the node_modules folder. Now, open the package.json file and within the dependencies object, edit the rxjs by removing ^ :

 "dependencies": {
   ...
   "rxjs": "6.0.0", // remove the `^`
   "zone.js": "^0.8.26"
 },

Save the file and run the npm install command again. Once the installation process is complete, you can now proceed to start the application with ng serve.

This will compile your application and start the development server. To view the default page of this Angular application, navigate to http://localhost:4200 from your favorite browser and you will see this:

Add PDF Export Component from Kendo UI

Next, we’ll need to add the PDF export component before we start using it in our application. To achieve that, we’ll use the ng add command to require and install the package as shown here:

ng add @progress/kendo-angular-pdf-export

This will import and add both PDFExportModule and BrowserAnimationsModule to the app.module.ts file:

// ./src/app/app/module.ts
   
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PDFExportModule } from '@progress/kendo-angular-pdf-export';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
   
   
@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   PDFExportModule,
   BrowserAnimationsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }
Use the Kendo PDF Export Component

After installing the PDF export package, you can now proceed to export content within our Angular application to PDF by placing it within the <kendo-pdf-export> component. Open ./src/app/app.component.html and replace its content with:

// ./src/app/app.component.html
   
<div class="pageWrapper">
 <div class="content">
   <kendo-pdf-export #pdf>
     <div class="size-a4">
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
     </div>
   </kendo-pdf-export>
   
   <div>
     <button kendo-button (click)="pdf.saveAs('demo-content.pdf')">
       Export As PDF
     </button>
   </div>
 </div>
</div>

Here, we have added dummy content and wrapped it with the <kendo-pdf-export></kendo-pdf-export> component. Next we added a button and attached a click event to it. Once the button is clicked, we called the saveAs() method in order to save the generated file. The file will be saved as the name passed as an argument to the saveAs() method.

Finally, to give the page some default styling, add the following content to ./src/app/app.component.css file:

// ./src/app/app.component.css
   
.pageWrapper {
 margin-top: 50px;
}
button {
   padding: 15px;
}
kendo-pdf-export {
 font-family: "DejaVu Sans", "Arial", sans-serif;
 font-size: 16px;
}
.content {
 width: 800px;
 margin: 0 auto;
 line-height: 20px;
}

Now proceed to start the application again by running ng serve from the terminal within the application’s directory. Once

the application is built and served on http://localhost:4200 you will see this:

The content displayed here is from our Angular application. To test the HTML content export functionality, click on the Kendo button with the text Export As PDF. Now open the downloaded PDF file:

Cool, right? This is the content of our page exported to PDF without much hassle. But with a close look at the PDF file, you will agree with me that something isn’t right. The content doesn’t look properly organized. We’ll change that by adding a little bit of margin in the next section.

Add Paper Size and Margin

The Kendo PDF export component API makes a provision for us to easily customize and specify the paper size of the PDF document. At the moment, it is set to the default auto which means that the paper size is determined by the content.

Let’s replace the content of ./src/app/app.component.html with:

// ./src/app/app.component.html
   
<div class="pageWrapper">
 <div class="content">
   <kendo-pdf-export #pdf paperSize="A4" margin="2cm">
     <div class="size-a4">
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
       <p> Build Better JavaScript Apps Faster The ultimate collection of JavaScript UI components with libraries for jQuery,
         Angular, React, and Vue. Quickly build eye-catching and high-performance responsive web applications—regardless
         of your JavaScript framework choice.
       </p>
     </div>
   </kendo-pdf-export>
   
   <div>
     <button kendo-button (click)="pdf.saveAs('demo-content.pdf')">
       Export As PDF
     </button>
   </div>
 </div>
</div>

We have added two data attributes to the <kendo-pdf-export>, which are:

  • paperSize: We set this to A4.
  • margin: We set this to 2cm.

Check the page again and click on the Export As PDF button. Now proceed to open your downloaded PDF file and you will notice that it looks much better as shown below:

Conclusion

The Kendo PDF export component as shown here is a solution for exporting and handling HTML content to PDF. This comes in handy whenever you need to quickly save a page as a PDF document from your Angular application.

We have barely scratched the surface here, because there is so much more functionality provided by the Kendo UI team when exporting HTML content to PDF. Feel free to explore the API by checking the link here for more details.

Hopefully you have learned a lot from this post. Check the source code here on GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Building CRUD Mobile App using Ionic 4, Angular 8

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

Ionic 4 & Angular Tutorial For Beginners - Crash Course

How to Validate an IP address using Javascript

How to Validate an IP address using Javascript

IP address validation using javascript

IP address validation

Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (e.g., 0.0.0.0 to 255.255.255.255).

Example of valid IP address

  • 115.42.150.37
  • 192.168.0.1
  • 110.234.52.124

Example of invalid IP address

  • 210.110 – must have 4 octets
  • 255 – must have 4 octets
  • y.y.y.y – the only digit has allowed
  • 255.0.0.y – the only digit has allowed
  • 666.10.10.20 – digit must between [0-255]
  • 4444.11.11.11 – digit must between [0-255]
  • 33.3333.33.3 – digit must between [0-255]

JavaScript code to validate an IP address

function ValidateIPaddress(ipaddress) 
{
 if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(myForm.emailAddr.value))
  {
    return (true)
  }
alert("You have entered an invalid IP address!")
return (false)
}

Explanation of the said Regular expression (IP address)

Regular Expression Pattern :

/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

This is image title

Note: Last two parts of the regular expression is similar to above.

Syntax diagram - IP-address validation:

Syntax diagram - IP-address validation

Let apply the above JavaScript function in an HTML form.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking IP address/title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an IP address and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="ValidateIPaddress(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="ipaddress-validation.js"></script>
</body>
</html>

JavaScript Code

function ValidateIPaddress(inputText)
 {
 var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
 if(inputText.value.match(ipformat))
 {
 document.form1.text1.focus();
 return true;
 }
 else
 {
 alert("You have entered an invalid IP address!");
 document.form1.text1.focus();return false;
 }
 }

Flowchart:

Flowchart : JavaScript - ipaddress validation

CSS Code

li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

Thank for reading !