This commit is contained in:
2023-02-22 12:12:38 +01:00
parent 4ce7d62433
commit 185746ee72
54 changed files with 3701 additions and 3701 deletions

726
.gitignore vendored
View File

@@ -1,364 +1,364 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
WebAPI/.local-chromium
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
WebAPI/.local-chromium
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@@ -1,7 +1,7 @@
{
"folders": [
{
"path": "."
}
]
{
"folders": [
{
"path": "."
}
]
}

View File

@@ -1,25 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33110.190
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiunaBI-WebAPI", "WebAPI\DiunaBI-WebAPI.csproj", "{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2CFA03A7-56D9-4ADE-9B6A-1A3383A1C104}
EndGlobalSection
EndGlobal

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33110.190
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiunaBI-WebAPI", "WebAPI\DiunaBI-WebAPI.csproj", "{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{799D68C2-A4C1-43F8-8C35-1126C0AC32D6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2CFA03A7-56D9-4ADE-9B6A-1A3383A1C104}
EndGlobalSection
EndGlobal

View File

@@ -1,7 +1,7 @@
{
"folders": [
{
"path": ".."
}
]
{
"folders": [
{
"path": ".."
}
]
}

View File

@@ -1,13 +1,13 @@
<div class="loading-container" *ngIf="loading">
<img class="loading-img" src="../../assets/loader.gif" />
</div>
<div class="logo"></div>
<div class="bg">
<div class="container">
<mat-card appearance="outlined" class="form">
<mat-card-content>
<div class="" id="google-button"></div>
</mat-card-content>
</mat-card>
</div>
<div class="loading-container" *ngIf="loading">
<img class="loading-img" src="../../assets/loader.gif" />
</div>
<div class="logo"></div>
<div class="bg">
<div class="container">
<mat-card appearance="outlined" class="form">
<mat-card-content>
<div class="" id="google-button"></div>
</mat-card-content>
</mat-card>
</div>
</div>

View File

@@ -1,63 +1,63 @@
.bg {
background-image: url("../../../assets/bg.jpg");
height: 70vh;
background-size: cover;
padding-top: 30vh;
}
.container {
width: fit-content;
display: block;
margin: auto;
}
.form {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.logo {
background-image: url('../../../assets/logo.png');
background-size: cover;
position: absolute;
top: 10px;
right: 10px;
width: 250px;
height: 250px;
opacity: 0.6;
}
mat-form-field {
width: 100%;
}
.user {
text-align: right;
}
.load {
text-align: center;
}
.loading-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.3);
z-index: 1400;
}
.loading-img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* for mobile */
@media screen and (max-width: 700px) {
.container {
width: 90%;
}
.logo {
width: 150px;
height: 150px;
}
}
.bg {
background-image: url("../../../assets/bg.jpg");
height: 70vh;
background-size: cover;
padding-top: 30vh;
}
.container {
width: fit-content;
display: block;
margin: auto;
}
.form {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.logo {
background-image: url('../../../assets/logo.png');
background-size: cover;
position: absolute;
top: 10px;
right: 10px;
width: 250px;
height: 250px;
opacity: 0.6;
}
mat-form-field {
width: 100%;
}
.user {
text-align: right;
}
.load {
text-align: center;
}
.loading-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.3);
z-index: 1400;
}
.loading-img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* for mobile */
@media screen and (max-width: 700px) {
.container {
width: 90%;
}
.logo {
width: 150px;
height: 150px;
}
}

View File

@@ -1,98 +1,98 @@
import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import jwt_decode from "jwt-decode";
import { AuthService } from 'src/app/auth/auth.service';
import { User } from 'src/app/models/user.model';
import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent implements OnInit {
constructor(
private router$: Router,
private auth$: AuthService,
private ngZone$: NgZone,
private notifications$: NotificationsService
) { }
loading = false;
ngOnInit(): void {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.onGoogleLibraryLoad = () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.initialize({
client_id: environment.google.clientId,
callback: this.handleCredentialResponse.bind(this),
auto_select: true,
cancel_on_tap_outside: true
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.renderButton(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
document.getElementById("google-button"),
{ theme: "outline", size: "large", width: "100%" }
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.prompt();
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async handleCredentialResponse(response: any) {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const responsePayload: any = jwt_decode(response.credential);
this.auth$.user = new User({
googleCredentials: response.credential,
userName: `${responsePayload.given_name} ${responsePayload.family_name}`,
email: responsePayload.email,
avatar: responsePayload.picture
});
this.ngZone$.run(() => {
this.loading = true;
});
this.auth$.googleCredential = response.credential;
await this.auth$.getAPIToken();
this.ngZone$.run(() => {
this.router$.navigate(['/app']);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
console.error('handleCredentialResponse', e);
this.ngZone$.run(() => {
this.loading = false;
});
if (e.status === 401) {
this.ngZone$.run(() => {
this.notifications$.add({
text: "User not exists in DiunaBI database.",
btn: "OK",
duration: 15000
});
});
} else {
this.ngZone$.run(() => {
this.notifications$.add({
text: "DiunaBI server not responded.",
btn: "OK",
duration: 15000
});
});
}
} finally {
this.loading = false;
}
}
}
import { Component, NgZone, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import jwt_decode from "jwt-decode";
import { AuthService } from 'src/app/auth/auth.service';
import { User } from 'src/app/models/user.model';
import { NotificationsService } from 'src/app/services/notifications.service';
import { environment } from 'src/environments/environment';
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent implements OnInit {
constructor(
private router$: Router,
private auth$: AuthService,
private ngZone$: NgZone,
private notifications$: NotificationsService
) { }
loading = false;
ngOnInit(): void {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.onGoogleLibraryLoad = () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.initialize({
client_id: environment.google.clientId,
callback: this.handleCredentialResponse.bind(this),
auto_select: true,
cancel_on_tap_outside: true
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.renderButton(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
document.getElementById("google-button"),
{ theme: "outline", size: "large", width: "100%" }
);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
google.accounts.id.prompt();
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async handleCredentialResponse(response: any) {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const responsePayload: any = jwt_decode(response.credential);
this.auth$.user = new User({
googleCredentials: response.credential,
userName: `${responsePayload.given_name} ${responsePayload.family_name}`,
email: responsePayload.email,
avatar: responsePayload.picture
});
this.ngZone$.run(() => {
this.loading = true;
});
this.auth$.googleCredential = response.credential;
await this.auth$.getAPIToken();
this.ngZone$.run(() => {
this.router$.navigate(['/app']);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
console.error('handleCredentialResponse', e);
this.ngZone$.run(() => {
this.loading = false;
});
if (e.status === 401) {
this.ngZone$.run(() => {
this.notifications$.add({
text: "User not exists in DiunaBI database.",
btn: "OK",
duration: 15000
});
});
} else {
this.ngZone$.run(() => {
this.notifications$.add({
text: "DiunaBI server not responded.",
btn: "OK",
duration: 15000
});
});
}
} finally {
this.loading = false;
}
}
}

View File

@@ -1,15 +1,15 @@
mat-card {
margin-bottom: 3px;
background-color: rgba(255, 145, 0, 0.4);
}
.action-button {
cursor: pointer;
}
.text {
float: left;
}
.btn {
float: right;
color: red;
margin-left: 5px;
mat-card {
margin-bottom: 3px;
background-color: rgba(255, 145, 0, 0.4);
}
.action-button {
cursor: pointer;
}
.text {
float: left;
}
.btn {
float: right;
color: red;
margin-left: 5px;
}

View File

@@ -1,56 +1,56 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import { EMPTY, Observable } from 'rxjs';
import moment from 'moment';
import { catchError, mergeMap } from 'rxjs/operators';
import { NotificationsService } from '../services/notifications.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private auth$: AuthService,
private notifications$: NotificationsService
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
console.log('Welcome to interceptor:', request.url);
console.log('IsAuth?', request.url.includes('/auth/apiToken'));
if (!request.url.includes('/auth/apiToken')) {
console.log(this.auth$.expirationTime.format(), moment.utc().format());
if (this.auth$.expirationTime.isBefore(moment.utc())) {
console.log('Need to refresh token');
return this.auth$.getAPITokenObservable().pipe(
mergeMap(() => {
console.log('New token is ready');
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}),
catchError(() => {
this.notifications$.add({
text: "User session is expired and unable to restore. Please restart the app.",
btn: "Restart",
action: () => { window.location.reload(); },
duration: 5000,
});
return EMPTY;
})
);
} else {
console.log('TOken is fine');
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}
} else {
return next.handle(request);
}
}
}
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import { EMPTY, Observable } from 'rxjs';
import moment from 'moment';
import { catchError, mergeMap } from 'rxjs/operators';
import { NotificationsService } from '../services/notifications.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private auth$: AuthService,
private notifications$: NotificationsService
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
console.log('Welcome to interceptor:', request.url);
console.log('IsAuth?', request.url.includes('/auth/apiToken'));
if (!request.url.includes('/auth/apiToken')) {
console.log(this.auth$.expirationTime.format(), moment.utc().format());
if (this.auth$.expirationTime.isBefore(moment.utc())) {
console.log('Need to refresh token');
return this.auth$.getAPITokenObservable().pipe(
mergeMap(() => {
console.log('New token is ready');
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}),
catchError(() => {
this.notifications$.add({
text: "User session is expired and unable to restore. Please restart the app.",
btn: "Restart",
action: () => { window.location.reload(); },
duration: 5000,
});
return EMPTY;
})
);
} else {
console.log('TOken is fine');
return next.handle(request.clone({
headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
}));
}
} else {
return next.handle(request);
}
}
}

View File

@@ -1,42 +1,42 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { finalize, Observable } from 'rxjs';
import { DataService } from '../services/data.service';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private tasks = 0;
constructor(
private data$: DataService
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
this.addTask();
return next.handle(request).pipe(
finalize(() => {
this.removeTask();
})
);
}
addTask() {
this.tasks++;
if (this.tasks === 1) {
this.data$.showLoader.next(true);
}
}
removeTask() {
this.tasks--;
if (this.tasks === 0) {
this.data$.showLoader.next(false);
}
}
}
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { finalize, Observable } from 'rxjs';
import { DataService } from '../services/data.service';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private tasks = 0;
constructor(
private data$: DataService
) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
this.addTask();
return next.handle(request).pipe(
finalize(() => {
this.removeTask();
})
);
}
addTask() {
this.tasks++;
if (this.tasks === 1) {
this.data$.showLoader.next(true);
}
}
removeTask() {
this.tasks--;
if (this.tasks === 0) {
this.data$.showLoader.next(false);
}
}
}

View File

@@ -1,128 +1,128 @@
.main-container {
display: flex;
flex-direction: column;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.sidenav-container {
flex: 1;
}
mat-icon.menu-icon {
margin-right: 3px;
color: gray;
}
mat-nav-list.menu-sublist {
padding-left: 10px;
}
mat-nav-list.menu-sublist > a {
font-size: small;
}
div.footer {
text-align: right;
font-size: smaller;
color: gray;
padding-right: 5px;
}
.fill-to-right {
flex: 1 1 auto;
}
span.topbar-user-name {
font-size: small;
}
h1.topbar-app-name {
margin-bottom: 0px;
}
mat-sidenav {
width: 200px;
}
.list-container {
display: flex;
flex-direction: column;
min-width: 300px;
height: 98%;
}
.top-list-container {
display: flex;
flex-direction: column;
min-width: 30vh;
height: 54vh;
}
.bottom-list-container {
display: flex;
flex-direction: column;
height: 35vh;
}
.table {
overflow: auto;
height: 100%;
}
.list-header {
min-height: 50px;
padding: 4px 12px 0;
}
.mat-mdc-form-field {
font-size: 14px;
width: 100%;
}
mat-form-field.detail-input {
width: 90%;
text-align: left;
color: black;
}
mat-form-field.detail-input-full-width {
width: 96%;
text-align: left;
color: black;
}
input[disabled] {
color: black;
-webkit-text-fill-color: black;
opacity: 1; /* required on iOS */
}
textarea[disabled] {
color: black;
-webkit-text-fill-color: black;
opacity: 1; /* required on iOS */
}
.loading-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.3);
z-index: 1400;
}
.loading-img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.flip-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.95);
z-index: 1500;
}
.flip-msg {
margin: auto;
text-align: center;
padding-top: 45vh;
color: rgb(205, 206, 177);
font-size: larger;
}
/* links */
a:link,
a:visited {
color: black;
.main-container {
display: flex;
flex-direction: column;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.sidenav-container {
flex: 1;
}
mat-icon.menu-icon {
margin-right: 3px;
color: gray;
}
mat-nav-list.menu-sublist {
padding-left: 10px;
}
mat-nav-list.menu-sublist > a {
font-size: small;
}
div.footer {
text-align: right;
font-size: smaller;
color: gray;
padding-right: 5px;
}
.fill-to-right {
flex: 1 1 auto;
}
span.topbar-user-name {
font-size: small;
}
h1.topbar-app-name {
margin-bottom: 0px;
}
mat-sidenav {
width: 200px;
}
.list-container {
display: flex;
flex-direction: column;
min-width: 300px;
height: 98%;
}
.top-list-container {
display: flex;
flex-direction: column;
min-width: 30vh;
height: 54vh;
}
.bottom-list-container {
display: flex;
flex-direction: column;
height: 35vh;
}
.table {
overflow: auto;
height: 100%;
}
.list-header {
min-height: 50px;
padding: 4px 12px 0;
}
.mat-mdc-form-field {
font-size: 14px;
width: 100%;
}
mat-form-field.detail-input {
width: 90%;
text-align: left;
color: black;
}
mat-form-field.detail-input-full-width {
width: 96%;
text-align: left;
color: black;
}
input[disabled] {
color: black;
-webkit-text-fill-color: black;
opacity: 1; /* required on iOS */
}
textarea[disabled] {
color: black;
-webkit-text-fill-color: black;
opacity: 1; /* required on iOS */
}
.loading-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.3);
z-index: 1400;
}
.loading-img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.flip-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.95);
z-index: 1500;
}
.flip-msg {
margin: auto;
text-align: center;
padding-top: 45vh;
color: rgb(205, 206, 177);
font-size: larger;
}
/* links */
a:link,
a:visited {
color: black;
}

