Zelma  Gerlach

Zelma Gerlach

1623613440

Pick The Google Cloud Region That’s Right for You

When it comes to sustainability, we get more done when we move together. That’s why Google Cloud partners with nonprofits, research organizations, governments, and businesses to build technology and tools to accelerate meaningful change.

Technologies like machine learning are proving to be invaluable for tackling unique challenges like identifying species in biodiversity and restoration projects such as those being done by Wildlife Insights. Data analytics tools like BigQuery can deliver insights into real-time energy consumption data, helping energy managers at E.ON make decisions that reduce costs and CO2 footprint. And hyper-efficient infrastructure is helping customers like Carrefour reduce their energy use. Using all the tools we have at Google Cloud, we’re committed to helping make your digital transformation a sustainable one too.

As we continue to operate the cleanest cloud in the industry we’re working with a growing group of cloud customers focused on reducing the carbon impact of their operations. Over 90% of global IT leaders plan to or currently report on sustainability metrics, with 26% of those leaders accelerating emissions reduction projects in the past year1. In the past year we’ve worked with over 50 customers to evaluate their IT estates for their carbon impact. From digital image libraries to huge data lakes, we’ve seen potential net-carbon reductions from a few thousand kg of CO2e to many kilotons, combining the determination of our customers and Google’s net carbon neutral cloud.

#google cloud platform #sustainability #cloud

What is GEEK

Buddha Community

Pick The Google Cloud Region That’s Right for You
Sean Robertson

Sean Robertson

1574307124

How to add CRUD Operations to Angular using ASP.NET Web API and MongoDB

MongoDB is a NoSQL, free, open source, high-performance, and cross-platform document-oriented database. MongoDB was developed by the 10gen company that is now called MongoDB Inc. MongoDB is written in C++ and stores data in a flexible, JSON-like format with a dynamic schema.

Prerequisites

  • We should have the basic knowledge of Angular, MongoDB, and Web API.
  • The Visual Studio Code IDE should be installed.
  • Robo 3T or Studio 3T should be installed.

Create a Database and Collection in MongoDB

MongoDB Environment Setup

Check how to set up the MongoDB environment and Robo 3T, from here.

Step 1

Now, open Robo 3T and connect to the local server.
Connecting to localhost

Step 2

Create a database with the name “employee” using Robo 3T (Check Link).

Create a Web API Project

Step 1

Open Visual Studio and create a new project.
Creating a project

Change the name to CrudWithMongoDB.

Changing project name

Choose the WEB API template.

Step 2

Now, add the MongoDB Driver for C# using NuGet Package Manager.

Go to Tools>>NuGet Package Manager >> Manage NuGet package for Solution.

Managing NuGet package

Step 3

Right-click the Models folder and add two classes, Employee and Status. Now, paste the following codes in these classes.

Add the required namespaces in the Employee class.

using MongoDB.Bson;  
using MongoDB.Bson.Serialization.Attributes;  

Employee class

 public class Employee  
       {  
           [BsonRepresentation(BsonType.ObjectId)]  
           public String Id { get; set; }  
           public string Name { get; set; }  
           public string  { get; set; }  
           public string Address { get; set; }  
           public string City { get; set; }  
           public string Country { get; set; }  
       }  

Status class

  public class Status  
       {  
           public string Result { set; get; }  
           public string Message { set; get; }  
       }  

Step 4

Now, add a connection string in the web.config file and add the following line in the App Settings section of that file.

<add key="connectionString" value="mongodb://localhost"/>    

Step 5

Right-click on the Controllers folder and add a new controller. Name it “Emp controller.”

Add the following namespaces in the Emp controller.

using MongoDB.Driver;  
using MongoDB.Bson;  
using CrudWithMongoDB.Models;  

Now, add a method to insert data into the database for inserting employee details.

    [Route("InsertEmployee")]  
           [HttpPost]  
           public object Addemployee(Employee objVM)  
           {  
               try  
               {   ///Insert Emoloyeee  
                   #region InsertDetails  
                   if (objVM.Id == null)  
                   {  
                       string constr = ConfigurationManager.AppSettings["connectionString"];  
                       var Client = new MongoClient(constr);  
                       var DB = Client.GetDatabase("Employee");  
                       var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                       collection.InsertOne(objVM);  
                       return new Status  
                       { Result = "Success", Message = "Employee Details Insert Successfully" };  
                   }  
                   #endregion  
                   ///Update Emoloyeee  
                   #region updateDetails  
                   else  
                   {  
                       string constr = ConfigurationManager.AppSettings["connectionString"];  
                       var Client = new MongoClient(constr);  
                       var Db = Client.GetDatabase("Employee");  
                       var collection = Db.GetCollection<Employee>("EmployeeDetails");  

                       var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  

                       return new Status  
                       { Result = "Success", Message = "Employee Details Update Successfully" };  
                   }  
                   #endregion  
               }  

               catch (Exception ex)  
               {  
                   return new Status  
                   { Result = "Error", Message = ex.Message.ToString() };  
               }  

           }  

