Author

Shehryar Khan

Browsing

One of the most important things is Choosing an e-commerce platform when you’re going to start an online business.

Not all like to install a WordPress theme & start selling. Some are quite conscious of choosing technologies because there are many factors you need to consider – high-performance, scalability, security, extensibility, pricing, programming language, etc.

Related: Why I’m in Love with .Net Core – Future of .Net Core 

A key feature of any E-Commerce is its modular architecture which allows additional features to be added that’s one of the reasons that WordPress became so popular while choosing Platform for an online store. But the Good News is that .Net Core also has some shopping Platforms with pluggable/modular architecture.

Mobile responsiveness is another must-have feature for any online business because 82% of smartphone users buy while surfing the Internet on their smartphone. 

Since you’re here, so you’ve decided to develop your e-commerce store using Asp.net Core.

But choosing the best option is not an easy task. If you start developing your E-commerce platform from scratch it could take months, depending upon your development team. So starting from an open source project is one of the best choices.

In this article, I’ll list down some of the best E-commerce platforms developed in Asp.net Core & available at Github. So let’s get started with the Top 3 Open Source E-commerce platform in ASP.NET Core.

1. NopCommerce

NopCommerce is a free and open-source e-commerce platform.

It’s a fully customizable shopping platform developed in Asp.Net Core.

Its architecture is modular & clean which allows developers to easily customize the front-end design and the back-end functionality.

New themes and add-ons can also be developed on top of nopCommerce.

Features

Responsive: nopCommerce has fully Responsive & Mobile ready design.

Multi-store:  you can host many frontend stores on different domains and manage all operations from your single backend panel. 

Multi-vendor: multiple vendors can add their products & sell.

Product comparison: user can select & compare products features.

Search Engine Optimization: customized URLs, friendly SEO names for products, sitemap, microdata, URL Canonicalization & Google analytics integration.

Reward Points System: points earning system on the money spent at store.

Discounts and coupons: It can either be a fixed value or a percent off, e.g. $20 off or 20% off. we can also define between what dates discount offer is valid.

Payment methods: more than 50 supported payment methods.

Affiliate program: supports affiliate marketing feature.

Tax Feature: Tax calculation system is so configurable.

Plateform

.Net Core SDK Version: .Net Core 2.2

Database: SQL Server 2008

2. SimplCommerce

SimplCommerce is Another simple, cross-platform, customized E-commerce system developed on .NET Core.

SimplCommerce is divided into many self contained modules.

Features

Responsive: fully responsive UI on all size devices.

Product Comparison: user can compare different products.

Coupons & Discounts: you can generate discount coupons for direct & percentage of discounts.

Payment Methods: Stripe, Paypal Express, COD

Tax System: Tax System is available for tax per country, state or zip code.

Plateform

.Net Core SDK Version: .Net Core 2.2

Database: Microsoft SQL Server, PostgreSQL, MySQL, SQLite

3. GrandNode

GrandNode is a functional cross-platform e-commerce solution developed for the most demanding users. You are able to run it on any system – Linux, Windows.

It’s based on ASP.NET Core 2.2 and MongoDB – non-relational database system. 

Features

Responsive: Support devices of all sizes.

Multi-store: can host many web store using a single back-end

Multi-vender: also support Multi-vender functionality like NopCommerce.

Product Comparison: user can compare different products.

Search engine optimization: Sitemap, Friendly URLs, Google Analytics integration & Localizable URLs.

Reward Points System: Reward Points System, Gift Cards, Discounts 

Coupons & Discount: can generate coupans for discounts.

Payment Methods: more than 50 payment methods and gateways.

Tax System: flexible tax system.

Plateform

.Net Core SDK Version: .Net Core 2.2

Database: MongoDB

Comparison

FeaturenopCommerceSimplCommerceGrandNode
DockerYesYesYes
Multi-storeYesYesYes
Multi-venderYesYesYes
Product ComparisonYesYesYes
Payment methods50+Stripe, Paypal Express, COD50+
Reward SystemYesYesYes
Coupons DiscountYesYesYes
.Net Core Version2.22.22.2
DatabaseSQL Server 2008SQL Server, PostgreSQL, MySQL, SQLiteMongoDB

Here are more Articles you might be Interested:

– Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

— Best 20 .Net Core Libraries Every Developer should know

– Top 10 .Net Core Features You need to know

Hey Guys, In this Article, we’re going to Create a very simple Email Sending Contact Form Application using C# with Asp.net Core. We’ll use a beautiful HTML5 Contact Form Template by colorlib for this Tutorial.

Email Sending Contact Form

Setting Up Project

Let’s start by creating a new Asp.net Core Project. I’m going to create an Empty Project using Dotnet CLI.

Run this Command to create a new Empty Project.

dotnet new Web

Update your “Startup.cs” to ready your Project.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=MailSender}/{action=Index}/{id?}");
        });
    }
}

Create 3 Folders as “Controllers”, “Views” & “wwwroot” at the root directory of your project.

Creating Controller

Inside your “Controllers” Folder Create a new File as “MailSenderController.cs” & Add this Code.

using System.Net;
using System.Net.Mail;
using FluentEmail.Core;
using Microsoft.AspNetCore.Mvc;

public class MailSenderController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public string SendEmail(string Name, string Email, string Message){
        
        try
        {
            // Credentials
            var credentials = new NetworkCredential("[email protected]", "your-password");

            // Mail message
            var mail = new MailMessage()
            {
                From = new MailAddress("[email protected]"),
                Subject = "Email Sender App",
                Body = Message
            };

            mail.IsBodyHtml = true;
            mail.To.Add(new MailAddress(Email));

            // Smtp client
            var client = new SmtpClient()
            {
                Port = 587,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Host = "smtp.gmail.com",
                EnableSsl = true,
                Credentials = credentials
            };

            client.Send(mail);

            return "Email Sent Successfully!";
        }
        catch (System.Exception e)
        {
            return e.Message;
        }
        
    }
}

Don’t Forget to Update your Email & Password Credentials in this Line of Code in the above Code.

var credentials = new NetworkCredential("[email protected]", "your-password");

Setting Up Contact Form Template

Now, we need to Create a Contact Form for Sending Emails.

I’m going to use this beautiful Email Sending Template by colorlib.

So, go to this Link & download the Source Code of Contact Page.

Extract the downloaded file & you’ll get this

contact form 2

Now, copy all the folders from the above image & paste inside the “wwwroot” directory in your project which we have created earlier.

Creating View

Create a new Folder inside the “Views” Folder as “MailSender” at the root directory of your Project.

Now, create a new file inside “MailSender” Folder as “Index.cshtml” & Add this Code.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Contact V2</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
  <link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
  <link rel="stylesheet" type="text/css" href="css/util.css">
  <link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
</head>
<body>

  <div class="bg-contact2" style="background-image: url('images/bg-01.jpg');">
    <div class="container-contact2">
      <div class="wrap-contact2">
        <span class="contact2-form-title">
          Contact Us
        </span>

        <div class="wrap-input2 validate-input" data-validate="Name is required">
          <input class="input2" type="text" id="name">
          <span class="focus-input2" data-placeholder="NAME"></span>
        </div>

        <div class="wrap-input2 validate-input" data-validate = "Valid email is required: [email protected]">
          <input class="input2" type="text" id="email">
          <span class="focus-input2" data-placeholder="EMAIL"></span>
        </div>

        <div class="wrap-input2 validate-input" data-validate = "Message is required">
          <textarea class="input2" id="message"></textarea>
          <span class="focus-input2" data-placeholder="MESSAGE"></span>
        </div>

        <div class="container-contact2-form-btn">
          <div class="wrap-contact2-form-btn">
            <div class="contact2-form-bgbtn"></div>
            <button class="contact2-form-btn" onclick="SendEmail()">
              Send Your Message
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