View File

@@ -1,73 +1,73 @@
import {NgModule} from '@angular/core';
//import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
//import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
//import { MatCheckboxModule } from '@angular/material/checkbox';
//import { MatChipsModule } from '@angular/material/chips';
//import { MatStepperModule } from '@angular/material/stepper';
//import { MatDatepickerModule } from '@angular/material/datepicker';
//import { MatDialogModule } from '@angular/material/dialog';
//import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
//import { MatProgressBarModule } from '@angular/material/progress-bar';
//import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
//import { MatRadioModule } from '@angular/material/radio';
//import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
//import { MatSliderModule } from '@angular/material/slider';
//import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
//import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
//import { MatTooltipModule } from '@angular/material/tooltip';
//import {CdkTableModule} from '@angular/cdk/table';
//import {MatBadgeModule} from '@angular/material/badge';
import {MatBottomSheetModule} from '@angular/material/bottom-sheet';
@NgModule({
exports: [
// CdkTableModule,
// MatAutocompleteModule,
MatButtonModule,
// MatButtonToggleModule,
MatCardModule,
// MatCheckboxModule,
// MatChipsModule,
// MatStepperModule,
// MatDatepickerModule,
// MatDialogModule,
// MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatPaginatorModule,
// MatProgressBarModule,
// MatProgressSpinnerModule,
// MatRadioModule,
// MatRippleModule,
MatSelectModule,
// MatSidenavModule,
// MatSliderModule,
// MatSlideToggleModule,
MatSortModule,
MatTableModule,
// MatTabsModule,
MatToolbarModule,
// MatTooltipModule,
MatSidenavModule,
// MatBadgeModule,
MatBottomSheetModule
],
providers: []
})
import {NgModule} from '@angular/core';
//import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
//import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatCardModule } from '@angular/material/card';
//import { MatCheckboxModule } from '@angular/material/checkbox';
//import { MatChipsModule } from '@angular/material/chips';
//import { MatStepperModule } from '@angular/material/stepper';
//import { MatDatepickerModule } from '@angular/material/datepicker';
//import { MatDialogModule } from '@angular/material/dialog';
//import { MatExpansionModule } from '@angular/material/expansion';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatPaginatorModule } from '@angular/material/paginator';
//import { MatProgressBarModule } from '@angular/material/progress-bar';
//import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
//import { MatRadioModule } from '@angular/material/radio';
//import { MatRippleModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
//import { MatSliderModule } from '@angular/material/slider';
//import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
//import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
//import { MatTooltipModule } from '@angular/material/tooltip';
//import {CdkTableModule} from '@angular/cdk/table';
//import {MatBadgeModule} from '@angular/material/badge';
import {MatBottomSheetModule} from '@angular/material/bottom-sheet';
@NgModule({
exports: [
// CdkTableModule,
// MatAutocompleteModule,
MatButtonModule,
// MatButtonToggleModule,
MatCardModule,
// MatCheckboxModule,
// MatChipsModule,
// MatStepperModule,
// MatDatepickerModule,
// MatDialogModule,
// MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatPaginatorModule,
// MatProgressBarModule,
// MatProgressSpinnerModule,
// MatRadioModule,
// MatRippleModule,
MatSelectModule,
// MatSidenavModule,
// MatSliderModule,
// MatSlideToggleModule,
MatSortModule,
MatTableModule,
// MatTabsModule,
MatToolbarModule,
// MatTooltipModule,
MatSidenavModule,
// MatBadgeModule,
MatBottomSheetModule
],
providers: []
})
export class MaterialModule {}

View File