Add a new method to delete employee details.

#region DeleteEmployee  
     [Route("Delete")]  
     [HttpGet]  
     public object Delete(string id)  
     {  
         try  
         {  
             string constr = ConfigurationManager.AppSettings["connectionString"];  
             var Client = new MongoClient(constr);  
             var DB = Client.GetDatabase("Employee");  
             var collection = DB.GetCollection<Employee>("EmployeeDetails");  
             var DeleteRecored = collection.DeleteOneAsync(  
                            Builders<Employee>.Filter.Eq("Id", id));  
             return new Status  
             { Result = "Success", Message = "Employee Details Delete  Successfully" };  

         }  
         catch (Exception ex)  
         {  
             return new Status  
             { Result = "Error", Message = ex.Message.ToString() };  
         }  

     }  
     #endregion  

Add a method to get Employee details.

  #region Getemployeedetails  
           [Route("GetAllEmployee")]  
           [HttpGet]  
           public object GetAllEmployee()  
           {  
               string constr = ConfigurationManager.AppSettings["connectionString"];  
               var Client = new MongoClient(constr);  
               var db = Client.GetDatabase("Employee");  
               var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
               return Json(collection);  

           }  
           #endregion  

Add a method to get Employee details by Id.

#region EmpdetaisById  
     [Route("GetEmployeeById")]  
     [HttpGet]  
     public object GetEmployeeById(string id)  
     {  
         string constr = ConfigurationManager.AppSettings["connectionString"];  
         var Client = new MongoClient(constr);  
         var DB = Client.GetDatabase("Employee");  
         var collection = DB.GetCollection<Employee>("EmployeeDetails");  
         var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
         return Json(plant);  

     }  
     #endregion 

Here is the complete Emp controller code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using MongoDB.Driver;  
using MongoDB.Bson;  
using CrudWithMongoDB.Models;  
using System.Configuration;  

namespace CrudWithMongoDB.Controllers  
{  
    [RoutePrefix("Api/Employee")]  
    public class EmpController : ApiController  
    {  
        [Route("InsertEmployee")]  
        [HttpPost]  
        public object Addemployee(Employee objVM)  
        {  
            try  
            {   ///Insert Emoloyeee  
                #region InsertDetails  
                if (objVM.Id == null)  
                {  
                    string constr = ConfigurationManager.AppSettings["connectionString"];  
                    var Client = new MongoClient(constr);  
                    var DB = Client.GetDatabase("Employee");  
                    var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                    collection.InsertOne(objVM);  
                    return new Status  
                    { Result = "Success", Message = "Employee Details Insert Successfully" };  
                }  
                #endregion  
                ///Update Emoloyeee  
                #region updateDetails  
                else  
                {  
                    string constr = ConfigurationManager.AppSettings["connectionString"];  
                    var Client = new MongoClient(constr);  
                    var Db = Client.GetDatabase("Employee");  
                    var collection = Db.GetCollection<Employee>("EmployeeDetails");  

                    var update = collection.FindOneAndUpdateAsync(Builders<Employee>.Filter.Eq("Id", objVM.Id), Builders<Employee>.Update.Set("Name", objVM.Name).Set("Department", objVM.Department).Set("Address", objVM.Address).Set("City", objVM.City).Set("Country", objVM.Country));  

                    return new Status  
                    { Result = "Success", Message = "Employee Details Update Successfully" };  
                }  
                #endregion  
            }  

            catch (Exception ex)  
            {  
                return new Status  
                { Result = "Error", Message = ex.Message.ToString() };  
            }  

        }  

        #region Getemployeedetails  
        [Route("GetAllEmployee")]  
        [HttpGet]  
        public object GetAllEmployee()  
        {  
            string constr = ConfigurationManager.AppSettings["connectionString"];  
            var Client = new MongoClient(constr);  
            var db = Client.GetDatabase("Employee");  
            var collection = db.GetCollection<Employee>("EmployeeDetails").Find(new BsonDocument()).ToList();  
            return Json(collection);  

        }  
        #endregion  
        #region EmpdetaisById  
        [Route("GetEmployeeById")]  
        [HttpGet]  
        public object GetEmployeeById(string id)  
        {  
            string constr = ConfigurationManager.AppSettings["connectionString"];  
            var Client = new MongoClient(constr);  
            var DB = Client.GetDatabase("Employee");  
            var collection = DB.GetCollection<Employee>("EmployeeDetails");  
            var plant = collection.Find(Builders<Employee>.Filter.Where(s => s.Id == id)).FirstOrDefault();  
            return Json(plant);  

        }  
        #endregion  
        #region DeleteEmployee  
        [Route("Delete")]  
        [HttpGet]  
        public object Delete(string id)  
        {  
            try  
            {  
                string constr = ConfigurationManager.AppSettings["connectionString"];  
                var Client = new MongoClient(constr);  
                var DB = Client.GetDatabase("Employee");  
                var collection = DB.GetCollection<Employee>("EmployeeDetails");  
                var DeleteRecored = collection.DeleteOneAsync(  
                               Builders<Employee>.Filter.Eq("Id", id));  
                return new Status  
                { Result = "Success", Message = "Employee Details Delete  Successfully" };  

            }  
            catch (Exception ex)  
            {  
                return new Status  
                { Result = "Error", Message = ex.Message.ToString() };  
            }  

        }  
        #endregion  
    }  
}  

