step by step process fro Crud application on .net

Viewed 24

Crud application from scratch UI. API, DB, DOA layer , is there any way we can do it better ? this is WEB API Controller:

    [HttpPost]
        [UsedImplicitly]
        [Route("Employee/PostData")]
        public HttpResponseMessage InsertUpdateEmployee()
        {
            HttpResponseMessage response;

            string message = this._iEmployee.InsertUpdateEmployee(HttpContext.Current);
            if (message == "")
            {
                response = Request.CreateResponse(HttpStatusCode.OK, "SUCCESS");
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.OK, message);
            }
            return response;
        }

**DAO PAGE

:** public DataTable GetEmployee(int "EmployeeID", { DbCommand command = Database.GetStoredProcCommand(StoredProcedureName.Get_Employee_Data); Database.AddInParameter(command, "EmployeeID", DbType.Int32, "EmployeeID", return Database.ExecuteDataSet(command).Tables[0];

        }

--
  public void DeleteEmployee(int "EmployeeID", 
        {
            DbCommand command = Database.GetStoredProcCommand(StoredProcedureName.Get_Employee_Data);
            Database.AddInParameter(command, "EmployeeID", DbType.Int32, "EmployeeID", 
            Database.AddInParameter(command, "ErrorMessage", DbType.String, employee.ErrorMessage);
            Database.ExecuteNonQuery(command);

        }
--

        public void InsertUpdateEmployee(EmployeeEntity employee)
        {
            DbCommand command = Database.GetStoredProcCommand(StoredProcedureName.INSERT_UPDATE_EMPLOYEE);
            Database.AddInParameter(command, "EMployyeId", DbType.String, employee.EmployyeId);
            Database.AddInParameter(command, "Forname", DbType.String, employee.Forname);
            Database.AddInParameter(command, "SurName", DbType.Int32, employee.SurtName);
            Database.AddInParameter(command, "Email_addr", DbType.Int32, employee.Email_addr);
            Database.AddInParameter(command, "tel_num", DbType.Int32, employee.@tel_num);
            Database.AddInParameter(command, "CreatedBy", DbType.Int32, employee.@CreatedBy);
            Database.AddInParameter(command, "ErrorMessage", DbType.String, employee.ErrorMessage);
            Database.ExecuteNonQuery(command);
        }

--- Angular UI: HTML--

<!-- <p>employee works!</p> -->

<!-- Button to clear selection -->
<button (click)="onBtADD()">Add or Uodate</button>
<!-- AG Grid Angular Component -->

<ag-grid-angular style="width: 100%; height: 400px;" class="ag-theme-balham" #agGrid [pagination]="true"
[defaultColDef]="columnDefs" [paginationPageSize]="paginationPageSize" [rowData]="rowData "
[columnDefs]="columnDefs" [floatingFilter]=true [rowDragManaged]="true"   [components]="components"
[singleClickEdit]="true" [rowModelType]="rowModelType" [rowClassRules]="rowClassRules" 
rowSelection="multiple" (cellValueChanged)="onCellValueChanged($event)" 
[frameworkComponents]="frameworkComponents" (gridReady)="onGridReady($event)"
(rowClicked)="onRowClick($event)">
</ag-grid-angular>

SERVICE

import { Injectable } from '@angular/core';
import { EployeeModel } from './invoice/invoice';
import { Observable } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  url: string = "";
  constructor(private http: HttpClient) { }
  updateInvoice(invoice: EployeeModel): Observable<EployeeModel> {
    return this.http.post<EployeeModel>(this.url + "Employee/PostData", invoice, {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'

      })
    })
  }
}

-- angular COMPONET to connect API and display data

  onBtADD() {
this.gridApi.stopEditing();

let selectedNodes = this.gridApi.getSelectedNodes();
this.selectedData = selectedNodes.map(node => node.data);

if (this.selectedData.length == 1 ) {
  this.EmployeeService
    .InsertupdateInvoice(this.getRowData(this.selectedData))
    .subscribe(
      (data: any) => {
        if (data == 'SUCCESS' || data == 'Record added successfully.') {
          this.loadGrid();
        
        }
      }, (error: HttpErrorResponse) => {
        if (error.status === 400) {
          var error_message: string = "";
          for (var key in error.error.ModelState) {
            for (var i = 0; i < error.error.ModelState[key].length; i++) {
              error_message = error_message + error.error.ModelState[key][i] + "<br/>";
            }

          }
        }
      })
}
else {
  this.alertService.info('Please select single record to update or record', this.options);
  setTimeout(() => this.alertService.clear(), 20000);
}

}

-- SQL

INSERT /UPDATE SP

IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertUpdateEmplyee]') AND type in (N'P', N'PC'))
BEGIN
    EXEC('CREATE PROCEDURE dbo.InsertUpdateEmplyee AS BEGIN SELECT 1 END')