@@ -1,35 +1,35 @@
import { Moment } from 'moment';
import { Deserializable } from './deserializable.model';
import { Serializable } from './serializable.model';
import * as moment from 'moment';
import { User } from './user.model';
export class Base implements Deserializable, Serializable {
id?: string;
createdAt?: Moment;
modifiedAt?: Moment;
createdById?: string;
modifiedById?: string;
createdBy?: User;
modifiedBy?: User;
constructor(data: Partial<Base> = {}) {
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deserialize(input: any): this {
if (input.createdAt) { input.createdAt = moment(input.createdAt).utc(true); }
if (input.modifiedAt) { input.modifiedAt = moment(input.modifiedAt).utc(true); }
if (input.createdBy) { input.createdBy = new User(input.createdBy); }
if (input.modifiedBy) { input.modifiedBy = new User(input.modifiedBy); }
Object.assign(this, input);
return this;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serialize() : any {
return Object.assign({}, this);
}
import { Moment } from 'moment';
import { Deserializable } from './deserializable.model';
import { Serializable } from './serializable.model';
import * as moment from 'moment';
import { User } from './user.model';
export class Base implements Deserializable, Serializable {
id?: string;
createdAt?: Moment;
modifiedAt?: Moment;
createdById?: string;
modifiedById?: string;
createdBy?: User;
modifiedBy?: User;
constructor(data: Partial<Base> = {}) {
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deserialize(input: any): this {
if (input.createdAt) { input.createdAt = moment(input.createdAt).utc(true); }
if (input.modifiedAt) { input.modifiedAt = moment(input.modifiedAt).utc(true); }
if (input.createdBy) { input.createdBy = new User(input.createdBy); }
if (input.modifiedBy) { input.modifiedBy = new User(input.modifiedBy); }
Object.assign(this, input);
return this;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serialize() : any {
return Object.assign({}, this);
}
}

View File

@@ -1,4 +1,4 @@
export interface Deserializable {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deserialize(input: any): this;
export interface Deserializable {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
deserialize(input: any): this;
}

View File

@@ -1,124 +1,124 @@
import { Base } from './base.model';
import { UntypedFormBuilder, Validators, UntypedFormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map } from 'rxjs';
import { Record } from 'src/app/models/record.model';
export class Layer extends Base {
// eslint-disable-next-line @typescript-eslint/ban-types
number?: Number;
source?: string;
name?: string;
records: Record[] = [];
created?: string;
constructor(data: Partial<Layer> = {}) {
super();
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override deserialize(input: any): this {
Object.assign(this, Object.assign(this, super.deserialize(input)));
if (this.records) { this.records = this.records.map(x => new Record().deserialize(x)); }
return this;
}
override serialize() {
this.number = 0; // will be overrided in backend
return Object.assign({}, this);
}
static getForm(fb: UntypedFormBuilder) {
return fb.group({
id: [null],
name: ['', Validators.required],
source: ['', Validators.required],
sheetId: '1G_Hu8DTP-PSPNXTaVYhc_ppnTQi6HWoA4oXSSdUmM9E',
createdAt: '',
modifiedAt: '',
createdBy: '',
modifiedBy: '',
modified: '',
created: ''
});
}
fillForm(form: UntypedFormGroup) {
form.patchValue(this);
form.patchValue({
createdBy: this.createdBy?.userName,
modifiedBy: this.modifiedBy?.userName
});
}
loadForm(form: UntypedFormGroup) {
for (const field of Object.keys(form.controls)) {
this[field as keyof Layer] = form.controls[field].value;
}
this.createdBy = undefined;
this.modifiedBy = undefined;
}
//API Actions
static add(input: Layer, _http: HttpClient): Promise<string> {
return new Promise((resolve, reject) => {
_http.post<string>(`${environment.api.url}/layers`, { ...input.serialize(), }).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
}
);
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static getList(_http: HttpClient): any {
return new Promise((resolve, reject) => {
_http.get<Layer[]>(`${environment.api.url}/layers`)
.pipe(map(data => data.map(x => new Layer().deserialize(x))))
.subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
})
});
}
static getById(id: string, _http: HttpClient): Promise<Layer> {
return new Promise((resolve, reject) => {
_http.get<Layer>(`${environment.api.url}/layers/${id}`).pipe(map(x => new Layer().deserialize(x))).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
})
});
}
static parseFile(file: File, _http: HttpClient): Promise<Layer[]> {
const formData = new FormData();
formData.append(file.name, file);
return new Promise((resolve, reject) => {
_http.post<Layer[]>(`${environment.api.url}/layers/parseFile`, formData,
).pipe(map(data => data.map(x => new Layer().deserialize(x))))
.subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
static parseGoogleSheet(sheetId: string, _http: HttpClient): Promise<Layer> {
return new Promise((resolve, reject) => {
_http.get<Layer>(`${environment.api.url}/layers/parseGoogleSheet/${sheetId}`,
).pipe(map(data => new Layer().deserialize(data)))
.subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
static exportToGoogleSheet(id: string, _http: HttpClient): Promise<boolean> {
return new Promise((resolve, reject) => {
_http.get<boolean>(`${environment.api.url}/layers/exportToGoogleSheet/${id}`,
).subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
import { Base } from './base.model';
import { UntypedFormBuilder, Validators, UntypedFormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map } from 'rxjs';
import { Record } from 'src/app/models/record.model';
export class Layer extends Base {
// eslint-disable-next-line @typescript-eslint/ban-types
number?: Number;
source?: string;
name?: string;
records: Record[] = [];
created?: string;
constructor(data: Partial<Layer> = {}) {
super();
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override deserialize(input: any): this {
Object.assign(this, Object.assign(this, super.deserialize(input)));
if (this.records) { this.records = this.records.map(x => new Record().deserialize(x)); }
return this;
}
override serialize() {
this.number = 0; // will be overrided in backend
return Object.assign({}, this);
}
static getForm(fb: UntypedFormBuilder) {
return fb.group({
id: [null],
name: ['', Validators.required],
source: ['', Validators.required],
sheetId: '1G_Hu8DTP-PSPNXTaVYhc_ppnTQi6HWoA4oXSSdUmM9E',
createdAt: '',
modifiedAt: '',
createdBy: '',
modifiedBy: '',
modified: '',
created: ''
});
}
fillForm(form: UntypedFormGroup) {
form.patchValue(this);
form.patchValue({
createdBy: this.createdBy?.userName,
modifiedBy: this.modifiedBy?.userName
});
}
loadForm(form: UntypedFormGroup) {
for (const field of Object.keys(form.controls)) {
this[field as keyof Layer] = form.controls[field].value;
}
this.createdBy = undefined;
this.modifiedBy = undefined;
}
//API Actions
static add(input: Layer, _http: HttpClient): Promise<string> {
return new Promise((resolve, reject) => {
_http.post<string>(`${environment.api.url}/layers`, { ...input.serialize(), }).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
}
);
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static getList(_http: HttpClient): any {
return new Promise((resolve, reject) => {
_http.get<Layer[]>(`${environment.api.url}/layers`)
.pipe(map(data => data.map(x => new Layer().deserialize(x))))
.subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
})
});
}
static getById(id: string, _http: HttpClient): Promise<Layer> {
return new Promise((resolve, reject) => {
_http.get<Layer>(`${environment.api.url}/layers/${id}`).pipe(map(x => new Layer().deserialize(x))).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
})
});
}
static parseFile(file: File, _http: HttpClient): Promise<Layer[]> {
const formData = new FormData();
formData.append(file.name, file);
return new Promise((resolve, reject) => {
_http.post<Layer[]>(`${environment.api.url}/layers/parseFile`, formData,
).pipe(map(data => data.map(x => new Layer().deserialize(x))))
.subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
static parseGoogleSheet(sheetId: string, _http: HttpClient): Promise<Layer> {
return new Promise((resolve, reject) => {
_http.get<Layer>(`${environment.api.url}/layers/parseGoogleSheet/${sheetId}`,
).pipe(map(data => new Layer().deserialize(data)))
.subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
static exportToGoogleSheet(id: string, _http: HttpClient): Promise<boolean> {
return new Promise((resolve, reject) => {
_http.get<boolean>(`${environment.api.url}/layers/exportToGoogleSheet/${id}`,
).subscribe({
next: (data) => {
resolve(data);
},
error: (e) => reject(e)
})
})
}
}

View File

@@ -1,22 +1,22 @@
import { Base } from './base.model';
export class Record extends Base {
code?: string;
value?: number;
desc1?: string;
desc2?: string;
desc3?: string;
desc4?: string;
desc5?: string;
constructor(data: Partial<Record> = {}) {
super();
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override deserialize(input: any): this {
Object.assign(this, Object.assign(this, super.deserialize(input)));
return this;
}
import { Base } from './base.model';
export class Record extends Base {
code?: string;
value?: number;
desc1?: string;
desc2?: string;
desc3?: string;
desc4?: string;
desc5?: string;
constructor(data: Partial<Record> = {}) {
super();
Object.assign(this, data);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
override deserialize(input: any): this {
Object.assign(this, Object.assign(this, super.deserialize(input)));
return this;
}
}

View File

@@ -1,4 +1,4 @@
export interface Serializable {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serialize(input: this): any;
export interface Serializable {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serialize(input: this): any;
}

View File

@@ -1,11 +1,11 @@
export class User {
id!: string;
email!: string;
userName!: string;
googleCredentials!: string;
avatar?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(input: any) {
Object.assign(this, input)
}
export class User {
id!: string;
email!: string;
userName!: string;
googleCredentials!: string;
avatar?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(input: any) {
Object.assign(this, input)
}
}

View File

@@ -1,14 +1,14 @@
import { Component } from '@angular/core';
import { DeviceService } from 'src/app/services/device.service';
@Component({
selector: 'app-board',
templateUrl: './board.component.html',
styleUrls: ['./board.component.scss']
})
export class BoardComponent {
constructor(
public _device: DeviceService
) { }
}
import { Component } from '@angular/core';
import { DeviceService } from 'src/app/services/device.service';
@Component({
selector: 'app-board',
templateUrl: './board.component.html',
styleUrls: ['./board.component.scss']
})
export class BoardComponent {
constructor(
public _device: DeviceService
) { }
}

View File

@@ -1,16 +1,16 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BoardComponent } from './board/board.component';
const routes: Routes = [
{
path: '',
component: BoardComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BoardComponent } from './board/board.component';
const routes: Routes = [
{
path: '',
component: BoardComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule { }

View File

@@ -1,17 +1,17 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { BoardComponent } from './board/board.component';
@NgModule({
declarations: [
BoardComponent
],
imports: [
CommonModule,
DashboardRoutingModule
]
})
export class DashboardModule { }
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { BoardComponent } from './board/board.component';
@NgModule({
declarations: [
BoardComponent
],
imports: [
CommonModule,
DashboardRoutingModule
]
})
export class DashboardModule { }

View File

@@ -1,5 +1,5 @@
@import "../../../main-view/main-view.component.scss";
.file-input {
display: none;
@import "../../../main-view/main-view.component.scss";
.file-input {
display: none;
}

View File

@@ -1,17 +1,17 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LayerDetailComponent } from './layer-detail/layer-detail.component';
import { LayerEditComponent } from './layer-edit/layer-edit.component';
import { LayersListComponent } from './layers-list/layers-list.component';
const routes: Routes = [
{ path: '', component: LayersListComponent },
{ path: 'Edit/:id', component: LayerEditComponent },
{ path: 'Detail/:id', component: LayerDetailComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LayersRoutingModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LayerDetailComponent } from './layer-detail/layer-detail.component';
import { LayerEditComponent } from './layer-edit/layer-edit.component';
import { LayersListComponent } from './layers-list/layers-list.component';
const routes: Routes = [
{ path: '', component: LayersListComponent },
{ path: 'Edit/:id', component: LayerEditComponent },
{ path: 'Detail/:id', component: LayerDetailComponent }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LayersRoutingModule { }

View File

@@ -1,88 +1,88 @@
Function IsDatabaseExists{
param([string]$containerId, [string]$database, [string]$sqlPass)
$query = "IF EXISTS
(SELECT name FROM master.sys.databases WHERE name = N'$database')
PRINT 'yes'
ELSE
PRINT 'no'"
return (docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query)
# USE master; ALTER DATABASE b-crm-master; SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE b-crm-master;
}
Function DropDatabase{
param([string]$containerId, [string]$database, [string]$sqlPass)
$query = "USE master;
ALTER DATABASE [$database]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE [$database];"
docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query > $null
return;
# /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P 'v](8Lc|RfG' -Q "USE master; ALTER DATABASE b-crm-master; SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE b-crm-master;"
}
Function AttachDatabase{
param([string]$containerId, [string]$database, [string]$sqlPass, [string]$mdfName, [string]$ldfName)
$query = "CREATE DATABASE [$database]
ON (FILENAME = N'/var/opt/mssql/data/$mdfName'),
(FILENAME = N'/var/opt/mssql/data/$ldfName') FOR ATTACH;
ALTER DATABASE [$database] SET READ_WRITE;"
docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query
return;
}
Function CopyFile{
param([string]$containerId, [string]$fileName)
docker cp ./Temp/$fileName $containerId"://var/opt/mssql/data/$fileName"
docker exec --user root $containerId chown mssql:root /var/opt/mssql/data/$fileName
return;
}
if ((Split-Path (Get-Location) -Leaf) -ne "DiunaBI") {
Write-Host "Error: Run script from main source directory.";
Exit;
}
try {
$containerId = (docker ps | Select-String "mssql").Line.split(" ")[0]
} catch {
Write-Host "Error: MSSQL container not exists (or Docker is not running)";
Exit;
}
Write-Host "MSSQL container id: "$containerId;
$sqlPass = "v](8Lc|RfG";
# Let's do the job!
@("diuna").ForEach({
$database = $_;
$ldfName = $database+"_log.ldf";
$mdfName = $database+".mdf";
Write-Host "Restoring database: "$database
# Download mdf/ldf nd check if files are new (donwload with success)
scp "crm.bim-it.pl:/var/opt/mssql/data/$mdfName" ./Temp/
if (((Get-Date) - ((Get-Item ./Temp/$mdfName).LastWriteTime)).TotalMinutes -gt 5) {
Write-Host "Error: $mdfName was not downloaded correctly."
continue;
}
scp "crm.bim-it.pl:/var/opt/mssql/data/$ldfName" ./Temp/
if (((Get-Date) - ((Get-Item ./Temp/$ldfName).LastWriteTime)).TotalMinutes -gt 5) {
Write-Host "Error: $ldfName was not downloaded correctly."
continue;
}
#drop existing database
DropDatabase $containerId $database $sqlPass;
if ((IsDatabaseExists $containerId $database $sqlPass) -eq 'yes') {
Write-Host "Error: $database still exists (drop error)"
continue;
}
#copy new files
CopyFile $containerId $mdfName
CopyFile $containerId $ldfName
#attach databases in container
AttachDatabase $containerId $database $sqlPass $mdfName $ldfName;
if ((IsDatabaseExists $containerId $database $sqlPass) -eq 'no') {
Write-Host "Error: $database still not exists (attach error)"
continue;
}
Write-Host "OK";
});
Function IsDatabaseExists{
param([string]$containerId, [string]$database, [string]$sqlPass)
$query = "IF EXISTS
(SELECT name FROM master.sys.databases WHERE name = N'$database')
PRINT 'yes'
ELSE
PRINT 'no'"
return (docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query)
# USE master; ALTER DATABASE b-crm-master; SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE b-crm-master;
}
Function DropDatabase{
param([string]$containerId, [string]$database, [string]$sqlPass)
$query = "USE master;
ALTER DATABASE [$database]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE [$database];"
docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query > $null
return;
# /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P 'v](8Lc|RfG' -Q "USE master; ALTER DATABASE b-crm-master; SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE b-crm-master;"
}
Function AttachDatabase{
param([string]$containerId, [string]$database, [string]$sqlPass, [string]$mdfName, [string]$ldfName)
$query = "CREATE DATABASE [$database]
ON (FILENAME = N'/var/opt/mssql/data/$mdfName'),
(FILENAME = N'/var/opt/mssql/data/$ldfName') FOR ATTACH;
ALTER DATABASE [$database] SET READ_WRITE;"
docker exec $containerId /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $sqlPass -Q $query
return;
}
Function CopyFile{
param([string]$containerId, [string]$fileName)
docker cp ./Temp/$fileName $containerId"://var/opt/mssql/data/$fileName"
docker exec --user root $containerId chown mssql:root /var/opt/mssql/data/$fileName
return;
}
if ((Split-Path (Get-Location) -Leaf) -ne "DiunaBI") {
Write-Host "Error: Run script from main source directory.";
Exit;
}
try {
$containerId = (docker ps | Select-String "mssql").Line.split(" ")[0]
} catch {
Write-Host "Error: MSSQL container not exists (or Docker is not running)";
Exit;
}
Write-Host "MSSQL container id: "$containerId;
$sqlPass = "v](8Lc|RfG";
# Let's do the job!
@("diuna").ForEach({
$database = $_;
$ldfName = $database+"_log.ldf";
$mdfName = $database+".mdf";
Write-Host "Restoring database: "$database
# Download mdf/ldf nd check if files are new (donwload with success)
scp "crm.bim-it.pl:/var/opt/mssql/data/$mdfName" ./Temp/
if (((Get-Date) - ((Get-Item ./Temp/$mdfName).LastWriteTime)).TotalMinutes -gt 5) {
Write-Host "Error: $mdfName was not downloaded correctly."
continue;
}
scp "crm.bim-it.pl:/var/opt/mssql/data/$ldfName" ./Temp/
if (((Get-Date) - ((Get-Item ./Temp/$ldfName).LastWriteTime)).TotalMinutes -gt 5) {
Write-Host "Error: $ldfName was not downloaded correctly."
continue;
}
#drop existing database
DropDatabase $containerId $database $sqlPass;
if ((IsDatabaseExists $containerId $database $sqlPass) -eq 'yes') {
Write-Host "Error: $database still exists (drop error)"
continue;
}
#copy new files
CopyFile $containerId $mdfName
CopyFile $containerId $ldfName
#attach databases in container
AttachDatabase $containerId $database $sqlPass $mdfName $ldfName;
if ((IsDatabaseExists $containerId $database $sqlPass) -eq 'no') {
Write-Host "Error: $database still not exists (attach error)"
continue;
}
Write-Host "OK";
});
Write-Host "All databases restored!";

View File

@@ -1,31 +1,31 @@
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using WebAPI.Models;
namespace WebAPI
{
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Layer> Layers { get; set; }
public DbSet<Record> Records { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public static readonly Microsoft.Extensions.Logging.LoggerFactory _myLoggerFactory =
new LoggerFactory(new[] {
new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider()
});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_myLoggerFactory);
}
}
}
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using WebAPI.Models;
namespace WebAPI
{
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Layer> Layers { get; set; }
public DbSet<Record> Records { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public static readonly Microsoft.Extensions.Logging.LoggerFactory _myLoggerFactory =
new LoggerFactory(new[] {
new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider()
});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_myLoggerFactory);
}
}
}

View File

@@ -1,72 +1,72 @@
using Google.Apis.Auth;
using Google.Apis.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
// [Authorize]
public class AuthController : Controller
{
private readonly AppDbContext db;
private readonly IConfiguration configuration;
public AuthController(
AppDbContext _db, IConfiguration _configuration)
{ db = _db; configuration = _configuration; }
[HttpPost]
[Route("apiToken")]
public async Task<IActionResult> apiToken([FromBody] string credential)
{
var settings = new GoogleJsonWebSignature.ValidationSettings()
{
Audience = new List<string> { configuration.GetValue<string>("GoogleClientId") }
};
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
var user = db.Users.Where(x => x.Email == payload.Email).FirstOrDefault();
if (user != null)
{
return Ok(JWTGenerator(user));
}
else
{
return Unauthorized();
}
}
private dynamic JWTGenerator(User user)
{
var key = Encoding.ASCII.GetBytes(configuration.GetValue<string>("Secret"));
var expirationTime = DateTime.UtcNow.AddMinutes(5);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),
Expires = expirationTime,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return new { token = stringToken, id = user.Id, expirationTime };
}
}
using Google.Apis.Auth;
using Google.Apis.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
// [Authorize]
public class AuthController : Controller
{
private readonly AppDbContext db;
private readonly IConfiguration configuration;
public AuthController(
AppDbContext _db, IConfiguration _configuration)
{ db = _db; configuration = _configuration; }
[HttpPost]
[Route("apiToken")]
public async Task<IActionResult> apiToken([FromBody] string credential)
{
var settings = new GoogleJsonWebSignature.ValidationSettings()
{
Audience = new List<string> { configuration.GetValue<string>("GoogleClientId") }
};
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
var user = db.Users.Where(x => x.Email == payload.Email).FirstOrDefault();
if (user != null)
{
return Ok(JWTGenerator(user));
}
else
{
return Unauthorized();
}
}
private dynamic JWTGenerator(User user)
{
var key = Encoding.ASCII.GetBytes(configuration.GetValue<string>("Secret"));
var expirationTime = DateTime.UtcNow.AddMinutes(5);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),
Expires = expirationTime,
SigningCredentials = new SigningCredentials
(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtToken = tokenHandler.WriteToken(token);
var stringToken = tokenHandler.WriteToken(token);
return new { token = stringToken, id = user.Id, expirationTime };
}
}
}

View File

@@ -1,182 +1,182 @@
using Google.Apis.Auth;
using Google.Apis.Http;
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.dataParsers;
using WebAPI.Exports;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class LayersController : Controller
{
private readonly AppDbContext db;
private SpreadsheetsResource.ValuesResource googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private readonly IConfiguration configuration;
public LayersController(
AppDbContext _db,
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
db = _db;
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
}
[HttpGet]
public IActionResult GetAll()
{
try
{
return Ok(db.Layers.Where(x => !x.IsDeleted).ToList());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpPost]
public IActionResult Save(Layer input)
{
try
{
Request.Headers.TryGetValue("userId", out var value);
Guid currentUserId = new Guid(value!);
return Ok(AddLayer(input, currentUserId).Id);
} catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("{id}")]
public IActionResult Get(Guid id)
{
try
{
return Ok(db.Layers
.Include(x => x.CreatedBy)
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("parseGoogleSheet/{sheetId}")]
public IActionResult ParseGoogleSheet(string sheetId)
{
string sheetName = "KOSZTY";
Layer layer = new Layer();
layer.Source = "GoogleSheet";
layer.Number = db.Layers.Count() + 1;
var parser = new googleSheetParser(googleSheetValues);
dynamic parsedSheet = parser.parse(sheetId);
layer.Records = parsedSheet.records;
layer.Name = $"W{layer.Number}-I-{sheetName}-{parsedSheet.date}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
return Ok(layer);
}
[HttpPost]
[DisableRequestSizeLimit]
[Route("parseFile")]
public IActionResult ParseFile()
{
var parser = new csvParser();
return Ok(parser.parse(Request.Form.Files[0]));
}
[HttpGet]
[Route("exportToGoogleSheet/{id}")]
public IActionResult ExportToGoogleSheet(Guid id)
{
Layer layer = db.Layers
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First();
var export = new googleSheetExport(googleDriveHelper, googleSheetValues);
export.export(layer);
return Ok(true);
}
[HttpGet]
[Route("autoImport/{apiKey}")]
[AllowAnonymous]
public IActionResult autoImport(string apiKey)
{
if (Request.Host.Value != "localhost:5400" || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
string sheetId = "1G_Hu8DTP-PSPNXTaVYhc_ppnTQi6HWoA4oXSSdUmM9E";
string sheetName = "KOSZTY";
Layer layer = new Layer();
layer.Source = "GoogleSheet";
layer.Number = db.Layers.Count() + 1;
var parser = new googleSheetParser(googleSheetValues);
dynamic parsedSheet = parser.parse(sheetId);
layer.Records = parsedSheet.records;
layer.Name = $"W{layer.Number}-I-{sheetName}-{parsedSheet.date}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
AddLayer(layer, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
return Ok("OK");
}
//
private Layer AddLayer(Layer input, Guid currentUserId)
{
input.Number = db.Layers.Count() + 1;
input.CreatedById = currentUserId;
input.ModifiedById = currentUserId;
input.CreatedAt = DateTime.UtcNow;
input.ModifiedAt = DateTime.UtcNow;
db.Layers.Add(input);
SaveRecords(input.Id, input.Records!, currentUserId);
db.SaveChanges();
return input;
}
private void SaveRecords(Guid id, ICollection<Models.Record> records, Guid currentUserId)
{
try
{
List<Guid> ids = new List<Guid>();
foreach (Record record in records)
{
record.CreatedById = currentUserId;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedById = currentUserId;
record.ModifiedAt = DateTime.UtcNow;
record.LayerId= id;
db.Records.Add(record);
}
}
catch (Exception)
{
throw;
}
}
}
using Google.Apis.Auth;
using Google.Apis.Http;
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.dataParsers;
using WebAPI.Exports;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class LayersController : Controller
{
private readonly AppDbContext db;
private SpreadsheetsResource.ValuesResource googleSheetValues;
private GoogleDriveHelper googleDriveHelper;
private readonly IConfiguration configuration;
public LayersController(
AppDbContext _db,
GoogleSheetsHelper _googleSheetsHelper,
GoogleDriveHelper _googleDriveHelper,
IConfiguration _configuration)
{
db = _db;
googleSheetValues = _googleSheetsHelper.Service.Spreadsheets.Values;
googleDriveHelper = _googleDriveHelper;
configuration = _configuration;
}
[HttpGet]
public IActionResult GetAll()
{
try
{
return Ok(db.Layers.Where(x => !x.IsDeleted).ToList());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpPost]
public IActionResult Save(Layer input)
{
try
{
Request.Headers.TryGetValue("userId", out var value);
Guid currentUserId = new Guid(value!);
return Ok(AddLayer(input, currentUserId).Id);
} catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("{id}")]
public IActionResult Get(Guid id)
{
try
{
return Ok(db.Layers
.Include(x => x.CreatedBy)
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First());
}
catch (Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpGet]
[Route("parseGoogleSheet/{sheetId}")]
public IActionResult ParseGoogleSheet(string sheetId)
{
string sheetName = "KOSZTY";
Layer layer = new Layer();
layer.Source = "GoogleSheet";
layer.Number = db.Layers.Count() + 1;
var parser = new googleSheetParser(googleSheetValues);
dynamic parsedSheet = parser.parse(sheetId);
layer.Records = parsedSheet.records;
layer.Name = $"W{layer.Number}-I-{sheetName}-{parsedSheet.date}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
return Ok(layer);
}
[HttpPost]
[DisableRequestSizeLimit]
[Route("parseFile")]
public IActionResult ParseFile()
{
var parser = new csvParser();
return Ok(parser.parse(Request.Form.Files[0]));
}
[HttpGet]
[Route("exportToGoogleSheet/{id}")]
public IActionResult ExportToGoogleSheet(Guid id)
{
Layer layer = db.Layers
.Include(x => x.Records)
.Where(x => x.Id == id && !x.IsDeleted).First();
var export = new googleSheetExport(googleDriveHelper, googleSheetValues);
export.export(layer);
return Ok(true);
}
[HttpGet]
[Route("autoImport/{apiKey}")]
[AllowAnonymous]
public IActionResult autoImport(string apiKey)
{
if (Request.Host.Value != "localhost:5400" || apiKey != configuration["apiKey"])
{
return Unauthorized();
}
string sheetId = "1G_Hu8DTP-PSPNXTaVYhc_ppnTQi6HWoA4oXSSdUmM9E";
string sheetName = "KOSZTY";
Layer layer = new Layer();
layer.Source = "GoogleSheet";
layer.Number = db.Layers.Count() + 1;
var parser = new googleSheetParser(googleSheetValues);
dynamic parsedSheet = parser.parse(sheetId);
layer.Records = parsedSheet.records;
layer.Name = $"W{layer.Number}-I-{sheetName}-{parsedSheet.date}-{DateTime.Now.ToString("yyyyMMddHHmm")}";
AddLayer(layer, Guid.Parse("F392209E-123E-4651-A5A4-0B1D6CF9FF9D"));
return Ok("OK");
}
//
private Layer AddLayer(Layer input, Guid currentUserId)
{
input.Number = db.Layers.Count() + 1;
input.CreatedById = currentUserId;
input.ModifiedById = currentUserId;
input.CreatedAt = DateTime.UtcNow;
input.ModifiedAt = DateTime.UtcNow;
db.Layers.Add(input);
SaveRecords(input.Id, input.Records!, currentUserId);
db.SaveChanges();
return input;
}
private void SaveRecords(Guid id, ICollection<Models.Record> records, Guid currentUserId)
{
try
{
List<Guid> ids = new List<Guid>();
foreach (Record record in records)
{
record.CreatedById = currentUserId;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedById = currentUserId;
record.ModifiedAt = DateTime.UtcNow;
record.LayerId= id;
db.Records.Add(record);
}
}
catch (Exception)
{
throw;
}
}
}
}

View File

@@ -1,36 +1,36 @@
using Google.Apis.Auth;
using Google.Apis.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PingController : Controller
{
private readonly IConfiguration configuration;
public PingController(
IConfiguration _configuration)
{
configuration = _configuration;
}
[HttpGet]
[Route("Ping")]
[AllowAnonymous]
public IActionResult Ping()
{
return Ok(configuration["PONG"]);
}
}
using Google.Apis.Auth;
using Google.Apis.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
using Microsoft.IdentityModel.Tokens;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI.Models;
namespace WebAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class PingController : Controller
{
private readonly IConfiguration configuration;
public PingController(
IConfiguration _configuration)
{
configuration = _configuration;
}
[HttpGet]
[Route("Ping")]
[AllowAnonymous]
public IActionResult Ping()
{
return Ok(configuration["PONG"]);
}
}
}

View File

@@ -1,33 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="Google.Apis.Auth" Version="1.58.0" />
<PackageReference Include="Google.Apis.Drive.v3" Version="1.58.0.2859" />
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.58.0.2826" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Content Update="client_secrets.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="Google.Apis.Auth" Version="1.58.0" />
<PackageReference Include="Google.Apis.Drive.v3" Version="1.58.0.2859" />
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.58.0.2826" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Content Update="client_secrets.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -1,50 +1,50 @@
using Google.Apis.Drive.v3.Data;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using WebAPI.Models;
using static Google.Apis.Drive.v3.FilesResource;
namespace WebAPI.Exports
{
public class googleSheetExport
{
private GoogleDriveHelper googleDriveHelper;
private SpreadsheetsResource.ValuesResource googleSheetValues;
public googleSheetExport(GoogleDriveHelper _googleDriveHelper, SpreadsheetsResource.ValuesResource _googleSheetValues)
{
googleDriveHelper = _googleDriveHelper;
googleSheetValues = _googleSheetValues;
}
public void export(Layer layer)
{
try
{
List<IList<object>> data = new List<IList<object>>() { new List<object>() { layer.Name!, layer.Number! } };
foreach (Record record in layer.Records!)
{
data.Add(new List<object> { record.Code!, record.Value });
}
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = $"export-{DateTime.Now}";
body.MimeType = "application/vnd.google-apps.spreadsheet";
body.Parents = new List<string> { "1c5GBQmsIoj6a9L-JYFTaLEZ3EfkbQHPt" };
CreateRequest request = googleDriveHelper.Service.Files.Create(body);
var file = request.Execute();
string sheetId = file.Id;
var range = $"Sheet1!A1:B${data.Count}";
ValueRange valueRange = new ValueRange() { Values = data};
var updateRequest = googleSheetValues.Update(valueRange, sheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
using Google.Apis.Drive.v3.Data;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using WebAPI.Models;
using static Google.Apis.Drive.v3.FilesResource;
namespace WebAPI.Exports
{
public class googleSheetExport
{
private GoogleDriveHelper googleDriveHelper;
private SpreadsheetsResource.ValuesResource googleSheetValues;
public googleSheetExport(GoogleDriveHelper _googleDriveHelper, SpreadsheetsResource.ValuesResource _googleSheetValues)
{
googleDriveHelper = _googleDriveHelper;
googleSheetValues = _googleSheetValues;
}
public void export(Layer layer)
{
try
{
List<IList<object>> data = new List<IList<object>>() { new List<object>() { layer.Name!, layer.Number! } };
foreach (Record record in layer.Records!)
{
data.Add(new List<object> { record.Code!, record.Value });
}
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = $"export-{DateTime.Now}";
body.MimeType = "application/vnd.google-apps.spreadsheet";
body.Parents = new List<string> { "1c5GBQmsIoj6a9L-JYFTaLEZ3EfkbQHPt" };
CreateRequest request = googleDriveHelper.Service.Files.Create(body);
var file = request.Execute();
string sheetId = file.Id;
var range = $"Sheet1!A1:B${data.Count}";
ValueRange valueRange = new ValueRange() { Values = data};
var updateRequest = googleSheetValues.Update(valueRange, sheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
updateRequest.Execute();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

View File

@@ -1,39 +1,39 @@
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
namespace WebAPI
{
public class GoogleDriveHelper
{
public DriveService Service { get; set; }
const string APPLICATION_NAME = "Diuna";
static readonly string[] Scopes = { DriveService.Scope.Drive };
public GoogleDriveHelper()
{
InitializeService();
}
private void InitializeService()
{
var credential = GetCredentialsFromFile();
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = APPLICATION_NAME
});
}
private GoogleCredential GetCredentialsFromFile()
{
string fileName = "client_secrets.json";
#if DEBUG
fileName = "client_secrets.Development.json";
#endif
GoogleCredential credential;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
return credential;
}
}
}
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
namespace WebAPI
{
public class GoogleDriveHelper
{
public DriveService Service { get; set; }
const string APPLICATION_NAME = "Diuna";
static readonly string[] Scopes = { DriveService.Scope.Drive };
public GoogleDriveHelper()
{
InitializeService();
}
private void InitializeService()
{
var credential = GetCredentialsFromFile();
Service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = APPLICATION_NAME
});
}
private GoogleCredential GetCredentialsFromFile()
{
string fileName = "client_secrets.json";
#if DEBUG
fileName = "client_secrets.Development.json";
#endif
GoogleCredential credential;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
return credential;
}
}
}

View File

@@ -1,39 +1,39 @@
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
namespace WebAPI
{
public class GoogleSheetsHelper
{
public SheetsService Service { get; set; }
const string APPLICATION_NAME = "Diuna";
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
public GoogleSheetsHelper()
{
InitializeService();
}
private void InitializeService()
{
var credential = GetCredentialsFromFile();
Service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = APPLICATION_NAME
});
}
private GoogleCredential GetCredentialsFromFile()
{
string fileName = "client_secrets.json";
#if DEBUG
fileName = "client_secrets.Development.json";
#endif
GoogleCredential credential;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
return credential;
}
}
}
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
namespace WebAPI
{
public class GoogleSheetsHelper
{
public SheetsService Service { get; set; }
const string APPLICATION_NAME = "Diuna";
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
public GoogleSheetsHelper()
{
InitializeService();
}
private void InitializeService()
{
var credential = GetCredentialsFromFile();
Service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = APPLICATION_NAME
});
}
private GoogleCredential GetCredentialsFromFile()
{
string fileName = "client_secrets.json";
#if DEBUG
fileName = "client_secrets.Development.json";
#endif
GoogleCredential credential;
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
return credential;
}
}
}

View File

@@ -1,51 +1,51 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221205190148_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221205190148_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,36 +1,36 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserName = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -1,192 +1,192 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221211210507_DataSetsAndDataRows")]
partial class DataSetsAndDataRows
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("MPK")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Number")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId");
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221211210507_DataSetsAndDataRows")]
partial class DataSetsAndDataRows
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("MPK")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("Number")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId");
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,121 +1,121 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class DataSetsAndDataRows : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DataSets",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Number = table.Column<string>(type: "nvarchar(max)", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSets", x => x.Id);
table.ForeignKey(
name: "FK_DataSets_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataSets_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "DataRows",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
MPK = table.Column<string>(type: "nvarchar(max)", nullable: false),
Value = table.Column<float>(type: "real", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
DataSetId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataRows", x => x.Id);
table.ForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
column: x => x.DataSetId,
principalTable: "DataSets",
principalColumn: "Id");
table.ForeignKey(
name: "FK_DataRows_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_DataRows_CreatedById",
table: "DataRows",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataRows_DataSetId",
table: "DataRows",
column: "DataSetId");
migrationBuilder.CreateIndex(
name: "IX_DataRows_ModifiedById",
table: "DataRows",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_CreatedById",
table: "DataSets",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_ModifiedById",
table: "DataSets",
column: "ModifiedById");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataRows");
migrationBuilder.DropTable(
name: "DataSets");
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class DataSetsAndDataRows : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DataSets",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Number = table.Column<string>(type: "nvarchar(max)", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSets", x => x.Id);
table.ForeignKey(
name: "FK_DataSets_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataSets_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "DataRows",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
MPK = table.Column<string>(type: "nvarchar(max)", nullable: false),
Value = table.Column<float>(type: "real", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
DataSetId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_DataRows", x => x.Id);
table.ForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
column: x => x.DataSetId,
principalTable: "DataSets",
principalColumn: "Id");
table.ForeignKey(
name: "FK_DataRows_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_DataRows_CreatedById",
table: "DataRows",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataRows_DataSetId",
table: "DataRows",
column: "DataSetId");
migrationBuilder.CreateIndex(
name: "IX_DataRows_ModifiedById",
table: "DataRows",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_CreatedById",
table: "DataSets",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_ModifiedById",
table: "DataSets",
column: "ModifiedById");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataRows");
migrationBuilder.DropTable(
name: "DataSets");
}
}
}

View File

@@ -1,197 +1,197 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221219163620_RenameFields")]
partial class RenameFields
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId");
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221219163620_RenameFields")]
partial class RenameFields
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId");
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,73 +1,73 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class RenameFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "MPK",
table: "DataRows",
newName: "Code");
migrationBuilder.AlterColumn<int>(
name: "Number",
table: "DataSets",
type: "int",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(max)");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AddColumn<string>(
name: "Source",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Source",
table: "DataSets");
migrationBuilder.RenameColumn(
name: "Code",
table: "DataRows",
newName: "MPK");
migrationBuilder.AlterColumn<string>(
name: "Number",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "DataSets",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)");
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class RenameFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "MPK",
table: "DataRows",
newName: "Code");
migrationBuilder.AlterColumn<int>(
name: "Number",
table: "DataSets",
type: "int",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(max)");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
defaultValue: "",
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AddColumn<string>(
name: "Source",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Source",
table: "DataSets");
migrationBuilder.RenameColumn(
name: "Code",
table: "DataRows",
newName: "MPK");
migrationBuilder.AlterColumn<string>(
name: "Number",
table: "DataSets",
type: "nvarchar(max)",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "DataSets",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)");
}
}
}

View File

@@ -1,199 +1,199 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221221165749_DataSetIdOnDataRow")]
partial class DataSetIdOnDataRow
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221221165749_DataSetIdOnDataRow")]
partial class DataSetIdOnDataRow
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,60 +1,60 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class DataSetIdOnDataRow : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),
oldClrType: typeof(Guid),
oldType: "uniqueidentifier",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: true,
oldClrType: typeof(Guid),
oldType: "uniqueidentifier");
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id");
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class DataSetIdOnDataRow : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),
oldClrType: typeof(Guid),
oldType: "uniqueidentifier",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: true,
oldClrType: typeof(Guid),
oldType: "uniqueidentifier");
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id");
}
}
}

View File

@@ -1,199 +1,199 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20230106095427_RenameModels")]
partial class RenameModels
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("Layers");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("LayerId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("LayerId");
b.HasIndex("ModifiedById");
b.ToTable("Records");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.Layer", null)
.WithMany("Records")
.HasForeignKey("LayerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Navigation("Records");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20230106095427_RenameModels")]
partial class RenameModels
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("Layers");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("LayerId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("LayerId");
b.HasIndex("ModifiedById");
b.ToTable("Records");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.Layer", null)
.WithMany("Records")
.HasForeignKey("LayerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Navigation("Records");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,227 +1,227 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class RenameModels : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataRows");
migrationBuilder.DropTable(
name: "DataSets");
migrationBuilder.CreateTable(
name: "Layers",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Number = table.Column<int>(type: "int", nullable: false),
Source = table.Column<string>(type: "nvarchar(max)", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Layers", x => x.Id);
table.ForeignKey(
name: "FK_Layers_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Layers_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "Records",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Code = table.Column<string>(type: "nvarchar(max)", nullable: false),
Value = table.Column<float>(type: "real", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
LayerId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Records", x => x.Id);
table.ForeignKey(
name: "FK_Records_Layers_LayerId",
column: x => x.LayerId,
principalTable: "Layers",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Records_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Records_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_Layers_CreatedById",
table: "Layers",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_Layers_ModifiedById",
table: "Layers",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_Records_CreatedById",
table: "Records",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_Records_LayerId",
table: "Records",
column: "LayerId");
migrationBuilder.CreateIndex(
name: "IX_Records_ModifiedById",
table: "Records",
column: "ModifiedById");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Records");
migrationBuilder.DropTable(
name: "Layers");
migrationBuilder.CreateTable(
name: "DataSets",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Number = table.Column<int>(type: "int", nullable: false),
Source = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSets", x => x.Id);
table.ForeignKey(
name: "FK_DataSets_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataSets_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "DataRows",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Code = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
DataSetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
Value = table.Column<float>(type: "real", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataRows", x => x.Id);
table.ForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
column: x => x.DataSetId,
principalTable: "DataSets",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_DataRows_CreatedById",
table: "DataRows",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataRows_DataSetId",
table: "DataRows",
column: "DataSetId");
migrationBuilder.CreateIndex(
name: "IX_DataRows_ModifiedById",
table: "DataRows",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_CreatedById",
table: "DataSets",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_ModifiedById",
table: "DataSets",
column: "ModifiedById");
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class RenameModels : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataRows");
migrationBuilder.DropTable(
name: "DataSets");
migrationBuilder.CreateTable(
name: "Layers",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Number = table.Column<int>(type: "int", nullable: false),
Source = table.Column<string>(type: "nvarchar(max)", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Layers", x => x.Id);
table.ForeignKey(
name: "FK_Layers_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Layers_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "Records",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Code = table.Column<string>(type: "nvarchar(max)", nullable: false),
Value = table.Column<float>(type: "real", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
LayerId = table.Column<Guid>(type: "uniqueidentifier", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Records", x => x.Id);
table.ForeignKey(
name: "FK_Records_Layers_LayerId",
column: x => x.LayerId,
principalTable: "Layers",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Records_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_Records_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_Layers_CreatedById",
table: "Layers",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_Layers_ModifiedById",
table: "Layers",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_Records_CreatedById",
table: "Records",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_Records_LayerId",
table: "Records",
column: "LayerId");
migrationBuilder.CreateIndex(
name: "IX_Records_ModifiedById",
table: "Records",
column: "ModifiedById");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Records");
migrationBuilder.DropTable(
name: "Layers");
migrationBuilder.CreateTable(
name: "DataSets",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Number = table.Column<int>(type: "int", nullable: false),
Source = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataSets", x => x.Id);
table.ForeignKey(
name: "FK_DataSets_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataSets_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateTable(
name: "DataRows",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CreatedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
ModifiedById = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Code = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
DataSetId = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Desc1 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc2 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc3 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc4 = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desc5 = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
ModifiedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
Value = table.Column<float>(type: "real", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataRows", x => x.Id);
table.ForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
column: x => x.DataSetId,
principalTable: "DataSets",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
table.ForeignKey(
name: "FK_DataRows_Users_ModifiedById",
column: x => x.ModifiedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.NoAction);
});
migrationBuilder.CreateIndex(
name: "IX_DataRows_CreatedById",
table: "DataRows",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataRows_DataSetId",
table: "DataRows",
column: "DataSetId");
migrationBuilder.CreateIndex(
name: "IX_DataRows_ModifiedById",
table: "DataRows",
column: "ModifiedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_CreatedById",
table: "DataSets",
column: "CreatedById");
migrationBuilder.CreateIndex(
name: "IX_DataSets_ModifiedById",
table: "DataSets",
column: "ModifiedById");
}
}
}

View File

@@ -1,196 +1,196 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("Layers");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("LayerId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("LayerId");
b.HasIndex("ModifiedById");
b.ToTable("Records");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.Layer", null)
.WithMany("Records")
.HasForeignKey("LayerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Navigation("Records");
});
#pragma warning restore 612, 618
}
}
}
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
partial class AppDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("Layers");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<Guid>("LayerId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("LayerId");
b.HasIndex("ModifiedById");
b.ToTable("Records");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Record", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.Layer", null)
.WithMany("Records")
.HasForeignKey("LayerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.Layer", b =>
{
b.Navigation("Records");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,33 +1,33 @@
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class Layer
{
#region Properties
[Key]
public Guid Id { get; set; }
[Required]
public int? Number { get; set; }
[Required]
public string? Source { get; set; }
[Required]
public string? Name { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public DateTime ModifiedAt { get; set; }
[Required]
public bool IsDeleted { get; set; }
#endregion
#region Relations
public ICollection<Record>? Records { get; set; }
[Required]
public Guid CreatedById { get; set; }
public User? CreatedBy { get; set; }
[Required]
public Guid ModifiedById { get; set; }
public User? ModifiedBy { get; set; }
#endregion
}
}
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class Layer
{
#region Properties
[Key]
public Guid Id { get; set; }
[Required]
public int? Number { get; set; }
[Required]
public string? Source { get; set; }
[Required]
public string? Name { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public DateTime ModifiedAt { get; set; }
[Required]
public bool IsDeleted { get; set; }
#endregion
#region Relations
public ICollection<Record>? Records { get; set; }
[Required]
public Guid CreatedById { get; set; }
public User? CreatedBy { get; set; }
[Required]
public Guid ModifiedById { get; set; }
public User? ModifiedBy { get; set; }
#endregion
}
}

View File

@@ -1,34 +1,34 @@
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class Record
{
#region Properties
[Key]
public Guid Id { get; set; }
[Required]
public string? Code { get; set; }
[Required]
public float Value { get; set; }
//Description fields
public string? Desc1 { get; set; }
public string? Desc2 { get; set; }
public string? Desc3 { get; set; }
public string? Desc4 { get; set; }
public string? Desc5 { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ModifiedAt { get; set; }
public bool IsDeleted { get; set; }
#endregion
#region Relations
[Required]
public Guid CreatedById { get; set; }
public User? CreatedBy { get; set; }
[Required]
public Guid ModifiedById { get; set; }
public User? ModifiedBy { get; set; }
public Guid LayerId { get; set; }
#endregion
}
}
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class Record
{
#region Properties
[Key]
public Guid Id { get; set; }
[Required]
public string? Code { get; set; }
[Required]
public float Value { get; set; }
//Description fields
public string? Desc1 { get; set; }
public string? Desc2 { get; set; }
public string? Desc3 { get; set; }
public string? Desc4 { get; set; }
public string? Desc5 { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ModifiedAt { get; set; }
public bool IsDeleted { get; set; }
#endregion
#region Relations
[Required]
public Guid CreatedById { get; set; }
public User? CreatedBy { get; set; }
[Required]
public Guid ModifiedById { get; set; }
public User? ModifiedBy { get; set; }
public Guid LayerId { get; set; }
#endregion
}
}

View File

@@ -1,16 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class User
{
#region Properties
[Key]
public Guid Id { get; set; }
public string? Email { get; set; }
[StringLength(50)]
public string? UserName { get; set; }
public DateTime CreatedAt { get; set; }
#endregion
}
}
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class User
{
#region Properties
[Key]
public Guid Id { get; set; }
public string? Email { get; set; }
[StringLength(50)]
public string? UserName { get; set; }
public DateTime CreatedAt { get; set; }
#endregion
}
}

View File

@@ -1,87 +1,87 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WebAPI;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SQLDatabase");
builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlServer(connectionString));
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
builder.WithOrigins("https://diuna.bim-it.pl")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllers();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Secret"]))
};
});
builder.Services.AddAuthorization();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton(typeof(GoogleSheetsHelper));
builder.Services.AddSingleton(typeof(GoogleDriveHelper));
var app = builder.Build();
app.Use(async (context, next) =>
{
string token = context.Request.Headers["Authorization"].ToString();
if (token.Length > 0) {
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token.Split(' ')[1]);
context.Request.Headers.Add("UserId", new Microsoft.Extensions.Primitives.StringValues(data.Subject));
}
await next(context);
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// app.UseHttpsRedirection();
app.UseCors("CORSPolicy");
app.UseAuthorization();
app.UseAuthorization();
app.MapControllers();
app.Run();
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WebAPI;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SQLDatabase");
builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlServer(connectionString));
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
builder.WithOrigins("https://diuna.bim-it.pl")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllers();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Secret"]))
};
});
builder.Services.AddAuthorization();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton(typeof(GoogleSheetsHelper));
builder.Services.AddSingleton(typeof(GoogleDriveHelper));
var app = builder.Build();
app.Use(async (context, next) =>
{
string token = context.Request.Headers["Authorization"].ToString();
if (token.Length > 0) {
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token.Split(' ')[1]);
context.Request.Headers.Add("UserId", new Microsoft.Extensions.Primitives.StringValues(data.Subject));
}
await next(context);
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// app.UseHttpsRedirection();
app.UseCors("CORSPolicy");
app.UseAuthorization();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@@ -1,31 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12241",
"sslPort": 44358
}
},
"profiles": {
"WebAPI": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7009;http://localhost:5183",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12241",
"sslPort": 44358
}
},
"profiles": {
"WebAPI": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7009;http://localhost:5183",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -1,23 +1,23 @@
{
"PONG": "Development",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLDatabase": "Server=tcp:127.0.0.1,1433;Initial Catalog=diuna;Persist Security Info=False;User ID=SA;Password=v](8Lc|RfG;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;"
},
"GoogleClientId": "107631825312-bkfe438ehr9k9ecb2h76g802tj6advma.apps.googleusercontent.com",
"Secret": "8393AF8EAEF8478CB738D44858690F9C7E2D19F65896DD9FBAA3EB2A6F493E80",
"apiKey": "9ecb2h76g802tF65896DD9FBAA3EB2A6F493",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5400"
}
}
}
}
{
"PONG": "Development",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLDatabase": "Server=tcp:127.0.0.1,1433;Initial Catalog=diuna;Persist Security Info=False;User ID=SA;Password=v](8Lc|RfG;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;"
},
"GoogleClientId": "107631825312-bkfe438ehr9k9ecb2h76g802tj6advma.apps.googleusercontent.com",
"Secret": "8393AF8EAEF8478CB738D44858690F9C7E2D19F65896DD9FBAA3EB2A6F493E80",
"apiKey": "9ecb2h76g802tF65896DD9FBAA3EB2A6F493",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:5400"
}
}
}
}

View File

@@ -1,23 +1,23 @@
{
"PONG": "#{PING}#",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLDatabase": "#{db-connection-string}#"
},
"GoogleClientId": "#{google-backend-login-client-id}#",
"Secret": "#{google-backend-login-secret}#",
"apiKey": "#{api-key}#",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "#{api-local-url}#"
}
}
}
}
{
"PONG": "#{PING}#",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"SQLDatabase": "#{db-connection-string}#"
},
"GoogleClientId": "#{google-backend-login-client-id}#",
"Secret": "#{google-backend-login-secret}#",
"apiKey": "#{api-key}#",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "#{api-local-url}#"
}
}
}
}