Step 6

Now, let’s enable CORS. Go to Tools, open NuGet Package Manager, search for Cors, and install the Microsoft.Asp.Net.WebApi.Cors package.

Installing Microsoft.Asp.Net.Web.Cors package

Open Webapiconfig.cs and add the following lines.

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");    
config.EnableCors(cors);   

Create an Project

Step 1

Create an Angular 7 project with the name “CrudwithMongoDB” by using the following command.

 ng new CrudwithMongoDB

Step 2

Open Visual Studio Code, open the newly created project, and add bootstrap to this project.

npm install bootstrap --save

Step 3

Now, create two components for displaying the employee list page and adding a new employee page. To create the components, open terminal and use the following commands.

ng g c employee
ng g c addemployee

Step 4

Create a class named “employee” by using the following command.

ng g class employee

Add the required properties in the class.

export class Employee {  
    Id: string;  
    Name: string;  
    Department: string;  
    Address: string;  
    City: string;  
    Country: string;  
} 

Step 5

Create a service to call the Web API.

ng g s emprecord

Step 6

Open the emprecord service and import the required packages and classes. Add the following lines of code in the emprecord.service.ts file.

    import { Injectable } from '@angular/core';  
    import { Observable } from "rxjs";  
    import {HttpHeaders, HttpClient } from "@angular/common/http";  
    import { Employee } from "../app/employee";  
    @Injectable({  
      providedIn: 'root'  
    })  
    export class EmprecordService {  
       Url="http://localhost:14026/Api/Employee/";  
      constructor(private http:HttpClient) { }  
       InsertEmployee(employee:Employee)  
       {  
         debugger;  
        const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
         return this.http.post<Employee[]>(this.Url+'/InsertEmployee/', employee,httpOptions)  
       }  
       GetEmployeeRecord():Observable<Employee[]>  
       {  
         debugger;  
        return this.http.get<Employee[]>(this.Url+"/GetAllEmployee")  
       }  
       DeleteEmployee(id:string):Observable<number>  
       {  
         debugger;  
        return this.http.get<number>(this.Url + '/Delete/?id='+id);  
       }  
       GetEmployeeById(id:string)  
       {  
        return this.http.get<Employee>(this.Url + '/GetEmployeeById/?id=' + id);  
       }  
       UpdatEmplouee(employee:Employee)  
       {  
        debugger;  
        const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
         return this.http.post<Employee[]>(this.Url+'/UpdateEmployee/', employee,httpOptions)  
       }  

    }  

Step 7 - Add Paging and Searching

To add paging and searching, install the following library in the project. For pagination:

npm install --save ngx-pagination  

For searching:

npm i ng2-search-filter --save  

Export and import both these directives in the app.module.ts file.

import {NgxPaginationModule} from 'ngx-pagination';  
import { Ng2SearchPipeModule } from 'ng2-search-filter';  

Step 8

Now, open addemployee.component.html and add the following HTML.


    <div class="container" style="padding-top:40px;">    
      <div class="row">    
        <div class="col-md-10 mx-auto">    
          <div class="card mx-4">   
            <div class="card-head p-4">  
                <div class="col-sm-12 btn btn-success">  
                    Employee's Information  
                  </div>  
            </div>   
            <div class="card-body p-4">    
         <form [formGroup]="Addemployee" (ngSubmit)="onFormSubmit(Addemployee.value)">  
        <div class="col-sm-12">  
          <div class="card-body">  
            <!-- <div class="row"> -->  
            <div class="form-group ">  

              <label class="col-sm-2 control-label" for="Name">Name</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter name" formControlName="Name">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Department">Department</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Department" formControlName="Department">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Address">Address</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Address" formControlName="Address">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="City">City</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter City" formControlName="City">  
              </div>  
            </div>  
            <div class="form-group ">  
              <label class="col-sm-2 control-label" for="Country">Country</label>  
              <div class="col-sm-10">  
                <input type="text" class="form-control" placeholder="Enter Country" formControlName="Country">  
              </div>  
            </div>  

          </div>  
        </div>  
        <div class="col-6 text-right">    
            <button class="btn btn-primary px-10" type="submit">Add </button>  
          </div>  
      </form>  
          </div>    
        </div>    
      </div>    
      </div>   
    </div>   