END
GO
/************************************************************************************************************  

TEST:  
DECLARE @ErrorMessageOUT VARCHAR(100)   
EXEC dbo.InsertUpdateCluster 0,
SELECT @ErrorMessageOUT

************************************************************************************************************/  
ALTER PROCEDURE dbo.InsertUpdateEmplyee 
  @EmployeeId VARCHAR(100)  
, @Forename VARCHAR(100)  
, @Surname VARCHAR(200)
, @Email_addr VARCHAR(200)
, @tel_num VARCHAR(100)
, @CreatedBy VARCHAR(100)   
, @ErrorMessage VARCHAR(500) OUTPUT  
  
AS  
BEGIN  
 BEGIN TRY  
   DECLARE @CreatedDate DATETIME = GETUTCDATE()
  SET @ErrorMessage = ''  

  If EXISTS(SELECT 1 FROM  dbo.Employee WHERE EmployeeId =@EmployeeId )  
  BEGIN  
   UPDATE  dbo.Employee   
   SET     
        EmployeeId =    @EmployeeId ,
        Forename=   @Forename,
        Surname=    @Surname,
        Email= @Email_addr ,
        Telephone=  @tel_num ,
        CreatedBy=  @CreatedBy,
        CreatedDate=    @CreatedDate,
      EmployeeId =@EmployeeId
  
   RETURN;  
  END  
  ELSE    
  BEGIN  
   IF NOT EXISTS (select 1 from dbo.Employee WITH (NOLOCK) WHERE EmployeeId =@EmployeeId ) 
    BEGIN
        INSERT INTO emplEmployee(EmployeeId, Forename, Surname,  
                        Email, Telephone, CreatedBy, CreatedDate)
        SELECT  @EmployeeId AS GlobalId,
            @Forename,
            @Surname,
            @Email_addr AS Email,
            @tel_num AS Telephone,
            @CreatedBy,
            @CreatedDate
     END
   ELSE
   BEGIN
    SET @ErrorMessage = @ErrorMessage + 'Employee already exist.<br />' 
   END
  END  
     
    
 END TRY  
 BEGIN CATCH   
  EXEC ReThrowError    
 END CATCH  
END   

-- SQL SIDE SCRIPTING for CRUD TABLE

CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [EmployeeId] [varchar](50) NOT NULL PRIMARY KEY,
    [Forename] [varchar](200) NULL,
    [Surname] [varchar](200) NULL,
    [FullName] [varchar](400) NULL,
    [Email] [varchar](100) NULL,
    [Telephone] [varchar](50) NULL,
    [CreatedBy] [varchar](50) NULL,
    [CreatedDate] [datetime] NULL,
    [UpdatedBy] [varchar](50) NULL,
    [UpdatedDate] [datetime] NULL
) 
GO
1 Answers

If you want to make the application more aligned and maintainable. Look into EF framework and structure your employees as objects of classes. This makes it a lot easier to add and remove new items. Alternatively you can also use Dapper if you want some more complex features.

Related