Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting :: How to Convert JSON And XML Object Into Class Using Visual Studio?

clock January 26, 2022 07:22 by author Peter

Creating classes based on JSON/XML responses, from APIs are the most usual work for all developers. Normally, if we want to convert a JSON/XML object into class, then we will check tools online for conversion. Hereafter no need for any online tool. Visual Studio can do this work and generate classes from a JSON/XML using just copy-paste. Do you believe this? Yes, there is. In this article, we are going to explore how to convert a JSON/XML object into the classes using Visual Studio.
Convert JSON into Classes

Step 1
Open your project/solution in Visual Studio 2019.

Step 2
Copy the JSON object for which you want to convert as a class. Let consider the below JSON object and i had copied it.
{
  "student": {
    "name": "Test",
    "degree": "IT",
    "subjects": [{
        "name" : "Computer Science",
        "mark": 95
    },
    {
        "name" : "Maths",
        "mark": 98
    }]
  }
}

Step 3
Go to the file where you want to create a class and place the cursor.

Step 4
Go to Edit -> Paste Special -> Paste JSON as Object

Convert JSON into Classes

Step 5
After clicking the "Paste JSON as Object" menu, the above JSON object is converted into class and pasted in the file as below.
public class Rootobject
{
    public Student student { get; set; }
}

public class Student
{
    public string name { get; set; }
    public string degree { get; set; }
    public Subject[] subjects { get; set; }
}

public class Subject
{
    public string name { get; set; }
    public int mark { get; set; }
}

 

You can convert any complex JSON object into the class using the above steps.

Convert XML into Classes

Step 1
Open your project/solution in Visual Studio.

Step 2
Copy the XML object for which you want to convert as a class.  Let consider the below XML object and i had copied it.
<?xml version="1.0" encoding="UTF-8" ?>
<student>
    <name>Test</name>
    <degree>IT</degree>
    <subjects>
        <name>Computer Science</name>
        <mark>95</mark>
    </subjects>
    <subjects>
        <name>Maths</name>
        <mark>98</mark>
    </subjects>
</student>