Step 9

Open the addemployee.componet.ts file and add the following lines.

	import { Component, OnInit } from '@angular/core';  
    import { HttpClient } from "@angular/common/http";  
    import { FormGroup, FormControl } from '@angular/forms';  
    import { EmprecordService } from "../../emprecord.service";  
    import { Employee } from "../../employee";  
    import { Observable } from "rxjs";  
    import { identifierModuleUrl } from '@angular/compiler';  
    import { Router } from '@angular/router';  
    @Component({  
      selector: 'app-addemployee',  
      templateUrl: './addemployee.component.html',  
      styleUrls: ['./addemployee.component.css']  
    })  
    export class AddemployeeComponent implements OnInit {  
      massage: string;  
      dataSaved = false;  
      Addemployee:FormGroup;  
      EmployeeIdUpdate = "0";  
      constructor(private router: Router,private emprecordService:EmprecordService) { }  

      InsertEmployee(employee:Employee)  
      {  
    debugger;  
        if (this.EmployeeIdUpdate != "0") employee.Id=this.EmployeeIdUpdate;  
          this.emprecordService.InsertEmployee(employee).subscribe(  
            ()=>  
            {  
              if (this.EmployeeIdUpdate == "0") {  
                this.massage = 'Saved Successfully';  

              }  
              else  
              {  
                this.massage = 'Update Successfully';  
              }  
              this.dataSaved = true;  
              this.router.navigate(['/employee']);  
            })  
      }  
      onFormSubmit() {  
        const Emp = this.Addemployee.value;  
        this.InsertEmployee(Emp);  
      }  

      EmployeeEdit(id: string) {  
        debugger;  
        this.emprecordService.GetEmployeeById(id).subscribe(emp => {  
          this.massage = null;  
          this.dataSaved = false;  
          debugger;  
          this.EmployeeIdUpdate=id;  
          this.Addemployee.controls['Name'].setValue(emp.Name);  
          this.Addemployee.controls['Department'].setValue(emp.Department);  
          this.Addemployee.controls['City'].setValue(emp.City);  
          this.Addemployee.controls['Country'].setValue(emp.Country);  
          this.Addemployee.controls['Address'].setValue(emp.Address);  
        });  
        debugger;  
      }  
      clearform() {  
        debugger;  
        this.Addemployee.controls['Name'].setValue("");  
        this.Addemployee.controls['Department'].setValue("");  
        this.Addemployee.controls['Address'].setValue("");  
        this.Addemployee.controls['City'].setValue("");  
        this.Addemployee.controls['Country'].setValue("");  

      }  
      ngOnInit() {  
        this.Addemployee = new FormGroup({  

          Name: new FormControl(),  
          Department:new FormControl(),  
          Address:new FormControl(),  
          City:new FormControl(),  
          Country:new FormControl(),  
      });  
      let Id = localStorage.getItem("id");  
    if(Id!=null)  
    {  
      this.EmployeeEdit(Id) ;  
     }}  
    }  

Step 10

Open employee.componet.html and add this HTML.


    <div class="container" style="margin-bottom:20px;padding-top:20px;">  
      <div class="row">  
        <div class="col-sm-12 btn btn-success">  
          Employee's Information  
        </div>  
      </div>  
      <div class="col-sm-12" style="margin-bottom:20px;padding-top:20px;">  
        <div class="row">  
          <div class="col-sm-6">  
            <button type="button" class="btn btn-primary" data-toggle="modal" routerLink="/addemployee">  
              Add New Employee  
            </button>  
          </div>  
          <div class="col-sm-6">  
            <input class="form-control" type="text" name="search" [(ngModel)]="filter" placeholder="Search">  
          </div>  
        </div>  
      </div>  
    </div>  
    <div class="container" style="padding-top:20px;">  
      <table class="table table-striped">  
        <thead class="thead-dark">  
          <th>Name</th>  
          <th>Department</th>  
          <th>Address</th>  
          <th>City</th>  
          <th>Country</th>  
          <th>Action</th>  
        </thead>  
        <tbody>  
          <tr *ngFor="let e of emp | async|filter:filter| paginate: { itemsPerPage: 5, currentPage: p } ; let i=index">  
            <td>{{e.Name}}</td>  
            <td>{{e.Department}}</td>  
            <td>{{e.Address}}</td>  
            <td>{{e.City}}</td>  
            <td>{{e.Country}}</td>  
            <td>  
              <div class="btn-group">  
                <button type="button" class="btn btn-primary mr-1" (click)="EmployeeEdit(e.Id)">Edit</button>  
                <button type="button" class="btn btn-danger mr-1" (click)="Deleteemployee(e.Id)">Delete</button>  
              </div>  
            </td>  
          </tr>  
        </tbody>  
      </table>  
      <ul class="pagination">  
        <pagination-controls (pageChange)="p = $event"></pagination-controls>  
      </ul>  
    </div>  