View File

@@ -1,53 +1,53 @@
using CsvHelper;
using CsvHelper.Configuration;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Formats.Asn1;
using System.Globalization;
using System.Text;
using WebAPI.Models;
namespace WebAPI.dataParsers
{
public class csvParser
{
public List<Record> parse(IFormFile file)
{
var info = CultureInfo.CurrentCulture;
List<Record> records = new List<Record>();
var stream = new StreamReader(file.OpenReadStream());
string content = stream.ReadToEnd();
List<string> lines = content.Split("\n").ToList();
List<List<string>> data = new List<List<string>>();
foreach (string line in lines)
{
data.Add(line.Split(";").ToList());
}
for (int i = 1; i < data[0].Count; i++)
{
for (int j = 1; j < data.Count; j++) {
if (data[j][0].Length > 0)
{
float value = float.Parse(data[j][i], CultureInfo.GetCultureInfo("pl-PL"));
if (value > 0)
{
Record record = new Record();
record.Id = Guid.NewGuid();
record.Code = data[0][i];
record.Desc1 = data[j][0];
record.Value = value;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedAt= DateTime.UtcNow;
records.Add(record);
}
}
};
}
return records;
}
}
}
using CsvHelper;
using CsvHelper.Configuration;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Formats.Asn1;
using System.Globalization;
using System.Text;
using WebAPI.Models;
namespace WebAPI.dataParsers
{
public class csvParser
{
public List<Record> parse(IFormFile file)
{
var info = CultureInfo.CurrentCulture;
List<Record> records = new List<Record>();
var stream = new StreamReader(file.OpenReadStream());
string content = stream.ReadToEnd();
List<string> lines = content.Split("\n").ToList();
List<List<string>> data = new List<List<string>>();
foreach (string line in lines)
{
data.Add(line.Split(";").ToList());
}
for (int i = 1; i < data[0].Count; i++)
{
for (int j = 1; j < data.Count; j++) {
if (data[j][0].Length > 0)
{
float value = float.Parse(data[j][i], CultureInfo.GetCultureInfo("pl-PL"));
if (value > 0)
{
Record record = new Record();
record.Id = Guid.NewGuid();
record.Code = data[0][i];
record.Desc1 = data[j][0];
record.Value = value;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedAt= DateTime.UtcNow;
records.Add(record);
}
}
};
}
return records;
}
}
}