<!--===============================================================================================-->
  <script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
  <script src="vendor/bootstrap/js/popper.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
  <script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
  <script src="js/main.js"></script>

  <script>

    function SendEmail(){

      $.ajax(
      {
        type: "POST",
        url: '@Url.Action("SendEmail", "MailSender")',
        data: {
          Name: $("#name").val(),
          Email: $("#email").val(),
          Message: $("#message").val()
        },
        error: function (result) {
          console.log(result);
        },
        success: function (result) {
          alert(result);
          $("#name").val("");
          $("#email").val("");
          $("#message").val("");
        }
      });
    }
  </script>

</body>
</html>

Testing Application

Run your Application, You’ll get this

Email Sending Contact Form

Fill the Form & click on “Send Your Message” Button.

You’ll Get an Email at the Given Email Address.

Complete Source Code of the Example is also available at Github.

Download Source Code

Secure Client Problem

You might get this Exception while trying to send an Email from your Local Host.

less secure client error

In this Case, you need to Allow Access for Less Secure Apps.

Using the same Google Account you have used in your Controller to Send Email, Go to this Link https://www.google.com/settings/security/lesssecureapps

& Allow Access for Less Secure App.

Google Less Secure App Access

Now, Test your Application again, you’ll be able to receive Email from your Application.

Thank you for reading, Feel free to Comment below if you find any problem.

Here are more Articles you might be Interested

– Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

– Top 10 .Net Core Features You need to know

– Dynamic Role-Based Authorization Asp.net Core

Today Stack Overflow released the results of their annual developer survey 2019.

This year, nearly 90,000 developers took the 20-minute world’s largest developer survey.

I’ve read through the results of the Stack Overflow survey and compiled the most interesting results related to Technologies right here in this article.

So without further ado, here’s a snapshot of what Software Development Technologies has risen in the ranks in 2019 as compared to 2018.

At the top of Key Results, Stack Overflow declared the Python fastest-growing major programming language, has risen in the ranks of programming languages in their survey yet again, edging out Java this year and standing as the second most loved language

Let’s compare the Technologies by categories.

Most Popular Technologies

Programming, Scripting, and Markup Languages

2018 2019

From the last 7 years, JavaScript is the most popular & commonly used language but Python is the fastest growing language. There’s no change in C#, Php & C++ position but Go & Kotlin gained popularity.

Frameworks, Libraries, and Tools

2018 2019

This year Stack Overflow separated the Web & other general purposes Frameworks. This year JQuery leading the Web Frameworks list. React, Angular & Asp.net are at 2nd, 3rd & 4th positions respectively.

Actually, this is the Good news for .Net & .Net Core Developers.

Databases

2018 2019

Not a big change in this list. One thing to note is that there’s a decrease of about 10% in SQL Server usage. It might be because now people are moving toward lightweight solutions.

Platforms

2018 2019
top platforms 2018 top platforms 2019

Linux & Windows popularity increased as development platforms. Stack Overflow added Docker for the first time in the list & It got the 3rd position.

Most Loved, Dreaded, and Wanted

Most Loved, Dreaded, and Wanted Languages

2018 2019
most loved languages 2018 most loved languages 2019

Rust maintained its position with a 5% increase in the most Wanted & Loved Languages List.

Most Loved, Dreaded, and Wanted Other Frameworks, Libraries, and Tools

2018 2019
most loved frameworks 2018 most loved frameworks 2019

It’s really good to see .Net Core & Flutter at the better positions in the Most Loved, Dreaded & Wanted frameworks List as compared to the previous year. Dotnet Core is one of the most versatile frameworks that’s one of the reason that .Net Core is loved by so many developers.

Development Environments and Tools

Most Popular Development Environments

2018 2019
popular development environments 2018 popular development environments 2019

I think It was obvious to increase in the popularity of Visual Studio Code this year. VS Code is one of the top choices of developers.

Developers’ Primary Operating Systems

2018 2019
popular os 2018 popular os 2019

Top Paying Technologies

Highest Salaries Technologies Worldwide

2018 2019
top paying technologies 2018 top paying technologies 2019

According to Stack Overflow, there are regional variations in this category, like Scala is the highest paying programming language in the US, while Clojure and Rust developers earn the most in India.

Conclusion

This year Stack Overflow survey was not accessible to the entire world. It was blocked for the Traffic from Crimea, Cuba, Iran, North Korea, and Syria. Still, about 90,000 developers took the survey. It’s a huge bundle of results categorised as Developers Profile, Technology, Work, Community, methodology & the subcategories of all these. You can check the complete survey results at Stack Overflow.

Here are some more Articles you might be Interested:

.Net Core is a lightweight and cross-platform version of the DotNet framework and the wonderful thing is that Developers required the same expertise to code with .Net Core as .Net Framework.

With Every new Update, new features are added that help developers deploy high-performance & highly scalable applications using less Code.

In this article, I’m listing down some of the most useful but not very commonly used .Net Core Libraries that every developer needs to know.

LiteDB

LiteDB is a lightweight, small & fast NoSQL embedded database. It’s Open source & freely available for everyone, also for commercial usage. LiteDB is fast & also support LINQ queries. It stores data in documents & support Datafile encryption using DES (AES).

Like SQLite, LiteDB also stores data in a single file. It can also index document fields for fast search.

CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.

CacheManager makes developer’s life simpler by handling very complex cache scenarios. It also provides the implementation of multiple layers of caching in just a few lines of code, e.g. in-process caching in front of a distributed cache.

Smidge

A lightweight runtime CSS/JavaScript file minification, combination, compression & management library for ASP.Net Core. It supports compression, Minification & combination for CSS/JS Files. It properly configures client-side caching & persistent server-side caching.

Smidge is easily extensible. You can completely customize the pre-processor pipeline and create your own processors for any file type.

BCrypt.Net-Core

A .net Core version of BCrypt.net, with enhanced features and security. Compatible with .net framework as well as .net core. It should be a drop-in replacement for BCrypt.net as the namespaces are unchanged.

AspNetCore.Diagnostics.HealthChecks

This project is a BeatPulse liveness and UI port to new Microsoft Health Checks feature included on ASP.NET Core 2.2. It supports almost every commonly used database including MySql, Sql Server, Sqlite, MongoDB, Amazon S3, Postgres, Elasticsearch, DynamoDb & many other.

FluentEmail

Send email from .NET or .NET Core. Many useful extension packages make this very simple and powerful. It also offers Email body as a template. We can also use a template from disk. Here’s the basic usage example, look how simple it is.

var email = Email
    	.From("[email protected]")
    	.To("[email protected]", "bob")
    	.Subject("hows it going bob")
    	.Body("yo dawg, sup?")
    .Send();

UnitConversion

UnitConversion is designed to be expansible through factories or through concrete converter implementations. It supports Mass Conversion, Time Conversion, Area Conversion, Distance Conversion & Volume Conversion.

FastReport

FastReport provides open source report generator for .NET Core 2.x/.Net Framework 4.x. You can use the FastReport in MVC, Web API applications.

You can get data from XML, JSON, CSV, MySql, MSSQL, Oracle, Postgres, SQLite, MongoDB, Couchbase, RavenDB.

autocomplete

A very simple, Persistent, powerful and portable autocomplete library. Ready for desktop, web & cloud. It Supports all stream types, including on classical disc storage for cheapest hosting. Considered as one of the fastest autocomplete algorithms with O(n) complexity for searching.