Step 5
After clicking the "Paste XML as Object" menu, the above XML object is converted into class and pasted in the file as below.
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class student
{

    private string nameField;
    private string degreeField;
    private studentSubjects[] subjectsField;
    private string[] textField;

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public string degree
    {
        get
        {
            return this.degreeField;
        }
        set
        {
            this.degreeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("subjects")]
    public studentSubjects[] subjects
    {
        get
        {
            return this.subjectsField;
        }
        set
        {
            this.subjectsField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string[] Text
    {
        get
        {
            return this.textField;
        }
        set
        {
            this.textField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class studentSubjects
{

    private string nameField;
    private byte markField;
    private string[] textField;

    /// <remarks/>
    public string name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    public byte mark
    {
        get
        {
            return this.markField;
        }
        set
        {
            this.markField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string[] Text
    {
        get
        {
            return this.textField;
        }
        set
        {
            this.textField = value;
        }
    }
}

Converting JSON/XML object into classes using copy-paste in Visual Studio is one of the great feature. Most of the developers are not aware of this feature in Visual Studio. Definitely, this feature has been used to reduce the developer's manual work (convert JSON/XML into class).


HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European Visual Studio Hosting - HostForLIFE :: How To Install Visual Studio Code?

clock January 4, 2022 08:20 by author Peter

Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and Unity).

In this article, will see how to install Visual Studio Code on your PC.

Follow the below steps for the same.

Step 1
Click here to navigate to Visual Studio Code official website.



Step 2
Click on Download for Windows.



Step 3
VSCodeUserSetup-x64-1.62.3.exe will be downloaded to your Downloads folder.

Step 4
Go to the Downloads folder and double click on the executable file.



Step 5
Click on I accept the agreement and Click on Next.

Step 6
Click on Next.


Step 7
Click on Next.

Step 8
Select Add “Open with Code” action to Windows Explorer file context menu and Add “Open with Code” action to Windows Explorer directory context menu, checkboxes.
Click on Next.



Step 9
Click on Install.

Installation is in progress.

 

Step 10
Click on Finish to launch the Visual Studio Code.


Step 10
Click on Finish to launch the Visual Studio Code.

Visual Studio Code is launched.

Hope you have successfully installed Visual Studio Code on your PC.
Please like and share your valuable feedback on this article.



European ASP.NET Core Hosting :: How To Install Multiple Versions Of Angular On The Same System?

clock December 22, 2021 06:50 by author Peter

In this article, we are going to discuss “how to install multiple Angular versions on the same computer”. This is an important interview question that was asked by many reputed IT companies.

USECASE
Google’s team is working hard to make Angular better and better and for that, they are releasing new versions frequently. Many times we fall into a situation where we have two projects developed in two different versions, and we need to support both.

This situation raises the requirement to install two different versions on the same computer.

Suppose we have 2 different projects like below
    Project 1 – Angular 12 – Install Locally.
    Project 2 – Angular 13 - Install Globally

In this case, we need two different versions to run both projects correctly.

We can do that using NVM. NVM permits us to do so. But here we are going to discuss using Angular CLI which is a more preferable way.
How to Install Multiple Angular Versions?

STEP 1 - Use the below command to install Angular 13 Globally.
npm install -g @angular/cli

Once Installation is done, we will check the version using the below command,
ng --version



I assume that you are already aware of how to create an Angular project, as the scope of this article is how to install multiple versions.

STEP 2 - Please create a project using Angular 13. If you don’t know then please create a project using the command mentioned in step 5. Kindly refer to this article to set up/install and create a project.

Create Project Folder for Angular Version 12.


STEP 3 - Open Command Prompt and set the working directory to “Angular12.1”.

STEP 4 - Now install angular 12 locally using the below command.


STEP 5 - Create a new project using the below command,
ng new “Angular122Project”

Below screen appear, once created successfully



STEP 6 - Execute Angular 12 Project using the below command. As we have created Angular 13 on port 4200. We will give a new port to Angular 12.
ng serve --port 4002

Install Multiple Angular Versions



Let's browse URL given in the above screen,

STEP 7 - I assume that we have created the Angular 13 Project using the above steps which are running at port 4200.



Let's browse the Angular 13 application using the given URL in the above image.



That’s all for this article. Hope you enjoyed it and find it useful.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European VB.NET Hosting - HostForLIFE :: Namespace Aliases In Visual Basic .NET

clock December 17, 2021 08:28 by author Peter

In Visual Basic .NET, it is possible to declare aliases for namespaces, giving the possibility of using more concise declarations, if the developer desires to do so.

Let's see an example: Typically, the use of StringBuilder class could follow the following three declarative ways:

Without Imports statement

    Dim s As New System.Text.StringBuilder("test")  
    s.Append("123")  

This kind of implementation requires the developer to declare the "s" variable writing down the path to the desired class, in our case StringBuilder, contained into System.Text namespace.

With Imports statement
    Imports System.Text  
    ' ...  
    Dim s As New StringBuilder("test")  
    s.Append("123")  


Using an Imports statement, the programmer can simply use the classes names, for the namespace(s) to be used will be declared at the beginning of the code.

Using Aliases
    Imports sb = System.Text.StringBuilder  
    '...  
    Dim s As New sb("test")  
    s.Append("123")  


The Imports statement could be implemented with customized names. In the example above, I have stated that in the rest of the code, the class System.Text.StringBuilder will be redefined as "sb". So, we can declare a new StringBuilder with the function "New sb()", accessing the same constructors possessed by System.Text.StringBuilder, being sb a simple alias of the real thing.



AngularJS Hosting Europe - HostForLIFE :: What Is Angular And The Latest Feature Release In Angular 13?

clock December 14, 2021 06:38 by author Peter

In this article, we are going to discuss Angular and the latest features released in Angular 13. I will post a series of articles on Angular 13. This is the first article of the series.

We will cover

    What is Angular?
    What is a Single Page Application?
    Important Feature release in Angular version 13

What is Angular?

Let’s see the below image to get a better understanding of what Angular is,

The above image describes the below 4 points, it says,

    Open Source
    Type Script-Based Framework
    Developed by Google.
    Used for Single Page Application.

Let’s combine all the above points and the Angular definition would be,

“Angular is an open-source, TypeScript framework created by Google for single page application using TypeScript and HTML.”

Angular is written in TypeScript and mainly used for

    Large Enterprise Application
    Single Page Application
    Progressive Web Application

Now the question is,

What is a Single Page Application? Let’s understand that,
SPA – Single Page Application

First we will discuss the traditional web page life cycle,


In traditional page life cycle,
The client sent a request to the server. Server renders a new HTML page. This triggers a page refresh in the browser.


In Single Page Application, 

  1. Page load successfully the first time. I mean Client sent a request to the server. The server renders a new HTML page. This trigges a page refresh in the browser.
  2. After that, all subsequent requests with the server happen through AJAX call. I mean client requests to server and server will provide only JSON data instead of HTML.

Important Features release in Angular version 13

The latest version of Angular is 13. Angular 13 was released on 04-Nov-2021. 

Below is a few important features release in Angular 13,

  1. Angular written in TypeScript.
  2. Latest Type version 4.4 support added in Angular 13.
  3. Node.js versions Older than v12.20 are no longer supported in Angular 13.
  4. Rxjs v7.0 library supported.
  5. Dynamically enabled/disabled building properties like min, max etc
  6. Error messaging is improved
  7. A simplified ViewContainerRef.createComponent API allows for the dynamic creation of components.
  8. IE11 support dropped.
  9. Restore history after canceled navigation.
  10. Accessibility improvements for angular material components
  11. Angular now supports the use of persistent build-cache by default for new v13 projects, which results in 68% improvement in build speed.
  12. Custom conditions can be set in ng_package.
  13. Angular CLI has been improved.
  14. Service worker cache is cleared in the safety worker to ensure stale or broken contents are not served in future requests.
  15. The error message has been improved for a missing animation trigger for the Platform browser.

That's all for this article. Hope you enjoy this article.



European ASP.NET Core Hosting :: Node.js API Authentication With JSON Web Tokens

clock December 7, 2021 08:38 by author Peter

In this article, we are going to cover how to access the JSON web token (jwt) and also to protect our routes by the JSON web token.
 
Have you ever thought about the process of authentication? What lies under the layers of abstraction and complexity? Nothing out of the ordinary. It's a method of encrypting data and generating a one-of-a-kind token that users can use to identify themselves. Your identity is verified with this token. It will verify your identity and grant you access to a variety of services. If you don't recognize any of these words, don't worry, I'll explain everything below.
 
Setup
Before we get started into this we should have few things installed in our machine.
    Visual Studio Code ->  VS Code
    Node.js -> Node.js

Prerequisites & Dependencies

Create a new folder with project name (NodeAuthAPI) and open the same folder in Visual Studio Code (VS Code)
 
Run the following command to initialize our package.json file.
    npm init --yes  

 Install all our remaining dependencies
    npm install express jsonwebtoken  

    npm install -g nodemon   

Why these Dependencies?
express - running on the server (Port number)
 
jsonwebtoken - This will be used to sign and verify Json web tokens.
 
nodemon - will use this to restart our server automatically whenever we make changes to our files.
 
Create a file named index.js inside the project.
 
Project Structure

Let's import the packages in index.js file
    const express = require("express");  
    const jwt = require("jsonwebtoken");  

 Now initialize the app variable with express
    const app = express();  

setup the port number for our server to process
    app.listen(5000,()=>console.log('listening on port 5000'));  

 Let's run and test whether our app is running under the same port number which we mentioned above.
 
Run the command in the terminal - nodemon  to check the output

Create a simple get method to check the output in Postman.
 
index.js
    app.get('/api',(req, res) => {  
        res.json({   
            message: 'Welcome to the API!',  
        });  
    });  


Postman

So it is confirmed that our get method is working as expected, Now configure the jwt setup to check with the actual authentication mechanism. Create a post API Login Method with Mock username and Email and also i have setup the token expiration seconds in the same method.

    app.post('/api/Login',(req, res) => {  
        //Mock user  
        const user ={  
            username: 'peter',  
            email: '[email protected]'  
        }  
        jwt.sign({user:user},'secretkey',{expiresIn: '30s'},(err,token)=>{  
            res.json({token})  
        })  
    })  

The token is generated with basic credentials, Now we need to validate another API with this token to access the credentials.
 
Create a function and verify the token which will be passed as a header
 Sample   Authorization :   Bearer <your token>

    //Access token  
    //Authorization : Bearer <access token>
      
    //Verify Token  
    function verifyToken(req, res,next) {  
        //Get Auth header value  
        const bearerHearder = req.headers['authorization'];  
        //check if bearer is undefined  
        if(typeof bearerHearder != 'undefined'){  
            //split at the space  
            const bearer = bearerHearder.split(' ');  
            //Get the token from array  
            const bearerToken = bearer[1];  
            // set the token  
            req.token = bearerToken;  
            //Next middleware  
            next();  
      
        }else{  
            //Forbidden  
            res.sendStatus(403);  
        }  
    }  


Let's create an API to validate this token
    // Post to Validate the API with jwt token  
    app.post('/api/validate',verifyToken,(req, res)=>{  
        jwt.verify(req.token,'secretkey',(err,authData)=>{  
            if(err){  
                res.sendStatus(403);  
            }else{  
                res.json({  
                    message: 'Validated',  
                    authData  
                });  
            }  
        });  
    });  


Testing with Postman

If you are trying to access the validate API without passing the token it will give us 403 Forbidden because of unauthorized access.
Now let's get the token first by accessing the Login API and then pass the same token as the header in the Validate API to get the access.

Note
After 30 sec the token will expire because we defined the expiration time in code, we need to get the token again by accessing the login API 

 



European ASP.NET Core Hosting :: How To Make Your Connection String Encrypted In ASP.NET Using C#?

clock December 6, 2021 06:07 by author Peter

INITIAL CHAMBER

    Open Visual Studio 2010 and create an empty website. Give a suitable name connectionstring_demo.
    In Solution Explorer you get your empty website. Add a web form, SQL Database. Here are the steps:

For Web Form

    connectionstring _demo (Your Empty Website) - Right Click, Add New Item, click Web Form. Name it connectionstring _demo.aspx.

For SQL Server Database
    connectionstring _demo (Your Empty Website) - Right Click, Add New Item, click SQL Server Database. Add Database inside the App_Data_folder.

DESIGN CHAMBER
    Now open your connectionstring _demo.aspx file, where we create our design for encrypting our Connection String.

connectionstring _demo.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html  
        xmlns="http://www.w3.org/1999/xhtml">  
        <head runat="server">  
            <title></title>  
        </head>  
        <body>  
            <form id="form1" runat="server">  
                <div>  
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"   
    Text="Press to Encrypt your Connection String" />  
                </div>  
                <p>  
     </p>  
                <p>  
     </p>  
                <p>  
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
                </p>  
            </form>  
        </body>  
    </html>  


CODE CHAMBER:
    Open your connectionstring _demo.aspx.cs and write some code so that our application starts working.

connectionstring _demo.cs
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Configuration;  
    using System.Web.Configuration;  
    using System.Web.UI.WebControls;  
    public partial class _Default: System.Web.UI.Page  
    {  
        const string PROVIDER = "DataProtectionConfigurationProvider";  
        protected void Page_Load(object sender, EventArgs e)  
        {}  
        protected void Button1_Click(object sender, EventArgs e)  
        {  
            Configuration con = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);  
            ConnectionStringsSection sect = con.ConnectionStrings;  
            sect.SectionInformation.ProtectSection(PROVIDER);  
            con.Save();  
            Label1.Text = "Your Connection String is Encrypted Now";  
            Label1.Text += "Your Connection String is:" + ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString;  
        }  
    }  

OUTPUT CHAMBER

Open your Web.config File


    <?xml version="1.0"?>  
    <!--  
    For more information on how to configure your ASP.NET application, please visit  
    http://go.microsoft.com/fwlink/?LinkId=169433  
    -->  
    <configuration>  
        <system.web>  
            <compilation debug="false" targetFramework="4.0" />  
        </system.web>  
        <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">  
            <EncryptedData>  
                <CipherData>  
                    <CipherValue>  
      
    // Your encrypted string  
      
      
    </CipherValue>  
                </CipherData>  
            </EncryptedData>  
        </connectionStrings>  
    </configuration>  

Hope you liked this. Thank you for reading. Have a good day.

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.




European Blazor Hosting - HostForLIFE :: TypeScript With Blazor

clock November 26, 2021 07:36 by author Peter

This particular blog will help you to setup and use TypeScript in a Blazor client project.

What is TypeScript ?
TypeScript is a strongly typed programing language built on top of Javascript. TypeScript have lot of pros over the Javascript which includes the power of Object Oriented Programing. TypeScript supports concepts from Object Oriented Programing and will be able to build a scalable and well organised code compared to JavaScript. TypeScript is always very much predictable. Everything in it always stays in the same way it was defined, if you decalre a variable with a type as boolean , it will always stays as boolean.
How to integrate TypeScript with Blazor?

In order to integrate TypeScript with blazor we can follow the below steps,
Install Microsoft.TypeScript.MSBuild nuget package in Blazor client project
Create a TypeScript File in the project
Create a class and the method which to be invoed from blazor C# code

ex

namespace common {
    class Prompt {
        public showAlert() {
            alert("thhis is a test");
        }
    }
}


Now we need to create a method which will return an instance of Prompt class.
export function getPromptInstance(): Prompt {
    return new Prompts();
}


Thats all from TypeScript side. Now lets move to C# side.
Create a Blazor component from where we need to access this type script method
Invoke the getPromptInstance() to get the instance of Prompt class from the razor or cs file using IJSRuntime object.

ex
var promptObject = await this._jSRuntime.InvokeAsync<IJSObjectReference>("common.getPromptInstance");

Now we can invoke the showAlert() using the prompt object
await promptObject.InvokeVoidAsync("showAlert");

Rebuild the solution and make sure .js and .js.map version of newly added TypeScript file has been created as below



European PHP Hosting - HostForLIFE :: User Management With Location Track Using PHP/MySQL

clock November 23, 2021 06:25 by author Peter

In this article, I will explain how to perform user management with their location in PHP using XAMPP server. This application is used to add the user name, email, mobile number and address and is also able to edit details and remove users. Download the XAMPP server in https://www.apachefriends.org/download.html. We can learn using this article curd operation and basic core PHP and MySQL server databases connection. Also all added user can view the google map location.

Here will see MySQL database connection, fetch all user details also insert, update and delete.
Create DB and Table in MySQL database

Using phpMyAdmin XAMPP server we can create our db.My database name is usermanagement.

To create table follow this below set of queries.

-- Database: `usermanagement`
-- ---------------------------
-- Table structure for table `tblusers`

CREATE TABLE `tblusers` (
  `ID` int(10) NOT NULL,
  `FirstName` varchar(200) DEFAULT NULL,
  `LastName` varchar(200) DEFAULT NULL,
  `MobileNumber` bigint(10) DEFAULT NULL,
  `Email` varchar(200) DEFAULT NULL,
  `Address` mediumtext DEFAULT NULL,
  `CreationDate` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `Country` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Dumping data for table `tblusers`

INSERT INTO `tblusers` (`ID`, `FirstName`, `LastName`, `MobileNumber`, `Email`, `Address`, `CreationDate`, `Country`) VALUES
(13, 'Peter', 'S', 9879887711, '[email protected]', 'New York', '2020-10-16 13:51:16', NULL),
(14, 'Scott', 's', 4654564111, '[email protected]', 'London', '2020-10-16 15:21:12', NULL),
(20, 'Leo', 'boss', 908776543, '[email protected]', 'london', '2021-03-03 05:42:04', NULL),
(34, 'Thea', 's', 2323298830, '[email protected]', 'London\r\n', '2021-10-19 06:36:47', NULL),
(36, 'Mark', 'd', 2987123390, '[email protected]', 'Sweden', '2021-10-19 06:36:02', NULL),
(43, 'Friedrich', 'f', 3333333333, '[email protected]', 'Germany', '2021-10-19 06:36:28', NULL);

-- Indexes for dumped tables

-- Indexes for table `tblusers`
ALTER TABLE `tblusers`
  ADD PRIMARY KEY (`ID`);

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `tblusers`

ALTER TABLE `tblusers`
  MODIFY `ID` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48;
COMMIT;

PHP database connection using MySQL
Create a database.php file and write below code to connect Database
<?php
$con=mysqli_connect("localhost","root","","usermanagement");
if(mysqli_connect_errno($con))
{
  echo "connection failed".mysqli_connect_error($con);
}
?>


index.php
index.php file is our application first page to view all added users.
<?php
$ret = mysqli_query($con, "select * from tblusers");
$cnt = 1;
$row = mysqli_num_rows($ret);
if ($row > 0)
{
    while ($row = mysqli_fetch_array($ret))
    {

?>
    <!--Fetch the Records -->
        <tr>
            <td><?php echo $cnt; ?></td>
            <td><?php echo $row['FirstName']; ?> <?php echo $row['LastName']; ?></td>
            <td><?php echo $row['Email']; ?></td>
            <td><?php echo $row['MobileNumber']; ?></td>
            <td> <?php echo $row['CreationDate']; ?></td>
            <td>
  <a href="read.php?viewid=<?php echo htmlentities($row['ID']); ?>" class="view" title="View" data-toggle="tooltip"><i class="material-icons">&#xE417;</i></a>
                <a href="edit.php?editid=<?php echo htmlentities($row['ID']); ?>" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                <a href="index.php?delid=<?php echo ($row['ID']); ?>" class="delete" title="Delete" data-toggle="tooltip" onclick="return confirm('Do you really want to Delete ?');"><i class="material-icons">&#xE872;</i></a>
            </td>
      <td> <a href="weblocation.php?id=<?php echo ($row['ID']); ?>" class="location" title="location" data-toggle="tooltip"><i class="fa fa-map-marker" aria-hidden="true"></i></a></td>
        </tr>
        <?php
        $cnt = $cnt + 1;
    }
}


insert.php
insert.php file is used to add user information like user name, email, mobile number, and address.
<?php
//Databse Connection file
include ('dbconnection.php');
if (isset($_POST['submit']))
{
    //getting the post values
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contno = $_POST['contactno'];
    $email = $_POST['email'];
    $add = $_POST['address'];
    //Query select
    $selectquery = mysqli_query($con, "select Email,MobileNumber from  tblusers");
    $cnt = 1;
    while ($row = mysqli_fetch_array($selectquery))
    {

        if ($row['Email'] == $email)
        {

            echo "<script>alert('email is already exists');</script>";
            echo "<script type='text/javascript'> document.location ='insert.php'; </script>";
        }
        if ($row['MobileNumber'] == $contno)
        {
            echo "<script>alert('contactno is already exists');</script>";
            echo "<script type='text/javascript'> document.location ='insert.php'; </script>";
        }
        $cnt = $cnt + 1;
    }
    // Query for data insertion
    $query = mysqli_query($con, "insert into tblusers(FirstName,LastName, MobileNumber, Email, Address) value('$fname','$lname', '$contno', '$email', '$add' )");
    if ($query)
    {
        echo "<script>alert('You have successfully inserted the data');</script>";
        echo "<script type='text/javascript'> document.location ='index.php'; </script>";
    }
    else
    {
        echo "<script>alert('Something Went Wrong. Please try again');</script>";
    }
}
?>

edit.php
We can edit all user details in edit.php
<?php
//Database Connection
include ('dbconnection.php');
if (isset($_POST['submit']))
{
    $eid = $_GET['editid'];
    //Getting Post Values
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $contno = $_POST['contactno'];
    $email = $_POST['email'];
    $add = $_POST['address'];
    //Query for data updation
    $query = mysqli_query($con, "update  tblusers set FirstName='$fname',LastName='$lname', MobileNumber='$contno', Email='$email', Address='$add' where ID='$eid'");

    if ($query)
    {
        echo "<script>alert('You have successfully update the data');</script>";
        echo "<script type='text/javascript'> document.location ='index.php'; </script>";
    }
    else
    {
        echo "<script>alert('Something Went Wrong. Please try again');</script>";
    }
}
?>


delete.php
delete.php file is used to remove each user separately
<?php
//database conection  file
include ('dbconnection.php');
//Code for deletion
if (isset($_GET['delid']))
{
    $rid = intval($_GET['delid']);
    $sql = mysqli_query($con, "delete from tblusers where ID=$rid");
    echo "<script>alert('Data deleted');</script>";
    echo "<script>window.location.href = 'index.php'</script>";
}
?>


weblocation.php
Location of users we can track via Google Maps.
<?php
include ('dbconnection.php');
$eid = $_GET['id'];
$ret = mysqli_query($con, "select Address from tblusers where ID='$eid'");
$row = mysqli_fetch_array($ret);
$selectall = mysqli_query($con, "select Address,FirstName,LastName from tblusers where Id !='$eid'");
if (mysqli_num_rows($selectall) > 0) echo "<b>Same Location users</b><br>";
while ($rows = mysqli_fetch_array($selectall))
{
    if ($rows['Address'] == $row['Address'])
    {
        $match = 1;
        echo $rows['FirstName'] . '' . $rows['LastName'] . '<br>';

    }
}
echo "<br>";
$add = $row['Address'];
?>
<html>
<div class="text-center"><a href="index.php">Back</a></div>
<div>
 <iframe width="50%" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?q=<?=$add; ?>&amp;ie=UTF8&amp;&amp;output=embed"></iframe><br />
</div>
</html>



European VB.NET Hosting - HostForLIFE :: Invoke Method To Update UI From Secondary Threads In VB.NET

clock November 17, 2021 07:36 by author Peter

As many developers well knows it's not possible -- using .NET Framework -- to realize a direct interaction between processes which run on threads different from the one on which the UI resides (typically, the main thread of the program). We are in a situation from which we can exploit the many advantages of multi-threading programming to execute parallel operations, but if those tasks must return an immediate graphical result, we won't be able to access the user controls from those processes.

In this brief article, we'll see how it can be possible, through the Invoke method, which is available to all controls through the System.Windows.Form namespace, to realize such functionality in order to execute a graphic refresh and update through delegates.

Delegates
The MSDN documentation states delegates are constructs which could be compared to the pointer of functions in languages like C or C++. Delegates incapsulate a method inside an object. The delegate object could then be passed to code which will execute the referenced method, or method that could be unknown during the compilation phase of the program itself. Delegates could be EventHandler instances, MethodInvoker-type objects, or any other form of object which ask for a void list of parameters.

Here follows a pretty trivial, though effective, example of their use.

Basic example

Let's consider a WinForm on which will reside a Label, Label2. That label must be use to show an increasing numeric counter. Since we desire to execute the value increase on a separated thread, we will incur into the named problem. Let's see why. First of all, we will write the code that will execute the increment of our numerical value on a secondary task from the main one, trying to update Label2, to observe the result of the operation.
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
      Dim n As Integer = 0  
       
      Dim t As New Task(New Action(Sub()  
                                  n += 1  
                    Label2.Text = n.ToString  
         End Sub))  
     t.Start()  
    End Sub


At runtime, the raised exception will attest what we saw up to here: it's not possible to modify an object properties (in reality, some of them), if the object itself is managed from a different thread other than the main one.

Yet, the Label control has - like any other control - a method named Invoke, through which we can call delegates toward the main thread. We can rewrite our method like the following. This time, for the sake of completeness, inserting our increment in a loop, to show how Invoke can work inside loops too.
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
      Dim n As Integer = 0  
       
      Dim t As New Task(New Action(Sub()  
      For n = 1 To 60000  
       
      Label2.Invoke(Sub()  
               Label2.Text = n.ToString  
               End Sub)  
      Next  
     End Sub))  
      t.Start()  
    End Sub


Running the program we can see how the graphical data update will be correctly executed, simultaneously with the development of the numerical variable.

That's -- as aforementioned -- a very basic and trivial example, but in a delegate context it's possible to execute an arbitrary number of operations of different complexity, making it possible to realize any feature in regarding of cross-threading operations.

Update UI from different tasks
To explore the subject further, we'll see now a more demanding example, in terms of resources needed. In this case, we'll make a program that will process simultaneously many text files, to update the UI to show what a single thread is doing in a given moment.

Example definition
We have 26 different text files, each of which contains a variable number of words, mainly italian but not exclusively. Those words begin with a particular letter: for example, the file "dizionario_a.txt" will contain only words which stars with "a", "dizionario_b.txt" only those which starts with "b", and so on. We want to write a program which possesses 26 labels and, starting a task for each letter, will proceed in inserting every read word in a variable of type List(Of String). Each task must show the processed word, so that every thread will execute -- through the Invoke() method -- the refreshing of the content of the Label on which it works.

Let's take a look to the code, to make some considerations after it.
    imports System.IO  
       
    public class Form1  
       
        Dim wordList As New List(Of String)  
       
        Public Sub AddWords(letter As Char, lbl As Label)  
            Using sR As New StreamReader(Application.StartupPath & "\text\dizionario_" & letter & ".txt")  
                While Not sR.EndOfStream  
                    Dim word As String = sR.ReadLine  
       
                    wordList.Add(word)  
       
                    lbl.Invoke(Sub()  
                          lbl.Text = word  
                          counter.Text = wordList.Count.ToString  
                          Me.Refresh()  
                        End Sub)  
                End While  
            End Using  
       
            lbl.ForeColor = Color.Green  
        End Sub  
       
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
            Me.DoubleBuffered = True  
       
            Dim _x As Integer = 8  
            Dim _y As Integer = 40  
       
            For ii As Integer = Asc("a") To Asc("z")  
       
                Dim c As New Label  
                c.Name = "Label" & ii.ToString("000")  
                c.Text = "---"  
                c.Top = _y  
                c.Left = _x  
                Me.Controls.Add(c)  
       
                _y += 20  
                If _y > 180 Then  
                    _y = 40  
                    _x += 120  
                End If  
       
                Dim j As Integer = ii  
                Dim t As New Task(Sub()  
                      AddWords(Chr(j), CType(Me.Controls("Label" & j.ToString("000")), Label))  
                     End Sub)  
       
                t.Start()  
            Next  
       
        End Sub  
       
    End Class


The project is a simple WinForms program. During Load() event, we'll create all the Labels we need, starting the tasks that will use, each of them on a different word, the AddWords() subroutine, to process a single dictionary (dictionary files will be found in the downloadable project, at the end of the article). We will see, taking a look at the loop in the Load() event, that each created task is launched immediately, letting the OS the worries of queueing those processes which aren't immediately manageable.

Each task, calling the AddWords() subroutine, will provide in: 1) opening the file having a given letter, 2) read each line, 3) save that value in the List wordList. We will also note a calling to the method Invoke() on the Label passed as argument to the subroutine. An interesting particular is that inside a single Invoke() a developer can manage more than a single UI update. In our specific case, we can see how the Label is updated, updating also the one named "counter", which we will use to show the global number of words read to a given moment. Moreover, to help the graphical rendering of our controls, we will call upon the Refresh() method of the Form itself, though - doing so - we will impair the overall performances, since the program will dedicate part of its cycles to refresh the Form and all its children, at every iteration.

As we can see running the code, or through the following video, the update of the content of our controls will happen in a concerted way, allowing each task to modify the value of controls which constitutes the UI of our program.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in