View File

@@ -1,49 +1,49 @@
using Google.Apis.Sheets.v4;
using System.Globalization;
using WebAPI.Models;
namespace WebAPI.dataParsers
{
public class googleSheetParser
{
private SpreadsheetsResource.ValuesResource googleSheetValues;
public googleSheetParser(SpreadsheetsResource.ValuesResource _googleSheetValues)
{
googleSheetValues = _googleSheetValues;
}
public dynamic parse(string sheetId)
{
var range = "Arkusz1!A:B";
var request = googleSheetValues.Get(sheetId, range);
var response = request.Execute();
var data = response.Values;
List<Record> records = new List<Record>();
string date = (string)data[0][0];
for (int i = 1; i < data.Count; i++)
{
float value = float.Parse(data[i][1].ToString(), CultureInfo.GetCultureInfo("pl-PL"));
if (value > 0)
{
Record record = new Record();
record.Id = Guid.NewGuid();
record.Code = data[i][0].ToString();
record.Value = value;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedAt = DateTime.UtcNow;
records.Add(record);
}
}
return new
{
records = records,
date = date
};
}
}
}
using Google.Apis.Sheets.v4;
using System.Globalization;
using WebAPI.Models;
namespace WebAPI.dataParsers
{
public class googleSheetParser
{
private SpreadsheetsResource.ValuesResource googleSheetValues;
public googleSheetParser(SpreadsheetsResource.ValuesResource _googleSheetValues)
{
googleSheetValues = _googleSheetValues;
}
public dynamic parse(string sheetId)
{
var range = "Arkusz1!A:B";
var request = googleSheetValues.Get(sheetId, range);
var response = request.Execute();
var data = response.Values;
List<Record> records = new List<Record>();
string date = (string)data[0][0];
for (int i = 1; i < data.Count; i++)
{
float value = float.Parse(data[i][1].ToString(), CultureInfo.GetCultureInfo("pl-PL"));
if (value > 0)
{
Record record = new Record();
record.Id = Guid.NewGuid();
record.Code = data[i][0].ToString();
record.Value = value;
record.CreatedAt = DateTime.UtcNow;
record.ModifiedAt = DateTime.UtcNow;
records.Add(record);
}
}
return new
{
records = records,
date = date
};
}
}
}