AppMetrics

App Metrics is an open-source and cross-platform library used to record metrics within an application. it provides several metric types to measure things such as the count of login users over time, the rate of requests, measure time to run a DB query, measure the amount of free memory and so on. It supports Counters, Meters, Gauges, Histograms and Timers etc.

sharpcompress

SharpCompress is a compression library that can unzip, unrar, un7zip, untar unbzip2 and ungzip with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip are implemented.

The major feature is support for non-seekable streams so large files can be done on the fly.

HashLib

Here you can find implementations of many hashing algorithms e.g. all sha3 round 2 and 3 candidates. You can hash files, streams, common types of data.

nopCommerce

nopCommerce is the best open-source e-commerce shopping cart. nopCommerce is available for free. It is a fully customizable shopping cart. It’s stable and highly usable. nopCommerce is an open source ecommerce solution.

nopCommerce can be up-and-running in just a few clicks. just download and follow the simple instructions. It’s also optimised for search engines & has friendly URLs.

MailKit

The main goal of this project is to provide the .NET world with robust, fully featured and RFC-compliant SMTP, POP3, and IMAP client implementations.

cscore

A free .NET audio library which is completely written in C#. it offers many features like playing or capturing audio, en- or decoding many different codecs, effects and much more!

NetOffice

NetOffice supports extending and automating Microsoft Office applications: Excel, Word, Outlook, PowerPoint, Access, Project and Visio. It doesn’t have any version limitation. It supports Office versions from 2000 to the latest version.

SSH.NET

This project was inspired by Sharp.SSH library which was adopted from java and it seems like was not supported for quite some time. This library is a complete rewrite, without any third party dependencies, using parallelism to achieve the best performance possible.

It provides SSH commands using Sync & Async methods. SFTP functionality also supports Sync & Async operations. Supports two-factor or higher authentication as well.

SignalR

ASP.NET SignalR is a library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications.

“real-time web” functionality is the ability to have your server-side code push content to the connected clients as it happens, in real-time.

C-Sharp-Algorithms

A C# plug-and-play class-library project of Algorithms & standard Data Structures. It includes 30+ Algorithms & 35+ Data Structures designed as Object-Oriented separate components. Actually, this project was started for educational purposes, the implemented Algorithms & Data Structures are efficient, standard, tested & stable.

Nancy

Nancy is a lightweight framework for building HTTP based services on .NET Framework/Core and Mono.

Nancy is designed to handle GET, POST, PUT, DELETE, HEAD, OPTIONS, & PATCH requests and provides a simple, elegant way for returning a response with just a couple of keystrokes, leaving you with more time to focus on the important logic of your application.

This is the 2nd part of the CRUD Operations Tutorial & the 3rd part of the PHP Web Application Tutorial series.

If you missed previous parts, then you can find here => Getting Started with Web Application using PHP & MySQL | Tutorials

I’m assuming that you have followed the previous part of this Tutorial & created API for CRUD Operations using PHP & MySQL.

In this part, we’ll use AdminLTE Template to create UI for our CRUD API we have created in the previous part of this article.

We have also set up our Template & created the database in the First part of this Tutorial.

After following the previous article, your project structure will look like this.

php mysql crud operation structure

We know that we have created the master.php in the First part, which is our Layout page.

We also have “Doctor” Folder at the root directory of our Project. We’ll create all pages related to Doctor in this Folder.

Let’s start by creating a page to display all doctors data into a Table.

We have created “index.php” file inside “Doctor” Folder. Update this file with the Code below.

<?php
  $content = '<div class="row">
                <div class="col-xs-12">
                <div class="box">
                  <div class="box-header">
                    <h3 class="box-title">Dostors List</h3>
                  </div>
                  <!-- /.box-header -->
                  <div class="box-body">
                    <table id="doctors" class="table table-bordered table-hover">
                      <thead>
                      <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>CNIC</th>
                        <th>Address</th>
                        <th>Action</th>
                      </tr>
                      </thead>
                      <tbody>
                      </tbody>
                      <tfoot>
                      <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>CNIC</th>
                        <th>Address</th>
                        <th>Action</th>
                      </tr>
                      </tfoot>
                    </table>
                  </div>
                  <!-- /.box-body -->
                </div>
                <!-- /.box -->
              </div>
            </div>';

  include('../master.php');
?>
<!-- page script -->
<script>

  $(document).ready(function(){

    $.ajax({
        type: "GET",
        url: "../api/doctor/read.php",
        dataType: 'json',
        success: function(data) {
            var response="";
            for(var user in data){
                response += "<tr>"+
                "<td>"+data[user].name+"</td>"+
                "<td>"+data[user].email+"</td>"+
                "<td>"+data[user].phone+"</td>"+
                "<td>"+data[user].cnic+"</td>"+
                "<td>"+data[user].address+"</td>"+
                "<td><a href='update.php?id="+data[user].id+"'>Edit</a> | <a onClick=Remove('"+data[user].id+"')>Remove</a></td>"+
                "</tr>";
            }
            $(response).appendTo($("#doctors"));
        }
    });
  });

  function Remove(id){

    $.ajax(
        {
            type: "POST",
            url: '../api/doctor/delete.php',
            dataType: 'json',
            data: {
                id: id
            },
            error: function (result) {
                alert(result.responseText);
            },
            success: function (result) {
                if (result['status'] == true) {
                    alert("Successfully Removed Doctor!");
                    window.location.href = '/medibed/doctor';
                }
                else {
                    alert(result['message']);
                }
            }
        });
  }

</script>

Code Explanation

First of all, we have the content of this page in a PHP variable & then we simply included our master.php because it has the code for Layout page.

On document load, we’re using ajax to consume our read API to get all doctors.

We also have a function to remove a Doctor.

Now go to this Url => http://localhost/medibed/doctor/

you’ll see this page

php mysql crud operations

Doctor remove will also work fine because of remove function ready in our code.

Now we need to create pages to Create & Update a Doctor.

Create a new file inside “Doctor” Folder with the name “create.php” & add this Code.

<?php 
  $content = '<div class="row">
                <!-- left column -->
                <div class="col-md-12">
                  <!-- general form elements -->
                  <div class="box box-primary">
                    <div class="box-header with-border">
                      <h3 class="box-title">Add Doctor</h3>
                    </div>
                    <!-- /.box-header -->
                    <!-- form start -->
                    <form role="form">
                      <div class="box-body">
                        <div class="form-group">
                          <label for="exampleInputName1">Name</label>
                          <input type="text" class="form-control" id="name" placeholder="Enter Name">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputEmail1">Email address</label>
                          <input type="email" class="form-control" id="email" placeholder="Enter email">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputPassword1">Password</label>
                          <input type="password" class="form-control" id="password" placeholder="Password">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">Phone</label>
                          <input type="text" class="form-control" id="phone" placeholder="Enter Phone">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">CNIC</label>
                          <input type="text" class="form-control" id="cnic" placeholder="Enter CNIC">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">Address</label>
                          <input type="text" class="form-control" id="address" placeholder="Enter Address">
                        </div>
                      </div>
                      <!-- /.box-body -->

                      <div class="box-footer">
                        <input type="button" class="btn btn-primary" onClick="AddDoctor()" value="Submit"></input>
                      </div>
                    </form>
                  </div>
                  <!-- /.box -->
                </div>
              </div>';

  include('../master.php');