Step 11

Open employee.componet.ts file and add the following lines.

	import { Component, OnInit } from '@angular/core';  
    import { Employee } from "../employee";  
    import { EmprecordService } from "../emprecord.service";  
    import { Observable } from "rxjs";  
    import { Router } from '@angular/router';  
    @Component({  
      selector: 'app-employee',  
      templateUrl: './employee.component.html',  
      styleUrls: ['./employee.component.css']  
    })  
    export class EmployeeComponent implements OnInit {  
      private emp: Observable<Employee[]>;  
      massage:String;  
      dataSaved=false;  
      constructor(private router: Router,private emprecordService:EmprecordService) { }  
       Loademployee()  
       {  
          debugger;  
          this.emp = this.emprecordService.GetEmployeeRecord();  
          console.log(this.emp);  

          debugger;  

       }  
       EmployeeEdit(id: string) {  
        debugger;  
       localStorage.removeItem("id");  
       localStorage.setItem("id",id.toString());  
        this.router.navigate(['/addemployee'], { queryParams: { Id: id } });  
        debugger;  
      }  
       Deleteemployee(id: string) {  
        if (confirm("Are You Sure To Delete this Informations")) {  

          this.emprecordService.DeleteEmployee(id).subscribe(  
            () => {  
              this.dataSaved = true;  
              this.massage = "Deleted Successfully";  
            }  
          );  
        }  
      }  
      ngOnInit() {  
        localStorage.clear();
        this.Loademployee();  

      }  

    }  

Step 12

Now, open app-routing.module.ts file and add the following lines to create routing.

	import { NgModule } from '@angular/core';  
    import { Routes, RouterModule } from '@angular/router';  
    import { EmployeeComponent } from "./employee/employee.component";  
    import { AddemployeeComponent } from "./employee/addemployee/addemployee.component";  

    const routes: Routes = [  
     {path:"employee",component:EmployeeComponent},  
     {path:"addemployee",component:AddemployeeComponent},  
    ];  

    @NgModule({  
      imports: [RouterModule.forRoot(routes)],  
      exports: [RouterModule]  
    })  
    export class AppRoutingModule { }  

Step 13

Now, open app.module.ts file and add the following lines.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { FormsModule } from '@angular/forms';  
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule,HttpClient} from '@angular/common/http';   
import { EmployeeComponent } from './employee/employee.component';  
import { ReactiveFormsModule } from "@angular/forms";  
import { EmprecordService } from "../app/emprecord.service";  
import { AddemployeeComponent } from './employee/addemployee/addemployee.component';   
import {NgxPaginationModule} from 'ngx-pagination';   
import { Ng2SearchPipeModule } from 'ng2-search-filter';  

