Franz  Becker

Franz Becker

1624560540

New Azure region coming to China in 2022

In order to meet the China market’s growing needs for global public cloud services, Microsoft is planning to bring a new Azure Region to North China in 2022 through its local operating partner, 21Vianet. This expansion is expected to effectively double the capacity of Microsoft’s intelligent cloud portfolio in China in the coming years, which includes Azure, Microsoft Office 365, Dynamics 365, and Power Platform operated by 21Vianet, to power innovation and digital transformation for developers, partners, and customers in China and around the world.

According to the white paper China Cloud Industry Development1, the cloud market in China is expected to reach 300 Billion RMB (est. $46 Billion) in 2023. In response to the pandemic, 63 percent of organizations in China are leveraging cloud-related innovations to accelerate digitization in their products, payments, e-commerce, automation, and more.

“This unveils a big opportunity. Microsoft Cloud operated by 21Vianet was the first international public cloud compliantly launched in China through a local operating partner. Our intelligent, trustworthy, and neutral cloud platform has been empowering hundreds of thousands of developers, partners, and customers from both China and the world to achieve more with technical innovation and business transformation. The upcoming region will reinforce the capabilities to help further nurture local talents, stimulate local innovation, grow local technology ecosystems, and empower businesses in a wide range of industries to achieve more." —Alain Crozier, Chairman and Chief Executive Officer of Microsoft Greater China Region (GCR)

The Microsoft Cloud platform delivers intelligent, scalable, secure, compliant, and trustworthy cloud services, which includes Microsoft Azure, an ever-expanding set of cloud services that offers computing, networking, databases, analytics, AI, and IoT services; Microsoft Office 365, the world’s productivity cloud that delivers best-of-breed productivity apps integrated through cloud services, delivered as part of an open platform for business processes; Dynamics 365 and Power Platform, the next generation of intelligent business applications that enable organizations to grow, evolve, and transform to meet the needs of customers.

In China, Microsoft has been collaborating with 21Vianet to run all these essential cloud services since 2014. Announced in 2012, and officially launched in March 2014 with two initial regions, Microsoft Azure operated by 21Vianet was the first international public cloud service to become generally available in the China market. Following Azure, Microsoft Office 365, Dynamics 365, and Power Platform operated by 21Vianet successively launched in China in 2014, 2019, and 2020.

#announcements #new azure #azure #2022

What is GEEK

Buddha Community

New Azure region coming to China in 2022
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

藤本  結衣

藤本 結衣

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 

Franz  Becker

Franz Becker

1624560540

New Azure region coming to China in 2022

In order to meet the China market’s growing needs for global public cloud services, Microsoft is planning to bring a new Azure Region to North China in 2022 through its local operating partner, 21Vianet. This expansion is expected to effectively double the capacity of Microsoft’s intelligent cloud portfolio in China in the coming years, which includes Azure, Microsoft Office 365, Dynamics 365, and Power Platform operated by 21Vianet, to power innovation and digital transformation for developers, partners, and customers in China and around the world.

According to the white paper China Cloud Industry Development1, the cloud market in China is expected to reach 300 Billion RMB (est. $46 Billion) in 2023. In response to the pandemic, 63 percent of organizations in China are leveraging cloud-related innovations to accelerate digitization in their products, payments, e-commerce, automation, and more.

“This unveils a big opportunity. Microsoft Cloud operated by 21Vianet was the first international public cloud compliantly launched in China through a local operating partner. Our intelligent, trustworthy, and neutral cloud platform has been empowering hundreds of thousands of developers, partners, and customers from both China and the world to achieve more with technical innovation and business transformation. The upcoming region will reinforce the capabilities to help further nurture local talents, stimulate local innovation, grow local technology ecosystems, and empower businesses in a wide range of industries to achieve more." —Alain Crozier, Chairman and Chief Executive Officer of Microsoft Greater China Region (GCR)

The Microsoft Cloud platform delivers intelligent, scalable, secure, compliant, and trustworthy cloud services, which includes Microsoft Azure, an ever-expanding set of cloud services that offers computing, networking, databases, analytics, AI, and IoT services; Microsoft Office 365, the world’s productivity cloud that delivers best-of-breed productivity apps integrated through cloud services, delivered as part of an open platform for business processes; Dynamics 365 and Power Platform, the next generation of intelligent business applications that enable organizations to grow, evolve, and transform to meet the needs of customers.