?>
<script>
  function AddDoctor(){
        $.ajax(
        {
            type: "POST",
            url: '../api/doctor/create.php',
            dataType: 'json',
            data: {
                name: $("#name").val(),
                email: $("#email").val(),				
                password: $("#password").val(),
                phone: $("#phone").val(),
                cnic: $("#cnic").val(),
                address: $("#address").val()
            },
            error: function (result) {
                alert(result.responseText);
            },
            success: function (result) {
                if (result['status'] == true) {
                    alert("Successfully Added New Doctor!");
                    window.location.href = '/medibed/doctor';
                }
                else {
                    alert(result['message']);
                }
            }
        });
    }
</script>

Now click on Create Doctor inside Doctors SideBar Menu or go to this Url => http://localhost/medibed/doctor/create.php

You’ll see this page

create user php mysql

Try to Create a new Doctor.

I hope everything is working as expected.

Let’s complete our Update Doctor functionality by creating a new file inside “Doctor” Folder as “update.php”

Add the below code inside this newly created file.

<?php
  $content = '<div class="row">
                <!-- left column -->
                <div class="col-md-12">
                  <!-- general form elements -->
                  <div class="box box-primary">
                    <div class="box-header with-border">
                      <h3 class="box-title">Update Doctor</h3>
                    </div>
                    <!-- /.box-header -->
                    <!-- form start -->
                    <form role="form">
                      <div class="box-body">
                        <div class="form-group">
                          <label for="exampleInputName1">Name</label>
                          <input type="text" class="form-control" id="name" placeholder="Enter Name">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputEmail1">Email address</label>
                          <input type="email" class="form-control" id="email" placeholder="Enter email">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputPassword1">Password</label>
                          <input type="password" class="form-control" id="password" placeholder="Password">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">Phone</label>
                          <input type="text" class="form-control" id="phone" placeholder="Enter Phone">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">CNIC</label>
                          <input type="text" class="form-control" id="cnic" placeholder="Enter CNIC">
                        </div>
                        <div class="form-group">
                          <label for="exampleInputName1">Address</label>
                          <input type="text" class="form-control" id="address" placeholder="Enter Address">
                        </div>
                      </div>
                      <!-- /.box-body -->

                      <div class="box-footer">
                        <input type="button" class="btn btn-primary" onClick="UpdateDoctor()" value="Update"></input>
                      </div>
                    </form>
                  </div>
                  <!-- /.box -->
                </div>
              </div>';
              
  include('../master.php');
?>
<script>
    $(document).ready(function(){

        $.ajax({
            type: "GET",
            url: "../api/doctor/read_single.php?id=<?php echo $_GET['id']; ?>",
            dataType: 'json',
            success: function(data) {
                $('#name').val(data['name']);
                $('#email').val(data['email']);
                $('#password').val(data['password']);
                $('#phone').val(data['phone']);
                $('#cnic').val(data['cnic']);
                $('#address').val(data['address']);
            },
            error: function (result) {
                console.log(result);
            },
        });
    });

    function UpdateDoctor(){
        $.ajax(
        {
            type: "POST",
            url: '../api/doctor/update.php',
            dataType: 'json',
            data: {
                id: <?php echo $_GET['id']; ?>,
                name: $("#name").val(),
                email: $("#email").val(),				
                password: $("#password").val(),
                phone: $("#phone").val(),
                cnic: $("#cnic").val(),
                address: $("#address").val()
            },
            error: function (result) {
                alert(result.responseText);
            },
            success: function (result) {
                if (result['status'] == true) {
                    alert("Successfully Updated Doctor!");
                    window.location.href = '/medibed/doctor';
                }
                else {
                    alert(result['message']);
                }
            }
        });
    }
</script>

</body>
</html>

Now you can also update any doctor record.

We have successfully created our CRUD(Create, Read, Update, Delete) Operations using Beautiful & Free UI Template.

You can also download the complete source code from GitHub.

Download Source Code

Please Comment If you found any problem.

You might be Interested in

Previous Part

Yes, I’d say a large percentage of most applications I’ve worked on is basic CRUD(Create, Read, Update, Delete) operations. Especially In any Web Application, you need to repeat the CRUD Operations for every object in your system.

For creating beautiful & responsive UI, I’m using AdminLTE Template. So, In case if you missed the first part of this Tutorial, then you can find here => Getting Started with Web Application using PHP & MySQL | Tutorials

php mysql crud operations

Assuming that you have followed the above tutorial & setup your project, let’s start our CRUD Operations Tutorial using PHP & MySQL.

I’m performing my CRUD Operation on this Database Table. You can use your own Table.

doctors table

Creating Folders

  1. First of all, create a new folder at the root of your project directory as “api”.
  2. Inside “api” folder create three folders as “config”, “objects” & “doctors”.

we’ll keep all Doctor API inside “doctors” folder.

This directory structure will help us to keep our project easy to manage.

Database Connectivity

In your “config” folder inside “api” folder, create a new file there as “database.php” and paste this code there

<?php
class Database{
 
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "PHPWebAppTutorial";
    private $username = "root";
    private $password = "";
    public $conn;
 
    // get the database connection
    public function getConnection(){
 
        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }
}
?>

Now, your project structure should look like this.

php mysql crud operation structure

Let’s start from creating API for CRUD operations.

First of all, create a Model of your Doctor.

So, create a new file as “doctor.php” inside “objects” folder & add this Code:

<?php
class Doctor{
 
    // database connection and table name
    private $conn;
    private $table_name = "doctors";
 
    // object properties
    public $id;
    public $name;
    public $email;
    public $password;
    public $phone;
    public $gender;
    public $address;
    public $cnic;
    public $profile_status;
    public $specialist;
    public $created;
 
    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // read all doctors
    function read(){
    
        // select all query
        $query = "SELECT
                    `id`, `name`, `email`, `password`, `phone`, `gender`, `address`, `cnic`, `profile_status`, `specialist`, `created`
                FROM
                    " . $this->table_name . " 
                ORDER BY
                    id DESC";
    
        // prepare query statement
        $stmt = $this->conn->prepare($query);
    
        // execute query
        $stmt->execute();
    
        return $stmt;
    }

    // get single doctor data
    function read_single(){
    
        // select all query
        $query = "SELECT
                    `id`, `name`, `email`, `password`, `phone`, `gender`, `address`, `cnic`, `profile_status`, `specialist`, `created`
                FROM
                    " . $this->table_name . " 
                WHERE
                    id= '".$this->id."'";
    
        // prepare query statement
        $stmt = $this->conn->prepare($query);
    
        // execute query
        $stmt->execute();
        return $stmt;
    }

    // create doctor
    function create(){
    
        if($this->isAlreadyExist()){
            return false;
        }
        
        // query to insert record
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    name=:name, email=:email, password=:password, phone=:phone, gender=:gender, cnic=:cnic, address=:address, profile_status=:profile_status, specialist=:specialist, created=:created";
    
        // prepare query
        $stmt = $this->conn->prepare($query);
    
        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->email=htmlspecialchars(strip_tags($this->email));
        $this->password=htmlspecialchars(strip_tags($this->password));
        $this->phone=htmlspecialchars(strip_tags($this->phone));
        $this->gender=htmlspecialchars(strip_tags($this->gender));
        $this->cnic=htmlspecialchars(strip_tags($this->cnic));
        $this->address=htmlspecialchars(strip_tags($this->address));
        $this->profile_status=htmlspecialchars(strip_tags($this->profile_status));
        $this->specialist=htmlspecialchars(strip_tags($this->specialist));
        $this->created=htmlspecialchars(strip_tags($this->created));
    
        // bind values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":email", $this->email);
        $stmt->bindParam(":password", $this->password);
        $stmt->bindParam(":phone", $this->phone);
        $stmt->bindParam(":gender", $this->gender);
        $stmt->bindParam(":cnic", $this->cnic);
        $stmt->bindParam(":address", $this->address);
        $stmt->bindParam(":profile_status", $this->profile_status);
        $stmt->bindParam(":specialist", $this->specialist);
        $stmt->bindParam(":created", $this->created);
    
        // execute query
        if($stmt->execute()){
            $this->id = $this->conn->lastInsertId();
            return true;
        }
    
        return false;
        
    }