@NgModule({  
  declarations: [  
    AppComponent,  
    EmployeeComponent,  
    AddemployeeComponent,  
  ],  
  imports: [  
    BrowserModule,FormsModule,  
    AppRoutingModule,HttpClientModule,ReactiveFormsModule,Ng2SearchPipeModule,NgxPaginationModule  
  ],  
  providers: [EmprecordService],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

Step 14

Now, let us run the project and redirect the URL to the Addemployee page.

Employee Information form

Step 15

Enter the details and click on the Add button.

Adding employees

Summary

In this article, we discussed how to perform CRUD operations using MongoDB, Angular 8, and Asp.net Web API.

#Angular #MongoDB #dotnet #webdev #api

Adaline  Kulas

Adaline Kulas

1594162500

Multi-cloud Spending: 8 Tips To Lower Cost

A multi-cloud approach is nothing but leveraging two or more cloud platforms for meeting the various business requirements of an enterprise. The multi-cloud IT environment incorporates different clouds from multiple vendors and negates the dependence on a single public cloud service provider. Thus enterprises can choose specific services from multiple public clouds and reap the benefits of each.

Given its affordability and agility, most enterprises opt for a multi-cloud approach in cloud computing now. A 2018 survey on the public cloud services market points out that 81% of the respondents use services from two or more providers. Subsequently, the cloud computing services market has reported incredible growth in recent times. The worldwide public cloud services market is all set to reach $500 billion in the next four years, according to IDC.

By choosing multi-cloud solutions strategically, enterprises can optimize the benefits of cloud computing and aim for some key competitive advantages. They can avoid the lengthy and cumbersome processes involved in buying, installing and testing high-priced systems. The IaaS and PaaS solutions have become a windfall for the enterprise’s budget as it does not incur huge up-front capital expenditure.

However, cost optimization is still a challenge while facilitating a multi-cloud environment and a large number of enterprises end up overpaying with or without realizing it. The below-mentioned tips would help you ensure the money is spent wisely on cloud computing services.

  • Deactivate underused or unattached resources

Most organizations tend to get wrong with simple things which turn out to be the root cause for needless spending and resource wastage. The first step to cost optimization in your cloud strategy is to identify underutilized resources that you have been paying for.

Enterprises often continue to pay for resources that have been purchased earlier but are no longer useful. Identifying such unused and unattached resources and deactivating it on a regular basis brings you one step closer to cost optimization. If needed, you can deploy automated cloud management tools that are largely helpful in providing the analytics needed to optimize the cloud spending and cut costs on an ongoing basis.

  • Figure out idle instances

Another key cost optimization strategy is to identify the idle computing instances and consolidate them into fewer instances. An idle computing instance may require a CPU utilization level of 1-5%, but you may be billed by the service provider for 100% for the same instance.

Every enterprise will have such non-production instances that constitute unnecessary storage space and lead to overpaying. Re-evaluating your resource allocations regularly and removing unnecessary storage may help you save money significantly. Resource allocation is not only a matter of CPU and memory but also it is linked to the storage, network, and various other factors.

  • Deploy monitoring mechanisms

The key to efficient cost reduction in cloud computing technology lies in proactive monitoring. A comprehensive view of the cloud usage helps enterprises to monitor and minimize unnecessary spending. You can make use of various mechanisms for monitoring computing demand.

For instance, you can use a heatmap to understand the highs and lows in computing visually. This heat map indicates the start and stop times which in turn lead to reduced costs. You can also deploy automated tools that help organizations to schedule instances to start and stop. By following a heatmap, you can understand whether it is safe to shut down servers on holidays or weekends.

#cloud computing services #all #hybrid cloud #cloud #multi-cloud strategy #cloud spend #multi-cloud spending #multi cloud adoption #why multi cloud #multi cloud trends #multi cloud companies #multi cloud research #multi cloud market

藤本  結衣

藤本 結衣

1633367280

単純な挿入MYSQLデータベースを使用したASP.NETでの更新と削除の選択

この記事では、ASP.NET WebアプリケーションからMySQLデータベースにデータの選択、更新、および削除を挿入する方法について説明します。

それでは、次の手順に進みましょう。

  • ASP.NETWebページ
  • グリッドビューデータコントロールとMySQLデータベース

次に、MySQLAdminページを開き、[Create A New Table]-> [View]-> [Table Structure for Table`student`]を選択します。

CREATE TABLE IF NOT EXISTS `student` (  
 `SID` int(100) NOT NULL AUTO_INCREMENT,  
 `Name` varchar(100) NOT NULL,  
 `Address` varchar(500) NOT NULL,  
 `Email` varchar(100) NOT NULL,  
 `Mobile` varchar(25) NOT NULL,  
 PRIMARY KEY (`SID`)  
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=31 ; 



Visual Studio 2012のインスタンスを開き、新しいASP.NETWebアプリケーションを作成します。次の図に示すように、プロジェクトに「MYSQLCRUDApplication」という名前を付け



ます。コードビハインドファイル(Student.aspx.cs)に、次のようにコードを記述します

Student.aspx 

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"  
CodeBehind="Student.aspx.cs" Inherits="MYSQLCRUDApplication.Student" %>  
  
<asp:Content ID="Content1" ContentPlaceHolderID="titleContent" runat="server">  
    Simple Insert Select Update and Delete in ASP.NET using MySQL Database   
</asp:Content>  
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">  
</asp:Content>  
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">  
    <table>  
        <tr>  
            <td class="td">Name:</td>  
            <td>  
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>  
            <td>  
                <asp:Label ID="lblSID" runat="server" Visible="false"></asp:Label> </td>  
        </tr>  
        <tr>  
            <td class="td">Address:</td>  
            <td>  
                <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>  
            <td> </td>  
        </tr>  
        <tr>  
            <td class="td">Mobile:</td>  
            <td>  
                <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>  
            <td> </td>  
        </tr>  
        <tr>  
            <td class="td">Email ID:</td>  
            <td>  
                <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>  
            <td> </td>  
        </tr>  
        <tr>  
            <td></td>  
            <td>  
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
                <asp:Button ID="btnUpdate" runat="server" Text="Update" Visible="false"  
OnClick="btnUpdate_Click" />  
                <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></td>  
            <td></td>  
        </tr>  
    </table>  
  
    <div style="padding: 10px; margin: 0px; width: 100%;">  
        <p>  
            Total Student:<asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>  
        </p>  
        <asp:GridView ID="GridViewStudent" runat="server" DataKeyNames="SID"   
            OnSelectedIndexChanged="GridViewStudent_SelectedIndexChanged"  
OnRowDeleting="GridViewStudent_RowDeleting">  
            <Columns>  
                <asp:CommandField HeaderText="Update" ShowSelectButton="True" />  
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />  
            </Columns>  
        </asp:GridView>  
    </div>  
</asp:Content>  

Web.configファイルで、次のように接続文字列を作成します。

Web.config 

<connectionStrings>  
    <add name="ConnectionString"  
connectionString="Server=localhost;userid=root;password=;Database=Testdb"  
providerName="MySql.Data.MySqlClient"/>  
 </connectionStrings>  

ここで、コードビハインドファイル「Student.aspx.cs」で次のコードを使用します。

Student.aspx.cs 

using System;  
using System.Collections.Generic;  
using System.Configuration;  
using System.Data;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using MySql.Data.MySqlClient;  
  
  
namespace MYSQLCRUDApplication  
{  
    public partial class Student : System.Web.UI.Page  
    {  
        #region MySqlConnection Connection and Page Lode  
        MySqlConnection conn = new  
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);          
        protected void Page_Load(object sender, EventArgs e)  
        {  
            Try  
            {  
                if (!Page.IsPostBack)  
                {  
                    BindGridView();  
                      
                }  
            }  
            catch (Exception ex)  
            {  
                ShowMessage(ex.Message);  
            }  
        }  
        #endregion  
        #region show message  
        /// <summary>  
        /// This function is used for show message.  
        /// </summary>  
        /// <param name="msg"></param>  
        void ShowMessage(string msg)  
        {  
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script  
language='javascript'>alert('" + msg + "');</script>");  
        }  
        /// <summary>  
        /// This Function is used TextBox Empty.  
        /// </summary>  
        void clear()  
        {  
            txtName.Text = string.Empty; txtAddress.Text = string.Empty; txtMobile.Text = string.Empty;  
txtEmail.Text = string.Empty;  
            txtName.Focus();  
        }  
        #endregion  
        #region bind data to GridViewStudent  
        private void BindGridView()  
        {   
            Try  
            {  
                if (conn.State == ConnectionState.Closed)  
                {  
                    conn.Open();  
                }  
                MySqlCommand cmd = new MySqlCommand("Select * from Student ORDER BY SID DESC;",  
conn);  
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);  
                DataSet ds = new DataSet();  
                adp.Fill(ds);  
                GridViewStudent.DataSource = ds;  
                GridViewStudent.DataBind();  
                lbltotalcount.Text = GridViewStudent.Rows.Count.ToString();  
            }  
            catch (MySqlException ex)  
            {  
                ShowMessage(ex.Message);  
            }  
            Finally  
            {  
                if (conn.State == ConnectionState.Open)  
                {  
                   conn.Close();  
                }  
            }  
        }  
        #endregion  
        #region Insert Data  
        /// <summary>  
        /// this code used to Student Data insert in MYSQL Database  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        protected void btnSubmit_Click(object sender, EventArgs e)  
        {  
            Try  
            {  
                conn.Open();  
                MySqlCommand cmd = new MySqlCommand("Insert into student (Name,Address,Mobile,Email )  
values (@Name,@Address,@Mobile,@Email)", conn);  
                cmd.Parameters.AddWithValue("@Name",txtName.Text);  
                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);  
                cmd.Parameters.AddWithValue("@Mobile",txtMobile.Text);  
                cmd.Parameters.AddWithValue("@Email",txtEmail.Text);  
                cmd.ExecuteNonQuery();                 
                cmd.Dispose();   
                ShowMessage("Registered successfully......!");               
                clear();  
                BindGridView();  
            }  
            catch (MySqlException ex)  
            {  
                ShowMessage(ex.Message);  
            }  
            Finally  
            {  
                conn.Close();  
            }  
        }  
          
        #endregion   
        #region SelectedIndexChanged  
        /// <summary>  
        /// this code used to GridViewRow SelectedIndexChanged value show textbox  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        protected void GridViewStudent_SelectedIndexChanged(object sender, EventArgs e)  
        {  
            GridViewRow row = GridViewStudent.SelectedRow;  
            lblSID.Text = row.Cells[2].Text;  
            txtName.Text = row.Cells[3].Text;  
            txtAddress.Text = row.Cells[4].Text;  
            txtEmail.Text = row.Cells[5].Text;  
            txtMobile.Text = row.Cells[6].Text;  
            btnSubmit.Visible = false;  
            btnUpdate.Visible = true;  
        }  
        #endregion  
        #region Delete Student Data  
        /// <summary>  
        /// This code used to GridViewStudent_RowDeleting Student Data Delete  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        protected void GridViewStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)  
        {  
            Try  
            {  
                conn.Open();  
                int SID = Convert.ToInt32(GridViewStudent.DataKeys[e.RowIndex].Value);  
                MySqlCommand cmd = new MySqlCommand("Delete From student where SID='" + SID + "'",  
conn);  
                cmd.ExecuteNonQuery();  
                cmd.Dispose();  
                ShowMessage("Student Data Delete Successfully......!");  
                GridViewStudent.EditIndex = -1;  
                BindGridView();  
            }  
            catch (MySqlException ex)  
            {  
                ShowMessage(ex.Message);  
            }  
            Finally  
            {  
                conn.Close();  
            }  
        }  
        #endregion  
        #region student data update  
        /// <summary>  
        /// This code used to student data update  
        /// </summary>  
        /// <param name="sender"></param>  
       /// <param name="e"></param>  
        protected void btnUpdate_Click(object sender, EventArgs e)  
        {  
            Try  
            {  
                conn.Open();  
                string SID = lblSID.Text;                
                MySqlCommand cmd = new MySqlCommand("update student Set  
Name=@Name,Address=@Address,Mobile=@Mobile,Email=@Email where SID=@SID", conn);  
                cmd.Parameters.AddWithValue("@Name", txtName.Text);  
                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);  
                cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text);  
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text);  
                cmd.Parameters.AddWithValue("SID",SID);  
                cmd.ExecuteNonQuery();  
                cmd.Dispose();  
                ShowMessage("Student Data update Successfully......!");  
                GridViewStudent.EditIndex = -1;  
                BindGridView(); btnUpdate.Visible = false;  
            }  
            catch (MySqlException ex)  
            {  
                ShowMessage(ex.Message);  
            }  
            Finally  
            {  
                conn.Close();  
            }  
        }  
        #endregion  
        #region textbox clear  
        protected void btnCancel_Click(object sender, EventArgs e)  
        {  
            clear();  
        }  
        #endregion  
    }  
}   