In China, Microsoft has been collaborating with 21Vianet to run all these essential cloud services since 2014. Announced in 2012, and officially launched in March 2014 with two initial regions, Microsoft Azure operated by 21Vianet was the first international public cloud service to become generally available in the China market. Following Azure, Microsoft Office 365, Dynamics 365, and Power Platform operated by 21Vianet successively launched in China in 2014, 2019, and 2020.

#announcements #new azure #azure #2022

藤本  結衣

藤本 結衣

1633175520

C#のTreeViewコントロール

TreeViewの紹介

これは、TreeViewコントロールの操作の基本のいくつかを取り上げた短い記事です。この記事では、TreeNodeをTreeViewコントロールに動的に追加し、ノードを検索して、TreeNodeのタグ、テキスト、または名前のプロパティに対して検索語に一致する単一のノードまたはノードのコレクションを見つけて強調表示し、手動またはプログラムでノードを選択する方法について説明します。

Image1.jpg

図1:TextプロパティによるTreeViewコントロールの検索。

Image2.jpg

図2:NameプロパティによるTreeViewコントロールの検索。

Image3.jpg

図3:NameプロパティによるTreeViewコントロールの検索。

Image4.jpg

図4:特定のプロパティを持つノードの作成。

TreeViewアプリケーション

アプリケーションソリューションには、単一のWindowsアプリケーションプロジェクトが含まれています。このプロジェクトをサポートするために提供されるすべてのコードは、2つのフォームクラスに含まれています。1つは、TreeViewと、ノード情報を表示し(図1、2、および3)、ユーザー指定の検索用語に基づいて特定のノードまたはノードのグループの検索を実行するために使用されるいくつかのコントロールを含むメインフォームです。もう1つのフォームクラス(図4)は、新しいノードを作成するために使用されます。アプリケーション内では、TreeViewからノードを選択し、コンテキストメニューから[ノードの追加]オプションを選択すると、このフォームが表示されます。

このアプリケーションのTreeView関連コンポーネントのいずれかで行われるカスタムまたは派手なことは何もありません。これは、Windowsフォームアプリケーションのコンテキスト内でTreeViewを操作する方法のデモンストレーションにすぎません。

コード:フォーム1-メインフォーム

メインフォームクラスは、いくつかのコントロールが追加された標準のウィンドウフォームです。フォームには分割コンテナコントロールが含まれています。コントロールの左側にはTreeViewコントロールがあり、スプリッターの右側には4つのグループボックスがあります。最初のグループボックスには、選択したノードに関する情報を表示するために使用されるラベルとテキストボックスのセットが含まれ、残りのグループボックスには、ノードのテキスト、名前に基づいてTreeViewのノードコレクションのさまざまな検索を実行するために使用されるラベル、テキストボックス、およびボタンが含まれます。 、またはタグ値。

クラスに含まれる機能は、いくつかの領域に分割されています。クラスは、デフォルトのインポート、名前空間宣言、およびクラス宣言で始まります。

 システムを使用する;  
 System.Collections.Genericを使用する;  
 System.ComponentModelを使用します。  
 System.Dataを使用します。  
 System.Drawingを使用する;  
 System.Textを使用します。  
 System.Windows.Formsを使用する;  
名前空間 EasyTreeView {  
    パブリック 部分 クラス Form1:フォーム{  
        public  Form1(){  
            InitializeComponent();  
            //ベースツリービューノードを追加することから始めます  
            TreeNode mainNode =  new  TreeNode();  
            mainNode.Name =  "mainNode" ;  
            mainNode.Text =  "Main" ;  
            this .treeView1.Nodes.Add(mainNode);  
        }  
    }  
}   

フォームクラスコンストラクターは、TreeViewコントロールにメインノードを作成します。実行時に、ユーザーはこのノード(またはこのノードから発生する任意の子ノード)を選択して、TreeViewにノードを追加できます。フォームクラスにはコンテキストメニューも含まれています。このコンテキストメニューには2つのオプションがあります。1つは新しいノードを追加するためのもので、もう1つは既存のノードを削除するためのものです。新しいノードが要求されると、アプリケーションは[新しいノード]ダイアログのインスタンスを開きます。このダイアログでは、ユーザーに新しいノードの名前、テキスト、およびタグの値を設定するように強制します。タグ値は任意のオブジェクトにすることができますが、この例では、タグは追加の文字列値を保持するように制限されています。ダイアログから値が収集されると、新しいノードに情報が入力され、TreeViewの選択されたノードに追加されます。