    // update doctor 
    function update(){
    
        // query to insert record
        $query = "UPDATE
                    " . $this->table_name . "
                SET
                    name='".$this->name."', email='".$this->email."', password='".$this->password."', phone='".$this->phone."', cnic='".$this->cnic."', address='".$this->address."'
                WHERE
                    id='".$this->id."'";
    
        // prepare query
        $stmt = $this->conn->prepare($query);

        // execute query
        if($stmt->execute()){
            return true;
        }
        return false;
    }

    // delete doctor
    function delete(){
        
        // query to insert record
        $query = "DELETE FROM
                    " . $this->table_name . "
                WHERE
                    id= '".$this->id."'";
        
        // prepare query
        $stmt = $this->conn->prepare($query);

        // execute query
        if($stmt->execute()){
            return true;
        }
        return false;
    }

    function isAlreadyExist(){

        $query = "SELECT *
            FROM
                " . $this->table_name . " 
            WHERE
                email='".$this->email."'";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();

        if($stmt->rowCount() > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

you can see that we have all CRUD Operations including read_single function for reading a single record from MySQL database table.

Now, we’ll create a separate file for each operation inside “doctor” folder & we’ll call functions from “doctor.php” inside “objects” folder.

Let’s create a file inside “doctor” folder as “create.php” for creating a new doctor & add the below code inside this file.

<?php
 
// get database connection
include_once '../config/database.php';
 
// instantiate doctor object
include_once '../objects/doctor.php';
 
$database = new Database();
$db = $database->getConnection();
 
$doctor = new Doctor($db);
 
// set doctor property values
$doctor->name = $_POST['name'];
$doctor->email = $_POST['email'];
$doctor->password = base64_encode($_POST['password']);
$doctor->phone = $_POST['phone'];
$doctor->gender = isset($_POST['gender']);
$doctor->cnic = $_POST['cnic'];
$doctor->address = $_POST['address'];
$doctor->profile_status = 1;
$doctor->specialist = isset($_POST['specialist']);
$doctor->created = date('Y-m-d H:i:s');
 
// create the doctor
if($doctor->create()){
    $doctor_arr=array(
        "status" => true,
        "message" => "Successfully Signup!",
        "id" => $doctor->id,
        "name" => $doctor->name,
        "email" => $doctor->email,
        "phone" => $doctor->phone,
        "gender" => $doctor->gender,
        "cnic" => $doctor->cnic,
        "address" => $doctor->address,
        "specialist" => $doctor->specialist
    );
}
else{
    $doctor_arr=array(
        "status" => false,
        "message" => "Email already exists!"
    );
}
print_r(json_encode($doctor_arr));
?>

For reading all records from Doctors table create a file as “read.php” & add this code

<?php

// include database and object files
include_once '../config/database.php';
include_once '../objects/doctor.php';
 
// instantiate database and doctor object
$database = new Database();
$db = $database->getConnection();
 
// initialize object
$doctor = new Doctor($db);
 
// query doctor
$stmt = $doctor->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if($num>0){
 
    // doctors array
    $doctors_arr=array();
    $doctors_arr["doctors"]=array();
 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){

        extract($row);
        $doctor_item=array(
            "id" => $id,
            "name" => $name,
            "email" => $email,
            "password" => $password,
            "phone" => $phone,
            "gender" => $gender,
            "cnic" => $cnic,
            "address" => $address,
            "profile_status" => $profile_status,
            "specialist" => $specialist,
            "created" => $created
        );

        array_push($doctors_arr["doctors"], $doctor_item);
    }
 
    echo json_encode($doctors_arr["doctors"]);
}
else{
    echo json_encode(array());
}
?>

to Update a record, create a file as “update.php” & add the code below

<?php
 
// get database connection
include_once '../config/database.php';
 
// instantiate doctor object
include_once '../objects/doctor.php';
 
$database = new Database();
$db = $database->getConnection();
 
$doctor = new Doctor($db);
 
// set doctor property values
$doctor->id = $_POST['id'];
$doctor->name = $_POST['name'];
$doctor->email = $_POST['email'];
$doctor->password = base64_encode($_POST['password']);
$doctor->phone = $_POST['phone'];
$doctor->cnic = $_POST['cnic'];
$doctor->address = $_POST['address'];
 
// create the doctor
if($doctor->update()){
    $doctor_arr=array(
        "status" => true,
        "message" => "Successfully Updated!"
    );
}
else{
    $doctor_arr=array(
        "status" => false,
        "message" => "Email already exists!"
    );
}
print_r(json_encode($doctor_arr));
?>

& for the last letter of CRUD, which is D.

create another file as “delete.php” & add this code

<?php
 
// get database connection
include_once '../config/database.php';
 
// instantiate doctor object
include_once '../objects/doctor.php';
 
$database = new Database();
$db = $database->getConnection();
 
$doctor = new Doctor($db);
 
// set doctor property values
$doctor->id = $_POST['id'];
 
// remove the doctor
if($doctor->delete()){
    $doctor_arr=array(
        "status" => true,
        "message" => "Successfully Removed!"
    );
}
else{
    $doctor_arr=array(
        "status" => false,
        "message" => "Doctor Cannot be deleted. may be he's assigned to a patient!"
    );
}
print_r(json_encode($doctor_arr));
?>

in the end, we need another method which is to get a single doctor record.

So, create a new file as “read_single.php” & add the below code

<?php

// include database and object files
include_once '../config/database.php';
include_once '../objects/doctor.php';
 
// get database connection
$database = new Database();
$db = $database->getConnection();
 
// prepare doctor object
$doctor = new Doctor($db);

// set ID property of doctor to be edited
$doctor->id = isset($_GET['id']) ? $_GET['id'] : die();

// read the details of doctor to be edited
$stmt = $doctor->read_single();
if($stmt->rowCount() > 0){

    // get retrieved row
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    // create array
    $doctor_arr=array(
        "id" => $row['id'],
        "name" => $row['name'],
        "email" => $row['email'],
        "password" => $row['password'],
        "phone" => $row['phone'],
        "gender" => $row['gender'],
        "cnic" => $row['cnic'],
        "address" => $row['address'],
        "profile_status" => $row['profile_status'],
        "specialist" => $row['specialist'],
        "created" => $row['created']
    );
}

// make it json format
print_r(json_encode($doctor_arr));
?>

After this our “api” directory will look like this

php mysql crud operation structure

Our API for CRUD Operation is ready using PHP & MySQL. Now, we need to create UI using the template we set up in the previous article & then connect our UI with the API we created in this article.

We’ll create UI for our CRUD Operations in the next part of this Article.

Comment If you find any difficulty, I’m available to solve your problems.

Previous Part

Next Part

PHP is a programming language used to create dynamic contents with the database. Basically, PHP is used to develop Web Applications. In this Tutorial, we’re going to Develop a very simple Web Application & we’ll add features in our application in next parts of the tutorial.

This Tutorial is for beginners. So, for keeping the things simple we’ll not use any PHP Framework. We’ll use Object Oriented PHP for creating our Web Application. 

We’re going to create an Application to manage Doctors, Nurses etc & I’m going to give our application a name “Medibed”.

Php web application

If you’re interested in creating Web Services using PHP. Here’s my article on Web Services in PHP

Restful Web Services in PHP Example – PHP + MySQL with Source Code

Let’s start our Tutorial.

Pre-requisites

Before starting this Tutorial, you must have a basic knowledge of PHP, MySQL, HTML, CSS, & JQuery to customize your application. We’ll use MySQL for creating Database for our Application & an Admin Template for creating interactive User Interfaces.

There are many Free Templates Available, for this Tutorial, I’m going to use This Beautiful Admin Template by almasaeed.

Setting up Server

To work on your local system you need to have PHP & MySQL installed on your system. So, the first step is to have a server to run our application. I’m going to install XAMPP because It installs both PHP & MySQL for us.

xampp php mysql

Run your server, go to your “htdocs” Folder inside “XAMPP” Forder & create a new folder there as “medibed”

Creating Database

It’s time to create a database for our Web Application.

I’m going to use very simple Hospital Database with 4 Tables, “doctors”, “nurses”, “patients” & “admins”.

You can use the database of your Web or Mobile App for which you are developing your Application.

Here’s the Database I’m going to use with the name “hospital_db”

hospital db er diagram

& here’s the SQL script for this database

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

-- Database: `hospital_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `doctors`
--
CREATE TABLE `doctors` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `gender` int(11) NOT NULL,
  `specialist` varchar(255) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `doctors`
--
INSERT INTO `doctors` (`id`, `name`, `email`, `password`, `phone`, `gender`, `specialist`, `created`) VALUES
(1, 'Ahsan Saeed', '[email protected]', 'Vm0xMFlWbFdWWGhVYmxKWFltdHdVRlpzV21GWFJscHlWV3RLVUZWVU1Eaz0=', '03218878961', 0, 'Heart', '2018-05-01 13:07:24');
-- --------------------------------------------------------
--
-- Table structure for table `nurses`
--
CREATE TABLE `nurses` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `nurses`
--
INSERT INTO `nurses` (`id`, `name`, `email`, `password`, `phone`, `created`) VALUES
(1, 'Ahsan', '[email protected]', 'MTIzNDU=', '03218878961', '2018-06-27 13:39:31'),
(2, '2', 'ABC', 'WFla', '123456789', '2018-07-06 13:50:24'),
(3, 'Shehryar khan', '[email protected]', 'YXBwcnl4', '3433243243', '2018-07-06 18:12:35');
-- --------------------------------------------------------
--
-- Table structure for table `patients`
--
CREATE TABLE `patients` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `gender` int(11) NOT NULL,
  `health_condition` varchar(255) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `nurse_id` int(11) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `patients`
--
INSERT INTO `patients` (`id`, `name`, `phone`, `gender`, `health_condition`, `doctor_id`, `nurse_id`, `created`) VALUES
(6, 'hjj', '9988596666', 1, 'vbjbb', 1, 1, '2018-06-26 13:12:18'),
(9, '2', '123456789', 1, 'OK', 1, 1, '2018-07-06 13:59:25'),
(10, '2', '123456789', 1, 'OK', 1, 1, '2018-07-06 14:13:13'),
(11, 'shehryar', '123456789', 1, 'OK', 1, 1, '2018-07-06 17:36:08'),
(14, 'Coding Infinite', '3433243243', 0, 'asd', 1, 1, '2018-07-06 18:39:42'),
(15, 'Coding Infinite', '3433243243', 0, 'asd', 1, 1, '2018-07-06 18:40:07'),
(16, 'Coding Infinite', '3433243243', 0, 'asd', 1, 1, '2018-07-06 18:40:59');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
  ADD PRIMARY KEY (`id`);
--
-- Indexes for table `doctors`
--
ALTER TABLE `doctors`
  ADD PRIMARY KEY (`id`);
--
-- Indexes for table `nurses`
--
ALTER TABLE `nurses`
  ADD PRIMARY KEY (`id`);
--
-- Indexes for table `patients`
--
ALTER TABLE `patients`
  ADD PRIMARY KEY (`id`),
  ADD KEY `doctor_id` (`doctor_id`),
  ADD KEY `nurse_id` (`nurse_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `doctors`
--
ALTER TABLE `doctors`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `nurses`
--
ALTER TABLE `nurses`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `patients`
--
ALTER TABLE `patients`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `patients`
--
ALTER TABLE `patients`
  ADD CONSTRAINT `patients_ibfk_1` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`),
  ADD CONSTRAINT `patients_ibfk_2` FOREIGN KEY (`nurse_id`) REFERENCES `nurses` (`id`);
COMMIT;

Save the Above SQL Script in a file as “hospital_db.sql”.

Go to http://localhost/phpmyadmin, create a database as “hospital_db” & import the SQL File in your Database.

Now our database is ready & the next step is to set up our Server & AdminLTE Template for our Application.

Setting Up Template

First, you need to download AdminLTE Template. So download or clone AdminLTE & Unzip AdminLTE folder.

You’ll see these files & folders.

admin lte files

For keeping our project clean you need to copy & paste only Two Folders “bower_components” & “dist” from here to the folder we have created earlier with the name “medibed”.

Let start by creating a Layout Page for our Application.

Now create a new file as “master.php” at the root folder of your Folder & paste this code.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>MediBed</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="../bower_components/font-awesome/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="../bower_components/Ionicons/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../dist/css/AdminLTE.min.css">
  <link rel="stylesheet" href="../dist/css/skins/skin-blue.min.css">

  <!-- Google Font -->
  <link rel="stylesheet"
        href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <!-- Main Header -->
  <header class="main-header">

    <!-- Logo -->
    <a href="index.php" class="logo">
      <!-- mini logo for sidebar mini 50x50 pixels -->
      <span class="logo-mini"><b>M</b>BD</span>
      <!-- logo for regular state and mobile devices -->
      <span class="logo-lg"><b>Medi</b>BED</span>
    </a>

    <!-- Header Navbar -->
    <nav class="navbar navbar-static-top" role="navigation">
      <!-- Sidebar toggle button-->
      <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
        <span class="sr-only">Toggle navigation</span>
      </a>
      <!-- Navbar Right Menu -->
      <div class="navbar-custom-menu">
        <ul class="nav navbar-nav">
          
          
          <!-- User Account Menu -->
          <li class="dropdown user user-menu">
            <!-- Menu Toggle Button -->
            <a href="" class="dropdown-toggle" data-toggle="dropdown">
              <!-- The user image in the navbar-->
              <img src="../dist/img/avatar5.png" class="user-image" alt="User Image">
              <!-- hidden-xs hides the username on small devices so only the image appears. -->
              <span class="hidden-xs">Ahmed Khalid</span>
            </a>
            <ul class="dropdown-menu">
              <!-- The user image in the menu -->
              <li class="user-header">
                <img src="../dist/img/avatar5.png" class="img-circle" alt="User Image">

                <p>
                  Ahmed Khalid - Developer
                  <small>Member since May. 2018</small>
                </p>
              </li>
              
              <!-- Menu Footer-->
              <li class="user-footer">
                <div class="pull-left">
                  <a href="#" class="btn btn-default btn-flat">Profile</a>
                </div>
                <div class="pull-right">
                  <a href="#" class="btn btn-default btn-flat">Sign out</a>
                </div>
              </li>
            </ul>
          </li>
          <!-- Control Sidebar Toggle Button -->
        
        </ul>
      </div>
    </nav>
  </header>
  <!-- Left side column. contains the logo and sidebar -->
  <aside class="main-sidebar">

    <!-- sidebar: style can be found in sidebar.less -->
    <section class="sidebar">

      <!-- Sidebar user panel (optional) -->
      <div class="user-panel">
        <div class="pull-left image">
          <img src="../dist/img/avatar5.png" class="img-circle" alt="User Image">
        </div>
        <div class="pull-left info">
          <p>Ahmed Khalid</p>
          <!-- Status -->
          <a href=""><i class="fa fa-circle text-success"></i> Online</a>
        </div>
      </div>

      <!-- search form (Optional) -->
      <form action="#" method="get" class="sidebar-form">
        <div class="input-group">
          <input type="text" name="q" class="form-control" placeholder="Search...">
          <span class="input-group-btn">
              <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
              </button>
            </span>
        </div>
      </form>
      <!-- /.search form -->

      <!-- Sidebar Menu -->
      <ul class="sidebar-menu" data-widget="tree">
        <li class="header">Menu</li>
        <!-- Optionally, you can add icons to the links -->
        <li class="treeview">
          <a href="#"><i class="fa fa-medkit"></i> <span>Doctors</span>
            <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
              </span>
          </a>
          <ul class="treeview-menu">
            <li><a href="/medibed/doctor/create.php">Create Doctor</a></li>
            <li><a href="/medibed/doctor">All Doctors</a></li>
          </ul>
        </li>
      </ul>
      
      <!-- /.sidebar-menu -->
    </section>
    <!-- /.sidebar -->
  </aside>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        Dashboard
        <small>Welcome to Admin Dashboard</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> MediBed</a></li>
        <li class="active">Dashboard</li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content container-fluid">

      <?php echo $content; ?>

    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

  <!-- Main Footer -->
  <footer class="main-footer">
    <!-- Default to the left -->
    <strong>Copyright &copy; 2018 <a href="https://codinginfinite.com">Coding Infinite</a>.</strong> All rights reserved.
  </footer>

  <!-- Add the sidebar's background. This div must be placed
  immediately after the control sidebar -->
  <div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->

<!-- jQuery 3 -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- DataTables -->
<script src="../bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="../dist/js/adminlte.min.js"></script>

</body>
</html>

This is our master/layout page. We’ll load the content of all other pages inside this master page.

Let’s test our master page.

Create a new Folder as “Doctor” at the root of our project & inside this folder create a new file with the name “index.php”

Now, your “medibed” folder should look like this.

web app folders

Add the Code below Inside your “index.php” 

<?php
  $content = '<h2>Your Main Content Here</h2>';
  include('../master.php');
?>

Now, open your browser & go to this URL => http://localhost/medibed/doctor

you’ll see this

php web app

Congrats, you have successfully completed the first step toward creating your Web Application.

In the Next part of this Tutorial, we’ll perform CRUD operations using this beautiful Template.

Comment If you have any question or find any difficulty. I’m here to solve your problem.

You might be Interested in

Next Part

I find it tough to believe that many developers do not use any Logging library in their applications. For a Web Applications, Error Logging is one of the key attributes to help troubleshoot application bugs. In many cases, developers don’t have direct access to his application after deployment. So, in order to assure the application’s quality, we must be aware of bugs in our application even after deployment.

There are many open-source libraries available for Error Logging. For .Net, most trusted & commonly used frameworks are NLog & Log4Net. Both frameworks make it simpler to send our application logs in different places like databases, files, log management systems & many other places. We can also Email our Critical logs. The awesome thing is that we can send the logs to a different place just by changing the config file.

By using Error Logging in an Application, we can categorize our logs at different levels. Here’s the list.

Levels

  • Info – Info Message, enabled in production mode
  • Warning – Warning Messages, temporary & recoverable problems.
  • Error – Error Messages, programming exceptions.
  • Trace – Very detailed Logs, usually enabled during the development phase.
  • Debug – Debugging information, less information than Traces.
  • Fatal – Serious Errors, failures that need immediate attention.

As I have discussed above, Error Logging Frameworks also facilitates us to send our application’s log to different destinations, we called them targets.

Targets

  • Files- We can log our messages into a file.
  • Databases – Important Logs can also be stored in a database. Usually, we store only those logs to a database which we need to display in our application.
  • Console – In Console Applications, best available target to display logs is console itself.
  • Email – In case of fatal errors which need attention we need to aware the team with the failure. so it’s always a good idea to email those logs.

Let’s have a quick look at available Logging frameworks for .Net Core. After deciding the better one, we’ll implement the winner logging framework in our Application. So in case, you missed the Admin Panel tutorials,

here you can follow => Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

Choosing a Framework

Here’s the result of a speed comparison of 5 most popular error logging framework for .Net & .Net Core

Logging Frameworks Comparison Result by Loggly and SolarWinds

Logging Libraries Comparison

So clearly, NLog is the winner here because it’s taking the minimum time to Log.

Without wasting our time let’s see how we can install, configure and use NLog in our Application.

Creating a Project

I’m going to use VS Code to create an empty web project.

Create an empty Web Application using this command

dotnet new web

after this add the Code below to your “Startup.cs” File to ready your Application.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Now create a new Folder as “Controllers” at the root level of your Project & inside this folder create a controller class as “HomeController.cs”

Installing NLog

After creating the project, we need to add NLog Library.

NLog is available at Nuget. You can install it in the way you like it. I’m going to use the .Net CLI. So, here’s the command to install NLog

dotnet add package NLog

Configuration

Now Add a configuration file at the root of your project with the name as “NLog.config” & paste this Code

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="Logs.txt" />
        <target name="logconsole" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

There’s another way to configure NLog but I’ll recommend using XML configuration. In this case, you’ll be able to edit you Logging configuration even after publishing your application.

If you still don’t like configuring NLog using above way then you can do the same by programmatically.

Here’s the alternate way.

var config = new NLog.Config.LoggingConfiguration();

var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "Logs.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            
NLog.LogManager.Configuration = config;

you can add this code to your “Program.cs” or “Startup.cs”.

Writing Logs

Now Add the code below in your “HomeController.cs” inside your Controllers Folder.

using Microsoft.AspNetCore.Mvc;
using NLog;

public class HomeController : Controller
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    public void Index()
    {
        logger.Debug("Hello from Home Controller...");
    }
}

Run your application & go to the Home Controller URL. e.g. http://localhost:*/Home

Now you’ll find your “Logs.txt” here => bin -> Debug -> netcoreapp

Here’s what I got in my “Logs.txt” File

2019-02-21 13:17:49.4574|DEBUG|NLogTutorials.HomeController|Hello from Home Controller...

Comment If you find any problem or have any Question.

Here are more Articles you might be Interested

– Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

– Top 10 .Net Core Features You need to know

– Dynamic Role-Based Authorization Asp.net Core

If you ask “what is the best” type of questions, you will end up with biased answers, usually. Everyone will tell you his own preference.

Although you have listened to this famous Quote “Love is blind” & no one believes to defend his love with arguments & solid pieces of evidence, but In this Article, I’m going to share some real grounds that why I’m in Love with .Net Core & why I think that .Net Core is the best available Framework even in 2019.

Without biasness, I can say that every language has it’s own area of strength, for example:

Python: Machine Learning, Data Science, and oh yes! Web development.

JavaScript: Web Development (Front End as well as Backend), and Game Development.

Java: Mobile Application Development, Enterprise Applications, and even Web development.

C++ & C: Operating Systems, Performance critical solutions, embedded systems, and anything needed low-level ability.

These languages also have some other roles, but I just mentioned strength areas of these languages.

If you’re interested in the Top programming languages to learn in 2019, here is the complete guide for you => The Ten Best Programming Languages to learn in 2019

Before talking about why I considered .Net Core the Top Framework, I want to clear one thing. Otherwise, we might get some comments something like “python is better than .Net Core”.

Language vs Framework

A programming language is a set of rules that need to be followed to write a program to accomplish a task whereas a framework is a collection of useful tools written for a particular programming language.

For example, C# is a programming language. Microsoft built the .NET & .NET Core Frameworks in C# so that developers can build C# applications much more quickly than if they had to create everything from scratch.

Before Talking about my Love (.Net Core), my Introduction is important.

Who I am?

I’m Shehryar Khan, working as a Full Stack .Net Core MVC developer from last 2 years. Before that, I worked as a .Net Developer 3 years. So I’m playing with .Net & C# from last 5 years, before that, I had some experience as a PHP developer.

What is my Job? (Important to know)

Actually, I’m working in a Smart Metering company from last 3 years & have worked on many projects of different types.

  • A project I completed, was a huge Web Based Application named as “Energy Axis” for Managing smart meters Data & for automatic Billing.
  • A task assigned to me was to Implement a protocol(DLMS) for reading some metering devices data.
  • A task assigned to me was to write some web services for sharing some Data to be used by another application.
  • A task assigned to me was to create a Task Scheduler for generating some files & send over SFTP using Code.
  • How can I forget that I have successfully completed a Ride Booking application project like Uber with Ahsen Saeed

– My C# knowledge has also helped me to develop a 3D game using Unity3D.

I have also worked on many other projects but these are enough to define the versatility of .Net Core Framework

.Net Core has countless features but In this Article, I’m going to discuss only a single feature which is Versatility.

If you’re interested in Top .Net Core features, you can read this Article => Top 10 .Net Core Features You need to know

Versatility: Web, Mobile, Server, Desktop

The main reason why I chose .Net Core as my Life Partner is the Versatility. Are you a Web Developer or want to Develop an app for Desktop or Mobile, If you are a Game Developer or want to work on Machine Learning, DotNet Core is here for you.

Thanks to Xamarin to use our Microsoft knowledge to Develop Cross-Platform Mobile Apps. Unity is there for Developing games. You can build desktop applications with UWP. Asp.net Core is also a main player in the Game for Developing powerful Web-based applications providing amazing SPA Angular Templates. Real-time applications with SignalR and a lot more.

Let’s not forget the high-performance service-oriented architecture. Docker containers is also supported which makes it easy to deploy your app to AWS or other providers. Using Microsoft Azure you can develop & deploy on the cloud in a few clicks.

ML.NET is a machine learning framework for .NET developers, when we talk about Cognitive Services in Azure, we’re really talking about commoditized AI(Artificial Intelligence). Blazor is going to take over some of the JavaScript functionalities.

Every time when I start to talk about .Net Features, It becomes difficult for me to stop writing. There are many more reasons why I’m in Love with .Net Core. Like Performance, Open-source, Awesome Developers Tools & many more.

I would like to share a review from Raygun’s CEO & Co-Founder here about .Net Core

.net core

Updates & News

Now, Let’s have a quick look at the Future Updates & News from Microsoft.

 .NET Core 3.0

The open-source .NET Core 3.0 adds support for WinForms and the Windows Presentation Framework (also now open source) and enabled more flexible deployment with self-contained EXE files and improved performance.

C# 8.0

Microsoft recently launched a new version of C# with some really useful features. I’ll write about the use of these features some other day. Some of the features I really want to use in my new developments are Non-Nullable & Nullable Reference Types, New Lightweight Classes, Solving Object Equality with Records, Default Interface Implementations & Improved Extension Support.

Visual Studio 2019 for Windows and Mac

Visual Studio is one of the most powerful IDE available. Visual Studio 2019 Preview is available for Windows & Mac with new features to help the developers make the development faster

Conclusion

I have no doubt that .Net Core is the Future. The reason why most of the top firms love to use .Net for the developments of their huge applications is because of Microsoft Support. Microsoft is adding new features to help developers in every new update. I have also worked with Top PHP MVC Frameworks, Python & Java but I can say that .Net Core has no limits.

Here are more Articles you might be Interested

Best 20 .Net Core Libraries Every Developer should know

– Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

– Top 10 .Net Core Features You need to know

The Ultimate Guide to the Best .NET Core E-commerce Open Source Platforms

Although there are many Graphical Tools available for sending files to a server using SFTP. But as a developer, we may have a scenario where we need to upload a file to SFTP Server from our Code.

A few days ago a job assigned to me was to develop a Task Scheduler for generating XML files daily on a specific time of the day & send these files on a Remote Server using File Transfer Protocol in a secure way.

Here’s my article on creating task scheduler => Creating Scheduler in c# – Schedule Task by Seconds, Minutes, Hours, Daily

In .Net Framework there are many Libraries available for uploading files to another machine using File Transfer Protocol but most of the libraries don’t work with .Net Core. In this Tutorial, we will develop a very simple SFTP client using C# for .Net Core.

Before start let’s have a quick look at SFTP.

What is SFTP?

SFTP stands for SSH File Transfer Protocol or Secure File Transfer Protocol. It is a protocol used to transfer files between remote machines over a secure shell.

In almost all cases, SFTP is preferable over FTP because of security features. FTP is not a secure protocol & it should only be used on a trusted network.

Choosing Library for C#

A lot of search & after testing many libraries I finally met with SSH.NET which was working perfectly with .Net Core 2.2 project & the good thing was that It does its job in a very few lines of Code.

So we’ll use SSH.NET

What is SSH.NET?

SSH.NET is an open-source library available at Nuget for .NET to work over SFTP. It is also optimized for parallelism to achieve the best possible performance. It was inspired by Sharp.SSH library which was ported from Java. This library is a complete rewrite using .Net, without any third party dependencies.

Here are the features of SSH.NET:

Features

ssh.net features

Creating Project

I’m in love with VS Code right after its first release so I’m going to use VS Code for creating project to upload/transfer a file to a remote server using SFTP.

Create a console application using this command

dotnet new console

Installing SSH.NET

I won’t recommend you to install the latest version of SSH.NET. It has a bug, it can be stuck on transferring the file to the remote location.

version 2016.0.0 is perfect. 

run this command to install the library from NuGet

using package manager

Install-Package SSH.NET -Version 2016.0.0

or using .Net CLI

dotnet add package SSH.NET --version 2016.0.0

Code

Finally, It’s time to create a class for SFTP Client Code.

Create a file with the name as “SendFileToServer” & add the below code

using Renci.SshNet;

public static class SendFileToServer
{
    // Enter your host name or IP here
    private static string host = "127.0.0.1";

    // Enter your sftp username here
    private static string username = "sftp";

    // Enter your sftp password here
    private static string password = "12345";
    public static int Send(string fileName)
    {    
        var connectionInfo = new ConnectionInfo(host, "sftp", new PasswordAuthenticationMethod(username, password));

        // Upload File
        using (var sftp = new SftpClient(connectionInfo)){
            
            sftp.Connect();
            //sftp.ChangeDirectory("/MyFolder");
            using (var uplfileStream = System.IO.File.OpenRead(fileName)){
                sftp.UploadFile(uplfileStream, fileName, true);
            }
            sftp.Disconnect();
        }
        return 0;
    }
}

Now you can call this Method to transfer a file to SFTP Server like this

SendFileToServer.Send("myFile.txt");

“myFile.txt” is the name of the file which should be located in your project root directory.

Let me know if you find any problem or comment If you find this Article helpful.

Here are more Articles you might be Interested

Generate QR Code Using ASP.NET CORE

– Creating Admin Panel in Asp.net Core MVC – Step by Step Tutorial

How to Create SOAP Web Services in Dotnet Core

– Top 10 .Net Core Features You need to know

– Dynamic Role-Based Authorization Asp.net Core