View File

@@ -1,79 +1,79 @@
# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4
trigger:
- deploy
pool:
vmImage: 'ubuntu-latest'
variables:
buildConfiguration: 'Release'
targetRuntime: 'linux-x64'
selfContained: false
dotNetFramework: 'net7.0'
dotNetVersion: '7.0.x'
buildId: $(Build.BuildNumber)
steps:
# Start: Build WebAPI
- task: UseDotNet@2
inputs:
version: $(dotNetVersion)
- script: dotnet build --configuration $(buildConfiguration) "WebAPI/DiunaBI-WebAPI.csproj"
displayName: 'Build .NET 6 Application'
- task: DotNetCoreCLI@2
displayName: 'dotnet publish $(buildConfiguration)'
inputs:
command: publish
publishWebProjects: True
arguments: '--configuration $(BuildConfiguration) --framework $(dotNetFramework) --runtime $(targetRuntime) --self-contained $(selfContained) --output $(Build.ArtifactStagingDirectory)'
workingDirectory: 'WebAPI'
zipAfterPublish: False
- task: DeleteFiles@1
inputs:
SourceFolder: '$(Build.ArtifactStagingDirectory)/WebAPI'
Contents: |
appsettings.Development.json
client_secrets.Development.json
# End: Build WebAPI
# Start: Build Frontend
- task: NodeTool@0
inputs:
versionSpec: '14.x'
displayName: 'Install Node.js'
- script: |
npm install -g @angular/cli
npm install
ng build --configuration production
workingDirectory: 'Frontend'
displayName: 'npm install and build'
- task: CopyFiles@2
inputs:
SourceFolder: '$(Build.Repository.LocalPath)/Frontend/dist/diunaBI'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/Frontend'
- task: replacetokens@5
inputs:
rootDirectory: '$(Build.ArtifactStagingDirectory)/Frontend'
targetFiles: '**/*.js'
encoding: 'auto'
tokenPattern: 'default'
writeBOM: true
actionOnMissing: 'warn'
keepToken: true
actionOnNoFiles: 'warn'
enableTransforms: false
enableRecursion: false
useLegacyPattern: false
enableTelemetry: true
# End: Build Frontend
# Publish results
- task: PublishBuildArtifacts@1
displayName: 'publish artifacts'
inputs:
pathtoPublish: '$(Build.ArtifactStagingDirectory)'
# ASP.NET
# Build and test ASP.NET projects.
# Add steps that publish symbols, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4
trigger:
- deploy
pool:
vmImage: 'ubuntu-latest'
variables:
buildConfiguration: 'Release'
targetRuntime: 'linux-x64'
selfContained: false
dotNetFramework: 'net7.0'
dotNetVersion: '7.0.x'
buildId: $(Build.BuildNumber)
steps:
# Start: Build WebAPI
- task: UseDotNet@2
inputs:
version: $(dotNetVersion)
- script: dotnet build --configuration $(buildConfiguration) "WebAPI/DiunaBI-WebAPI.csproj"
displayName: 'Build .NET 6 Application'
- task: DotNetCoreCLI@2
displayName: 'dotnet publish $(buildConfiguration)'
inputs:
command: publish
publishWebProjects: True
arguments: '--configuration $(BuildConfiguration) --framework $(dotNetFramework) --runtime $(targetRuntime) --self-contained $(selfContained) --output $(Build.ArtifactStagingDirectory)'
workingDirectory: 'WebAPI'
zipAfterPublish: False
- task: DeleteFiles@1
inputs:
SourceFolder: '$(Build.ArtifactStagingDirectory)/WebAPI'
Contents: |
appsettings.Development.json
client_secrets.Development.json
# End: Build WebAPI
# Start: Build Frontend
- task: NodeTool@0
inputs:
versionSpec: '14.x'
displayName: 'Install Node.js'
- script: |
npm install -g @angular/cli
npm install
ng build --configuration production
workingDirectory: 'Frontend'
displayName: 'npm install and build'
- task: CopyFiles@2
inputs:
SourceFolder: '$(Build.Repository.LocalPath)/Frontend/dist/diunaBI'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/Frontend'
- task: replacetokens@5
inputs:
rootDirectory: '$(Build.ArtifactStagingDirectory)/Frontend'
targetFiles: '**/*.js'
encoding: 'auto'
tokenPattern: 'default'
writeBOM: true
actionOnMissing: 'warn'
keepToken: true
actionOnNoFiles: 'warn'
enableTransforms: false
enableRecursion: false
useLegacyPattern: false
enableTelemetry: true
# End: Build Frontend
# Publish results
- task: PublishBuildArtifacts@1
displayName: 'publish artifacts'
inputs:
pathtoPublish: '$(Build.ArtifactStagingDirectory)'

View File

@@ -1,11 +1,11 @@
version: "3.9"
services:
db:
container_name: "DIUNA-MSSQL-2022"
image: "mcr.microsoft.com/mssql/server:2022-latest"
ports:
- "1433:1433"
environment:
SA_PASSWORD: "v](8Lc|RfG"
ACCEPT_EULA: "Y"
version: "3.9"
services:
db:
container_name: "DIUNA-MSSQL-2022"
image: "mcr.microsoft.com/mssql/server:2022-latest"
ports:
- "1433:1433"
environment:
SA_PASSWORD: "v](8Lc|RfG"
ACCEPT_EULA: "Y"
MSSQL_PID: "Express"