ノードが削除されると、選択されたノードとそのすべての子がTreeViewから削除されます。ここで注意すべきことの1つは、タグを介してオブジェクトをノードに関連付ける場合です。選択したノードを削除する前に、そのオブジェクトを破棄するハンドラーを作成する必要があります。

#regionノードの追加と削除  
/// <概要>  
    ///ダイアログボックスを使用してTreeviewノードを追加します  
    ///ユーザーに名前とテキストのプロパティを設定するように強制する  
    ///ノードの  
    /// </ summary>  
///  
<param name = "送信者" >  
</ param>  
///  
<param name = "e" >  
</ param>  
private void  cmnuAddNode_Click(object  sender、EventArgs e)   
{{  
    NewNode n =  new  NewNode();  
    n.ShowDialog();  
    TreeNode nod =  new  TreeNode();  
    nod.Name = n.NewNodeName.ToString();  
    nod.Text = n.NewNodeText.ToString();  
    nod.Tag = n.NewNodeTag.ToString();  
    n.Close();  
    treeView1.SelectedNode.Nodes.Add(nod);  
    treeView1.SelectedNode.ExpandAll();  
}  
/// <概要>  
    ///選択したノードとその子を削除します  
    /// </ summary>  
///  
<param name = "送信者" >  
</ param>  
///  
<param name = "e" >  
</ param>  
private void  cmnuRemoveNode_Click(object  sender、EventArgs e)   
{{  
    treeView1.SelectedNode.Remove();  
}  
#endregion  

コードの次の領域は、TreeViewイベントを処理するために使用されます。このセクションで処理されるイベントは2つだけです。TreeViewのAfterSelectイベントとTreeViewのclickイベント。After Selectイベントハンドラーは、選択したノードからの情報(名前、テキスト、タグ、および親テキストのプロパティ)を表示するために使用されるテキストボックスにデータを入力するために使用されます。後で説明する検索機能は、一致する各ノードの背景色を黄色に設定することにより、検索に応答して見つかったすべてのノードを強調表示します。TreeViewのクリックイベントハンドラーは、そのような強調表示をすべて削除するために使用されます。

#regionTreeviewイベントハンドラー  
/// <概要>  
///選択したノードに関する情報を表示します  
/// </ summary>  
/// <param name = "sender"> </ param>  
/// <param name = "e"> </ param>  
private void  treeView1_AfterSelect(object  sender、TreeViewEventArgs e)   
{{  
    試す  
    {{  
        txtName.Text =  "" ;  
        txtParentName.Text =  "" ;  
        txtText.Text =  "" ;  
        txtTag.Text =  "" ;  
        txtName.Text = treeView1.SelectedNode.Name.ToString();  
        txtText.Text = treeView1.SelectedNode.Text.ToString();  
        txtTag.Text = treeView1.SelectedNode.Tag.ToString();  
        txtParentName.Text = treeView1.SelectedNode.Parent.Text.ToString();  
    }  
    キャッチ {}  
}  
/// <概要>  
///検索関数でマークされたノードをクリアします  
/// </ summary>  
/// <param name = "sender"> </ param>  
/// <param name = "e"> </ param>  
private void  treeView1_Click(object  sender、EventArgs e)   
{{  
    ClearBackColor();  
}  
#endregion   

クラス内の次の領域は、nameプロパティでノードを検索するために使用されます。名前でノードを検索する方法は、TreeViewで直接サポートされている唯一の検索機能です。名前以外の名前でノードを検索する場合は、独自のメソッドを作成する必要があります。このクリックイベントハンドラーは、一致する名前でノードの配列にデータを入力します。findメソッドは2つの引数を受け入れます。最初の引数は検索語で、2番目の引数は子ノードも検索に含めるかどうかを決定するために使用されるブール値です。この場合、検索語はフォームのテキストボックスから収集され、子ノードを検索するオプションは、2番目の引数をtrueに設定することで有効になります。

ノードのコレクションが作成されると、一致する各ノードの背景色が黄色に設定され、TreeViewでノードが強調表示されます。一致するノードの背景色を設定する前に、Clear Back Colorメソッドを呼び出すことにより、TreeView内の他のすべてのノードが白い背景に戻されます。

#region名前で検索  
/// <概要>  
///ツリービューの組み込みの検索関数を使用します  
///ノードを検索する  
/// </ summary>  
/// <param name = "sender"> </ param>  
/// <param name = "e"> </ param>  
private void  btnFindNode_Click(object  sender、EventArgs e)   
{{  
    ClearBackColor();  
    試す  
    {{  
        TreeNode [] tn = treeView1.Nodes [0] .Nodes.Find(txtNodeSearch.Text、  true );  
        for  (int  i = 0; i <tn.Length; i ++)  
        {{  
            treeView1.SelectedNode = tn [i];  
            treeView1.SelectedNode.BackColor = Color.Yellow;  
        }  
    }  
    キャッチ {}  
}  
#endregion  

コードの次の領域は、以前の検索で強調表示されたノードから背景色を削除するために使用されます。このプロセスは、2つの別々の方法に依存しています。最初のメソッドは、フォームのTreeViewコントロール内のすべてのノードを含むツリーノードコレクションのインスタンスを作成します。コレクション内の各ノードは、2番目のメソッド(Clear Recursive)に渡されます。この2番目のメソッドには、現在のノードが渡されます。Clear Recursiveメソッドは、渡されたノードノードコレクション内に含まれるすべてのノードをループし、それらの各ノードの背景色を白に設定します。次に、各ノードは同じClear Recursiveメソッドに再帰的に戻され、処理するノードがなくなるまで、各ノードのノードコレクションが処理されます。このようにして、ツリー全体の各ノードと子ノードが処理されます。

このプロセスは、各ノードの背景色を白に設定するためだけに使用されますが、ツリー全体を処理する必要がある場合は常に同じアプローチを使用できます。実際、残りの検索方法はまさにそれを行います。

#regionBackColorを削除します  
//ツリービューノードを再帰的に移動します  
//そして背景色を白にリセットします  
private void  ClearBackColor()   
{{  
    TreeNodeCollectionノード= treeView1.Nodes;  
    foreachの (ツリーノードN における ノード)  
    {{  
        ClearRecursive(n);  
    }  
}  
// ClearBackColor関数によって呼び出されます  
private void  ClearRecursive(TreeNode treeNode)   
{{  
    foreachの (ツリーノードTN で treeNode.Nodes)  
    {{  
        tn.BackColor = Color.White;  
        ClearRecursive(tn);  
    }  
}  
#endregion   

コードの次の領域は、検索式に一致するテキストプロパティを持つ1つまたは複数のノードを見つけるために使用されます。フォームには、テキスト検索用語を設定し、ボタンクリックイベントハンドラーからメソッドを呼び出すために使用されるグループボックスが含まれています。ボタンをクリックすると、最初にClear Back Colorメソッドを呼び出して、強調表示されているすべてのノードがクリアされます。ノードがすべて白い背景に復元された後、ハンドラーはFind ByTextメソッドを呼び出します。この方法は、背景色をクリアするために説明した方法とほとんど同じように機能します。このメソッドは、ツリービューノードのコレクションをアセンブルしてから、各ノードを再帰メソッドに渡します。find recursiveメソッドは、検索式に一致するテキストプロパティを持つノードを検索し、一致するものが見つかると、背景色を黄色に設定します。

#regionテキストで検索  
/// <概要>  
///テキストによるノードの検索には特別な機能が必要です  
///この関数はツリービューを再帰的にスキャンし、  
///一致するアイテムをマークします。  
/// </ summary>  
/// <param name = "sender"> </ param>  
/// <param name = "e"> </ param>  
private void  btnNodeTextSearch_Click(object  sender、EventArgs e)   
{{  
    ClearBackColor();  
    FindByText();  
}  
private void  FindByText()   
{{  
    TreeNodeCollectionノード= treeView1.Nodes;  
    foreachの (ツリーノードN における ノード)  
    {{  
        FindRecursive(n);  
    }  
}  
private void  FindRecursive(TreeNode treeNode)   
{{  
    foreachの (ツリーノードTN で treeNode.Nodes)  
    {{  
        //テキストのプロパティが一致する場合は、アイテムに色を付けます  
        if  (tn.Text ==  this .txtNodeTextSearch.Text)  
            tn.BackColor = Color.Yellow;  
        FindRecursive(tn);  
    }  
}  
#endregion  

次の領域は、タグ値(この場合は文字列)によってノードを検索するために使用されるメソッドを含むために使用されます。一致するノードを黄色で強調表示します。これらのメソッドは、一致がテキスト値ではなくタグ値によって決定されることを除いて、最後のメソッドとほとんど同じように機能します。

#regionタグで検索  
/// <概要>  
///タグでノードを検索するには特別な機能が必要です  
///この関数はツリービューを再帰的にスキャンし、  
///一致するアイテムをマークします。タグはオブジェクトにすることができます。これで  
///文字列を含めるためだけに使用される場合  
/// </ summary>  
/// <param name = "sender"> </ param>  
/// <param name = "e"> </ param>  
private void  btnNodeTagSearch_Click(object  sender、EventArgs e)   
{{  
    ClearBackColor();  
    FindByTag();  
}  
private void  FindByTag()   
{{  
    TreeNodeCollectionノード= treeView1.Nodes;  
    foreachの (ツリーノードN における ノード)  
    {{  
        FindRecursiveTag(n);  
    }  
}  
private void  FindRecursiveTag(TreeNode treeNode)   
{{  
    foreachの (ツリーノードTN で treeNode.Nodes)  
    {{  
    //テキストのプロパティが一致する場合は、アイテムに色を付けます  
        if  (tn.Tag.ToString()==  this .txtTagSearch.Text)  
            tn.BackColor = Color.Yellow;  
        FindRecursiveTag(tn);  
    }  
}  
#endregion  

これで、ノードを追加および削除したり、名前、テキスト、またはタグの値に基づいて特定のノードを検索したりするために必要なすべてのコードがまとめられます。

コード:フォーム2-新しいノードフォーム

New Nodeフォームで提供されるコードは、新しく作成されたノードの名前、テキスト、およびタグのプロパティを設定するために使用されるユーザー指定の値をキャプチャするためにのみ使用されます。フォームはダイアログとして表示され、ユーザーがアプリケーションのメインフォームから新しいノードの追加を要求したことに応答して表示されます。インポート、名前空間宣言、およびクラス宣言はすべて、フォームクラスのデフォルト構成にあります。

 システムを使用する;  
 System.Collections.Genericを使用する;  
 System.ComponentModelを使用します。  
 System.Dataを使用します。  
 System.Drawingを使用する;  
 System.Textを使用します。  
 System.Windows.Formsを使用する;  
名前空間 EasyTreeView  
{{  
    パブリック 部分 クラス NewNode:フォーム  
    {{  

クラス宣言に続いて、3つのローカルメンバー変数が定義されます。それぞれが、ユーザー指定の名前、テキスト、およびタグのプロパティを格納するために使用されます。

#regionローカル変数  
プライベート文字列 mNewNodeName;   
プライベート文字列 mNewNodeText;   
プライベート文字列 mNewNodeTag;   
#endregion  

フォームコンストラクターはデフォルト構成です。

/// <概要>  
///デフォルトのコンストラクタ  
/// </ summary>  
public  NewNode()  
{{  
     InitializeComponent();  
}  

コードの次の領域は、新しいノード名、テキスト、およびタグ値を保持するために使用される3つのパブリックプロパティを定義するために使用されます。ユーザーがこのフォームにこれらの値を設定すると、メインフォームはこれらのプロパティを収集し、新しいノードの名前、テキスト、およびタグのプロパティに割り当てます。

#regionクラスのプロパティ  
パブリック文字列 NewNodeName {   
    取得 {  
         mNewNodeNameを返します。  
    }  
    セット {  
        mNewNodeName =値;  
    }  
}  
パブリック文字列 NewNodeText {   
    取得 {  
         mNewNodeTextを返します。  
    }  
    セット {  
        mNewNodeText =値;  
    }  
}  
パブリック文字列 NewNodeTag {   
    取得 {  
         mNewNodeTagを返します。  
    }  
    セット {  
        mNewNodeTag =値;  
    }  
}  
#endregion  

このボタンクリックイベントハンドラーは、ユーザーに3つの値すべてを設定するように強制することを目的としています。それぞれが設定されると、関連するプロパティに正しい値が渡され、フォームが閉じられます。

private void  btnSubmit_Click(object  sender、EventArgs e){   
    if  (txtNewNodeName.Text!=  string .Empty){  
        NewNodeName = txtNewNodeName.Text;  
    }   
    else  {  
        MessageBox.Show("ノードに名前を付けます。" );  
        戻る;  
    }  
    if  (txtNewNodeText.Text!=  string .Empty){  
        NewNodeText = txtNewNodeText.Text;  
    }   
    else  {  
        MessageBox.Show("新しいノードのテキストを提供する" );  
        戻る;  
    }  
    if  (txtTag.Text!=  string .Empty){  
        NewNodeTag = txtTag.Text;  
    }   
    else  {  
        MessageBox.Show("新しいノードのテキストを提供する" );  
        戻る;  
    }  
    this .Close();  
}  

これですべてです。このコードが実行されると、ユーザーはメインノードを右クリックして、適切と思われる数のノードと子ノードを追加できます。ユーザーは、有効な検索式を任意の検索オプションに入力して、一致するノードを強調表示するか、ツリーからノードを選択して、選択したノードから関連する名前、テキスト、タグ、および親の値を読み取ることができます。

  

概要

当然、TreeViewコントロールを使用する方法は無数にあり、この簡単なデモンストレーションでは、利用可能なさまざまなオプションの調査を開始していません。デモンストレーションの唯一の目的は、ノードを追加および削除する方法、選択したノードから情報を取得する方法、およびノー​​ドの名前、テキスト、およびタグ値に基づいて特定のノードを検索する方法の説明を提供することでした。

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

#csharp 

Eric  Bukenya

Eric Bukenya

1624713540

Learn NoSQL in Azure: Diving Deeper into Azure Cosmos DB

This article is a part of the series – Learn NoSQL in Azure where we explore Azure Cosmos DB as a part of the non-relational database system used widely for a variety of applications. Azure Cosmos DB is a part of Microsoft’s serverless databases on Azure which is highly scalable and distributed across all locations that run on Azure. It is offered as a platform as a service (PAAS) from Azure and you can develop databases that have a very high throughput and very low latency. Using Azure Cosmos DB, customers can replicate their data across multiple locations across the globe and also across multiple locations within the same region. This makes Cosmos DB a highly available database service with almost 99.999% availability for reads and writes for multi-region modes and almost 99.99% availability for single-region modes.

In this article, we will focus more on how Azure Cosmos DB works behind the scenes and how can you get started with it using the Azure Portal. We will also explore how Cosmos DB is priced and understand the pricing model in detail.

How Azure Cosmos DB works

As already mentioned, Azure Cosmos DB is a multi-modal NoSQL database service that is geographically distributed across multiple Azure locations. This helps customers to deploy the databases across multiple locations around the globe. This is beneficial as it helps to reduce the read latency when the users use the application.

As you can see in the figure above, Azure Cosmos DB is distributed across the globe. Let’s suppose you have a web application that is hosted in India. In that case, the NoSQL database in India will be considered as the master database for writes and all the other databases can be considered as a read replicas. Whenever new data is generated, it is written to the database in India first and then it is synchronized with the other databases.

Consistency Levels

While maintaining data over multiple regions, the most common challenge is the latency as when the data is made available to the other databases. For example, when data is written to the database in India, users from India will be able to see that data sooner than users from the US. This is due to the latency in synchronization between the two regions. In order to overcome this, there are a few modes that customers can choose from and define how often or how soon they want their data to be made available in the other regions. Azure Cosmos DB offers five levels of consistency which are as follows:

  • Strong
  • Bounded staleness
  • Session
  • Consistent prefix
  • Eventual

In most common NoSQL databases, there are only two levels – Strong and EventualStrong being the most consistent level while Eventual is the least. However, as we move from Strong to Eventual, consistency decreases but availability and throughput increase. This is a trade-off that customers need to decide based on the criticality of their applications. If you want to read in more detail about the consistency levels, the official guide from Microsoft is the easiest to understand. You can refer to it here.

Azure Cosmos DB Pricing Model

Now that we have some idea about working with the NoSQL database – Azure Cosmos DB on Azure, let us try to understand how the database is priced. In order to work with any cloud-based services, it is essential that you have a sound knowledge of how the services are charged, otherwise, you might end up paying something much higher than your expectations.

If you browse to the pricing page of Azure Cosmos DB, you can see that there are two modes in which the database services are billed.

  • Database Operations – Whenever you execute or run queries against your NoSQL database, there are some resources being used. Azure terms these usages in terms of Request Units or RU. The amount of RU consumed per second is aggregated and billed
  • Consumed Storage – As you start storing data in your database, it will take up some space in order to store that data. This storage is billed per the standard SSD-based storage across any Azure locations globally

Let’s learn about this in more detail.

#azure #azure cosmos db #nosql #azure #nosql in azure #azure cosmos db