ページを実行すると、次のようになります。



次に、学生データの挿入とグリッドビューのデータの表示を入力します。メッセージボックス「正常に登録されました」。



次に、Studentを選択し、データTextBoxを表示して、メッセージボックス「StudentDataupdatesuccessfully」に表示されているデータを更新します。



ここで、メッセージボックス「StudentDataDeleteSuccessfully」に表示されているStudentデータを削除します。



この記事がお役に立てば幸いです。他にご不明な点がございましたら、以下にコメントをお寄せください。

リンク: https://www.c-sharpcorner.com/

#aspdotnet #sql 

Rusty  Shanahan

Rusty Shanahan

1597833840

Overview of Google Cloud Essentials Quest

If you looking to learn about Google Cloud in depth or in general with or without any prior knowledge in cloud computing, then you should definitely check this quest out, Link.

Google Could Essentials is an introductory level Quest which is useful to learn about the basic fundamentals of Google Cloud. From writing Cloud Shell commands and deploying my first virtual machine, to running applications on Kubernetes Engine or with load balancing, Google Cloud Essentials is a prime introduction to the platform’s basic features.

Let’s see what was the Quest Outline:

  1. A Tour of Qwiklabs and Google Cloud
  2. Creating a Virtual Machine
  3. Getting Started with Cloud Shell & gcloud
  4. Kubernetes Engine: Qwik Start
  5. Set Up Network and HTTP Load Balancers

A Tour of Qwiklabs and Google Cloud was the first hands-on lab which basically gives an overview about Google Cloud. There were few questions to answers that will check your understanding about the topic and the rest was about accessing Google cloud console, projects in cloud console, roles and permissions, Cloud Shell and so on.

**Creating a Virtual Machine **was the second lab to create virtual machine and also connect NGINX web server to it. Compute Engine lets one create virtual machine whose resources live in certain regions or zones. NGINX web server is used as load balancer. The job of a load balancer is to distribute workloads across multiple computing resources. Creating these two along with a question would mark the end of the second lab.

#google-cloud-essentials #google #google-cloud #google-cloud-platform #cloud-computing #cloud

Google Cloud: Caching Cloud Storage content with Cloud CDN

In this Lab, we will configure Cloud Content Delivery Network (Cloud CDN) for a Cloud Storage bucket and verify caching of an image. Cloud CDN uses Google’s globally distributed edge points of presence to cache HTTP(S) load-balanced content close to our users. Caching content at the edges of Google’s network provides faster delivery of content to our users while reducing serving costs.

For an up-to-date list of Google’s Cloud CDN cache sites, see https://cloud.google.com/cdn/docs/locations.

Task 1. Create and populate a Cloud Storage bucket

Cloud CDN content can originate from different types of backends:

  • Compute Engine virtual machine (VM) instance groups
  • Zonal network endpoint groups (NEGs)
  • Internet network endpoint groups (NEGs), for endpoints that are outside of Google Cloud (also known as custom origins)
  • Google Cloud Storage buckets

In this lab, we will configure a Cloud Storage bucket as the backend.

#google-cloud #google-cloud-platform #cloud #cloud storage #cloud cdn