first commit

This commit is contained in:
Mohaimen Hasan 2026-11-03 13:06:00 +06:00
commit 838b8d4480
8554 changed files with 3379216 additions and 0 deletions

764
.gitignore vendored Normal file
View File

@ -0,0 +1,764 @@
# Created by https://www.toptal.com/developers/gitignore/api/csharp,angular,aspnetcore,visualstudio,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,angular,aspnetcore,visualstudio,visualstudiocode
### Angular ###
## Angular ##
# compiled output
dist/
tmp/
app/**/*.js
app/**/*.js.map
# dependencies
node_modules/
bower_components/
bin/
obj/
# IDEs and editors
.idea/
# misc
.sass-cache/
connect.lock/
coverage/
libpeerconnection.log/
npm-debug.log
testem.log
typings/
.angular/
# e2e
e2e/*.js
e2e/*.map
# System Files
.DS_Store/
### ASPNETCore ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
# 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
# TODO: 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
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable 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
# 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
# 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
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# 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/
# JetBrains Rider
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/
### Csharp ###
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
mono_crash.*
# Build results
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
# NUnit
nunit-*.xml
# Build Results of an ATL Project
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_h.h
*.iobj
*.ipdb
*_wpftmp.csproj
*.tlog
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# 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
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# 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
# NuGet Packages
# 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
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
# 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)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.ndf
# Business Intelligence projects
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
# 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/
# Visual Studio History (VSHistory) files
.vshistory/
# 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
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
### VisualStudioCode ###
!.vscode/*.code-snippets
# Local History for Visual Studio Code
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### VisualStudio ###
# User-specific files
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
# Build results
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
# MSTest test Results
# NUnit
# Build Results of an ATL Project
# Benchmark Results
# .NET Core
# ASP.NET Scaffolding
# StyleCop
# Files built by Visual Studio
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# AxoCover is a Code Coverage Tool
# Coverlet is a free, cross platform Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# 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
# NuGet Packages
# NuGet Symbol Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
# NuGet v3's project.json files produces more ignorable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
# Telerik's JustMock configuration file
# BizTalk build output
# OpenCover UI analysis results
# Azure Stream Analytics local run output
# MSBuild Binary and Structured Log
# NVidia Nsight GPU debugger configuration file
# MFractors (Xamarin productivity tool) working folder
# Local History for Visual Studio
# Visual Studio History (VSHistory) files
# BeatPulse healthcheck temp database
# Backup folder for Package Reference Convert tool in Visual Studio 2017
# Ionide (cross platform F# VS Code tools) working folder
# Fody - auto-generated XML schema
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
# JetBrains Rider
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/csharp,angular,aspnetcore,visualstudio,visualstudiocode
/HRM.UI/appsettings.json
/HRM.UI/appsettings.json
/HRM.UI/appsettings.json
/HRM.UI/appsettings.json
/HRM.UI/appsettings.json
# Employee photos written at runtime (approved thumbnails + photos awaiting approval).
# Not source; regenerated/repopulated by the app.
HRM.UI/EmployeePhotos/
HRM.UI/EmployeePhotoBulkUpload/
/HRM.UI/ClientApp/src/app/payroll/allowance-deduction/allowance-deduction-parameterization/allowance-deduction-parameterization-entry/allowance-deduction-parameterization-entry.component.css
/HRM.UI/ClientApp/src/app/payroll/allowance-deduction/allowance-deduction-parameterization/allowance-deduction-parameterization-entry/allowance-deduction-parameterization-entry.component.scss
/HRM.UI/ClientApp/src/app/payroll/allowance-deduction/allowance-deduction-parameterization/allowance-deduction-parameterization-entry/allowance-deduction-parameterization-entry.component.css

77
CEL.HRM.5.sln Normal file
View File

@ -0,0 +1,77 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34728.123
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.UI", "HRM.UI\HRM.UI.csproj", "{3E1F9D0F-BCE2-4E3B-8AE1-CD1775AF9044}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ease.Core", "Ease.Core\Ease.Core.csproj", "{BEFCAD7A-6B9C-4ADA-A620-E666B5C26407}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.DA", "HRM.DA\HRM.DA.csproj", "{928CCCDF-A39E-43A6-8776-4FEE90100074}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.BO", "HRM.BO\HRM.BO.csproj", "{26810BDB-91FA-42F0-91FE-6C273012D307}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.Report", "HRM.Report\HRM.Report.csproj", "{971FA68B-369A-41BB-BF43-20EE78DEBBDE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.AttendanceAutoProcess", "HRM.AttendanceAutoProcess\HRM.AttendanceAutoProcess.csproj", "{9D590FDC-DCBF-4EFA-BBAD-43501ECB6305}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HRM.MailNotificationProcess", "HRM.MailNotificationProcess\HRM.MailNotificationProcess.csproj", "{07405782-10D4-49A6-830B-FF011AC93327}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Erecruitment.UI", "Erecruitment.UI\Erecruitment.UI.csproj", "{C0DEA26B-7A77-4512-B0CB-D92A0C533CFC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseComparison", "DatabaseComparison\DatabaseComparison.csproj", "{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3E1F9D0F-BCE2-4E3B-8AE1-CD1775AF9044}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3E1F9D0F-BCE2-4E3B-8AE1-CD1775AF9044}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3E1F9D0F-BCE2-4E3B-8AE1-CD1775AF9044}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3E1F9D0F-BCE2-4E3B-8AE1-CD1775AF9044}.Release|Any CPU.Build.0 = Release|Any CPU
{BEFCAD7A-6B9C-4ADA-A620-E666B5C26407}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BEFCAD7A-6B9C-4ADA-A620-E666B5C26407}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BEFCAD7A-6B9C-4ADA-A620-E666B5C26407}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BEFCAD7A-6B9C-4ADA-A620-E666B5C26407}.Release|Any CPU.Build.0 = Release|Any CPU
{928CCCDF-A39E-43A6-8776-4FEE90100074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{928CCCDF-A39E-43A6-8776-4FEE90100074}.Debug|Any CPU.Build.0 = Debug|Any CPU
{928CCCDF-A39E-43A6-8776-4FEE90100074}.Release|Any CPU.ActiveCfg = Release|Any CPU
{928CCCDF-A39E-43A6-8776-4FEE90100074}.Release|Any CPU.Build.0 = Release|Any CPU
{26810BDB-91FA-42F0-91FE-6C273012D307}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{26810BDB-91FA-42F0-91FE-6C273012D307}.Debug|Any CPU.Build.0 = Debug|Any CPU
{26810BDB-91FA-42F0-91FE-6C273012D307}.Release|Any CPU.ActiveCfg = Release|Any CPU
{26810BDB-91FA-42F0-91FE-6C273012D307}.Release|Any CPU.Build.0 = Release|Any CPU
{971FA68B-369A-41BB-BF43-20EE78DEBBDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{971FA68B-369A-41BB-BF43-20EE78DEBBDE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{971FA68B-369A-41BB-BF43-20EE78DEBBDE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{971FA68B-369A-41BB-BF43-20EE78DEBBDE}.Release|Any CPU.Build.0 = Release|Any CPU
{9D590FDC-DCBF-4EFA-BBAD-43501ECB6305}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9D590FDC-DCBF-4EFA-BBAD-43501ECB6305}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9D590FDC-DCBF-4EFA-BBAD-43501ECB6305}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9D590FDC-DCBF-4EFA-BBAD-43501ECB6305}.Release|Any CPU.Build.0 = Release|Any CPU
{07405782-10D4-49A6-830B-FF011AC93327}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07405782-10D4-49A6-830B-FF011AC93327}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07405782-10D4-49A6-830B-FF011AC93327}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07405782-10D4-49A6-830B-FF011AC93327}.Release|Any CPU.Build.0 = Release|Any CPU
{C0DEA26B-7A77-4512-B0CB-D92A0C533CFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C0DEA26B-7A77-4512-B0CB-D92A0C533CFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C0DEA26B-7A77-4512-B0CB-D92A0C533CFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C0DEA26B-7A77-4512-B0CB-D92A0C533CFC}.Release|Any CPU.Build.0 = Release|Any CPU
{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5B2B9F46-8435-47E8-AE43-6DDA118BD830}
EndGlobalSection
GlobalSection(SubversionScc) = preSolution
Svn-Managed = True
Manager = AnkhSVN2019 - Subversion Support for Visual Studio
EndGlobalSection
EndGlobal

712
CLAUDE.md Normal file
View File

@ -0,0 +1,712 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Overview
CEL.HRM.5 is a large ASP.NET Core (net10.0) + Angular 22 HR Management System (payroll, attendance,
leave, recruitment, fund/PF management, learning management, grievance management, PMP/talent, final
settlement, etc.), plus a separate ERecruitment portal. It is a Windows/Visual Studio solution
(`CEL.HRM.5.sln`).
Three facts shape almost everything else: **there is no ORM**, **there is no migration framework**,
and **there are no automated tests**. Data access is hand-written ADO.NET with hand-built SQL strings,
schema changes ship as hand-authored `.sql` scripts run manually, and verification is build-based and
manual.
## Solution structure
| Project | Type | Purpose |
|---|---|---|
| `HRM.UI` | ASP.NET Core Web API + Angular SPA host | Main application. REST controllers under `Controllers/<Module>/`, Angular app in `ClientApp/`. |
| `Erecruitment.UI` | ASP.NET Core Web API + Angular SPA host | Separate e-recruitment portal (`ClientApp` project `Erecruitment_Angular`, output `dist`, dev port 44375). References `HRM.BO` + `HRM.DA`, same three-layer pattern. |
| `HRM.BO` | Class library | Business objects (deriving from `ObjectTemplate`) and service **interfaces** (`IEmployeeService`, …), organized by module. |
| `HRM.DA` | Class library | `DA/` = `internal static` raw-SQL builders; `Service/` = concrete `I*Service` implementations. |
| `Ease.Core` | Class library | The in-house framework everything sits on: `DataAccess/` (`TransactionContext`, `DataReader`, `SQLParser`/`MakeSQL`, `ConnectionFactory`, `DbConfig`, `NullHandler`), `Model/` (`ObjectTemplate`, `ServiceTemplate`, `ServiceException`), `Utility/`, `EnumHelper`. |
| `HRM.Report` | Class library | RDLC reporting (`ReportProcessor`, ~383 `.rdlc`; `HRM.UI/RDLC` holds ~104 more). Uses `BinaryFormatter`, hence `EnableUnsafeBinaryFormatterSerialization`. |
| `HRM.AttendanceAutoProcess` | Console exe | Scheduled attendance import job (single `Program.cs`). |
| `HRM.MailNotificationProcess` | WinForms exe (net10.0-windows) | Scheduled mail notification sender; SSH.NET for SFTP. |
| `DatabaseComparison` | Legacy WinForms exe (net461, non-SDK csproj) | Standalone DB schema diff tool, not part of the app runtime. |
Reference graph: `Ease.Core` ← `HRM.BO` ← `HRM.DA` ← `HRM.Report` ← `HRM.UI`.
Gotcha: `HRM.UI` and `Erecruitment.UI` *also* carry an old `Ease.NetCore` **NuGet** PackageReference
(v1.0.5, 2021) alongside the transitive `Ease.Core` **project** reference, and both DLLs ship to the
output folder. The live framework is the `Ease.Core` project in this repo — that is the one to edit and
read. But the NuGet is **not dead**: `AuthController` encrypts/decrypts every password with
`Ease.NetCore.Utility.Global.CipherFunctions`. Keep it pinned at 1.0.5 — a newer version that ciphered
differently would lock every user out.
### Package policy (since the .NET 10 upgrade)
Microsoft packages track the runtime (`10.0.x`). Three are deliberately held back or gone:
`Aspose.Words` stays at the version the client licence covers (a newer build than the subscription
allows silently drops to evaluation mode), `EPPlus` stays on 8.x (licensed), and **AutoMapper was
removed** — 10.1.1 had a high-severity advisory whose only fix is the commercial 15.x line, and nothing
called `IMapper`. Don't add it back; map by hand. EF Core, `Swashbuckle`, `Facebook` and
`Microsoft.Extensions.PlatformAbstractions` were removed too (never used). API versioning is
`Asp.Versioning.Mvc` (+ `.ApiExplorer`), the successor of `Microsoft.AspNetCore.Mvc.Versioning`.
`dotnet list CEL.HRM.5.sln package --vulnerable --include-transitive` was clean after the upgrade;
`System.Security.Cryptography.Pkcs/Xml` are pinned directly in `Ease.Core`/`HRM.BO` only to lift
vulnerable transitive versions.
There is a nested, separately-buildable `HRM.UI/Controllers/MobileAPI/HRMobileAPI.csproj` (legacy
mobile API) included only in the narrower `HRM.UI/HRM.UI.sln`. But the live mobile API is not that project:
`MobileAPI/Controllers/*.cs` (`api/Mobile/User`, `api/Mobile/Attendance`, …) are ASP.NET Core controllers
that `HRM.UI` itself compiles and serves — search that folder too when changing anything app-wide. Don't confuse that solution with the
root `CEL.HRM.5.sln`, which is the one for whole-solution work.
`HRM.UI/CLAUDE.md` is a second, frontend/backend-detailed file. Its architecture notes still hold,
but several specifics are stale — prefer *this* file wherever the two disagree. It claims `.git` lives
at `e:\HRMGIT\` alongside a sibling `IntegrationSuite` project (this checkout is a single
self-contained repo and no `IntegrationSuite` exists), lists `npm run lint` as a working command (it
is broken — see below), describes `Ease.Core` as "referenced as the `Ease.NetCore` NuGet package"
(the live one is the project in this repo), and counts "~250+" services (there are ~450 service classes, ~310 of them DI-registered).
## Build & run
```
dotnet restore CEL.HRM.5.sln
dotnet build CEL.HRM.5.sln
dotnet build HRM.UI/HRM.UI.csproj
dotnet run --project HRM.UI/HRM.UI.csproj
dotnet run --project Erecruitment.UI/Erecruitment.UI.csproj # the e-recruitment portal, :44375
```
`dotnet build` handles the whole solution including the net461 `DatabaseComparison` project;
Visual Studio/MSBuild is not required for it. Building `HRM.UI` alone pulls in BO/DA/Report/Ease.Core
and is the fast loop for backend work — `ClientApp/**` is excluded from the csproj, so a `dotnet build`
never runs the Angular build.
Expect the **solution build to fail on `Erecruitment.UI`** — every other project builds clean. It does
not compile on this branch, and did not on net8 either: `SurveyController` uses `SurveyEmployee` /
`SurveyResult` members that `HRM.BO` no longer has, and its DI file registers a `FinalSettlementService`
that does not exist. On a clean build it fails even earlier, on TypeScript: unlike `HRM.UI` it lacks
`<TypeScriptCompileBlocked>`, so `Microsoft.TypeScript.MSBuild` compiles `ClientApp` and fails without
`node_modules`.
Production servers need the **ASP.NET Core 10 Hosting Bundle** (IIS, `AspNetCoreModuleV2`, in-process)
before a net10 build is deployed to them.
Dev URLs: API on `https://localhost:44374` (`HRM.UI/Properties/launchSettings.json`); Angular dev
server on `http://localhost:4200`, which is the only origin the `"CORSPolicy"` CORS policy allows.
The normal full-stack loop is `dotnet run` from `HRM.UI` — in Development it proxies to `ng serve`
via `UseAngularCliServer`. Run `ng serve` standalone only for Angular-only iteration, with the
backend running separately.
Frontend (from `HRM.UI/ClientApp` or `Erecruitment.UI/ClientApp`):
```
npm install
npm start # ng serve, http://localhost:4200
npm run build # ng build -> dist/babylon (HRM.UI) | dist (Erecruitment.UI)
npm test # ng test (Karma, entry src/test.ts)
```
Both SPAs `ng serve` on 4200, so only one of the two can run at a time.
- `npm run lint` is **broken**: `angular.json` still points at the `@angular-devkit/build-angular:tslint`
builder (with a `tslint.json`), which no longer exists in Angular 19. There is no ESLint config.
- `npm test` works, but coverage is nominal — 18 `.spec.ts` files across the whole app. Single spec:
`ng test --include='**/some.component.spec.ts'`.
- There are no `*.Tests.csproj` anywhere in the solution.
### Production build/deploy (`HRM.UI`)
[`deploy.ps1`](deploy.ps1) does the whole thing: bumps `HRM.UI/ClientApp/src/version.json`
(`YYYYMMDD-NN`, counter auto-increments per day), runs `ng build --configuration production
--base-href <baseHref>`, `dotnet publish` for `win-x64`, copies `dist/babylon` into the publish
folder's `wwwroot`, and writes an Angular `web.config` (SPA rewrites + no-cache for
`index.html`/`version.json`). Edit `$baseHref`/`$outputFolder` at the top per client/environment
before running. `VersionCheckService` (`ClientApp/src/app/version-check.service.ts`) polls
`version.json` every 5 minutes and prompts a reload when the server version changes — keep the
version bump intact if you touch the script. The repo-root `publish/` folder is this script's output
(gitignored) — never hand-edit it. `HRM.UI/ClientApp/deploy.ps1` is a **deprecated** frontend-only
shim that just forwards to the root script; don't extend it.
## Architecture: BO → DA → Service → Controller
Every feature module mirrors the same folder name across `HRM.BO/`, `HRM.DA/DA/`, and
`HRM.DA/Service/` (e.g. `Employee/`, `Leave/`, `Fund/`, `Attendance/`).
1. **BO** — the entity (`class Employee : ObjectTemplate`) plus its service interface
(`IEmployeeService`). `ObjectTemplate` supplies `ID`, `IsNew` (`_id <= 0`), `SortOrder` and an
`ObjectState`; BOs are not plain POCOs.
2. **DA** (`HRM.DA/DA/<Module>/<Entity>DA.cs`) — `internal static` classes whose methods all take a
`TransactionContext` as first argument, build SQL via `SQLParser.MakeSQL(...)`, and return
`IDataReader`/`DataSet`/scalars. Never called from controllers.
3. **Service** (`HRM.DA/Service/<Module>/<Entity>Service.cs`) — `public class XService :
ServiceTemplate, IXService`. Owns the transaction, maps rows to BOs, and is what controllers get
via DI.
4. **Controller** (`HRM.UI/Controllers/<Module>/`) — `[ApiController]`, `[Route("api/<Module>")]`,
`[Authorize]`, constructor-injects a long list of `I*Service` interfaces and delegates. Almost no
logic. API versioning is configured (URL-segment) but routes are unversioned in practice.
All ~310 service registrations live in one file:
[HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs](HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs)
(`ConfigureBusinessServices`, almost all `AddTransient<IX, X>()`). Register new services there.
Note the asymmetry: **DI is used at the controller boundary only.** Inside `HRM.DA`, services
instantiate each other directly (`new LeaveService().Get(...)`, `new EmployeeService().Get(...)`),
so following the existing style means `new`-ing a sibling service, not injecting it.
### Mapping rows to objects
`ServiceTemplate` forces `protected override T CreateObject<T>(DataReader dr)`. The house style is a
private `MapObject(Entity, DataReader)` that `CreateObject` calls; lists come from the inherited
`CreateObjects<T>(dr)`, which also stamps `ObjectState.Saved` on each row.
### Canonical service method
Every public service method follows this shape — match it exactly:
```csharp
public int Save(LeaveEntry oLeaveEntry)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true); // true = start a DB transaction (writes)
Save(oLeaveEntry, tc);
tc.End(); // commit
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError(); // rollback
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return oLeaveEntry.ID;
}
```
`TransactionContext.Begin()` (no argument) is the read-only form used by every `Get*`. Services also
expose `Get(TransactionContext tc, ...)` overloads so callers can join an outer transaction.
### SQL is string interpolation, not parameterization
`SQLParser.MakeSQL` splices **literals** into the SQL text. Placeholders are positional and consume
arguments in order; a `null` argument becomes `NULL`:
| | meaning |
|---|---|
| `%n` | numeric literal (by far the most used — ~14.5k occurrences) |
| `%s` | string, single-quoted, `'` doubled |
| `%u` | same as `%s` but `N'...'` (unicode) |
| `%T` | same as `%s` |
| `%d` / `%t` / `%D` | date / time / datetime literal |
| `%b` | bit, emitted as `1`/`0` |
| `%q` | **raw, verbatim, unescaped** |
| `%%` | a literal `%` |
| `%{0}` | re-use the already-formatted argument at that ordinal |
`%q` (~1.5k occurrences) is the injection surface — it exists for things like comma-separated ID lists
in `IN (%q)` and for splicing fragments. Only ever pass values the code itself produced (joined ints,
a fixed column name); never a user-supplied string. Do not introduce `$"..."` interpolation or `+`
concatenation for SQL — use `MakeSQL`.
### Primary keys are application-generated
There are no IDENTITY columns in this schema. New IDs come from
`tc.GenerateID("TableName", "ColumnName")`, which is literally `SELECT MAX(col) FROM table` + 1
(optionally with a where-clause overload), executed inside the same transaction. When adding a table,
follow this — do not add an IDENTITY column, or the pattern breaks.
### Stored procedures
The escape hatch for heavy reporting queries. Used in ~12 DA files, e.g. in
[HRM.DA/DA/Attendance/DailyAttnProcessDA.cs](HRM.DA/DA/Attendance/DailyAttnProcessDA.cs):
```csharp
var p = new List<SqlParameter> {
SqlHelperExtension.CreateInParam("@FromDate", SqlDbType.Date, fromDate), ... };
return tc.ExecuteDataSet(CommandType.StoredProcedure, "usp_EmployeeAttendanceLeaveSummaryLM", p.ToArray());
```
These are properly parameterized. The proc body itself ships in the matching `_DB_Changes.sql`
script (see below) — for this one,
[db/Script/AttendanceLeaveSummaryLM_DB_Changes.sql](db/Script/AttendanceLeaveSummaryLM_DB_Changes.sql).
### Excel import/export
Three Excel libraries are referenced: `NPOI` (in `HRM.BO`), plus `ClosedXML` and `EPPlus` (both in
`HRM.DA`). Before adding a workbook feature, check which one the surrounding module already uses
instead of adding a fourth. The newest and largest workbook feature (Employee Bulk Upload, below)
uses **ClosedXML** for both writing and reading.
Every Excel interface in the app is served by the one
[DataUploadController](HRM.UI/Controllers/CommonInterface/DataUploadController.cs) (`api/dataUpload`)
— do not add a separate controller for a new uploader.
### Employee Bulk Upload
The whole information of many employees in one spreadsheet — one row per employee, carrying that
employee's children, spouse, education, nominee and experience in the same row. ~8,000 lines across
four files, and the pattern is worth following for any future uploader:
| Layer | File |
|---|---|
| Layout + DTOs + interface | [HRM.BO/EmployeeBulkUpload/EmployeeBulkUploadTemplate.cs](HRM.BO/EmployeeBulkUpload/EmployeeBulkUploadTemplate.cs) |
| Raw SQL | [HRM.DA/DA/EmployeeBulkUpload/EmployeeBulkUploadDA.cs](HRM.DA/DA/EmployeeBulkUpload/EmployeeBulkUploadDA.cs) |
| Generate / validate / save | [HRM.DA/Service/EmployeeBulkUpload/EmployeeBulkUploadService.cs](HRM.DA/Service/EmployeeBulkUpload/EmployeeBulkUploadService.cs) |
| Screen | `ClientApp/src/app/common-interface/employee-bulk-upload/` + `_services/common/employee-bulk-upload.service.ts` |
Four things shape it:
- **`EmployeeBulkUploadTemplate` is the single source of truth.** The static layout (groups →
sub-groups → columns, with each column's mandatory flag, kind, width, dropdown list and number
format) is declared once in BO. The downloadable `.xlsx` is **generated** from it on every request,
and validation reads the uploaded file against the same declaration — so the template and the rules
cannot drift apart. Add a column by appending it inside its sub-group, never by inserting in the
middle: the uploader matches by position and heading.
- **Validation is 8 ordered layers**, built in `ReadUpload`: Excel file → Sections and columns → Rows
→ Employee No and Name → Mandatory values → Data types → Employees → Master data. Every check of a
layer runs and is reported even when it passes (`Code`, `Title`, `Status`, `Message`, `Details`,
`Fix`); the next layer runs only once the previous one passed. Validation problems are returned in
the result, not thrown — only an unexpected failure throws.
- **Save is all-or-nothing**: `SaveUpload` re-validates every layer, then writes every row in ONE
transaction. An Employee No already in the current payroll type updates that employee (only the
cells the file fills); anything else creates a new one.
- **Missing master data can be added from the screen** (`AddMasterData`) — but through each master
table's own service `Save`, one record per transaction, so one failure does not undo the rest.
That is deliberately *not* part of the all-or-nothing save.
Six endpoints, all on `DataUploadController`: `employee-bulk-upload-layout`, `-template`, `-read`,
`-save`, `-add-master-data`, `-master-options/{masterData}/{payrollTypeId}`.
Gotcha: the screen has an Angular route (`/common-interface/employee-bulk-upload`) but **no `<Menu>`
node in any `*-Menu.xml`** — key `2.3.7` under Manage Employee › Interface went to "Historical Career
Data Upload" instead. So the page is reachable only by typing the URL until a menu node is added and
the XML re-uploaded (see the menu flow under *Auth and the current user*).
### Two later uploaders built on the same pattern
Both reuse the bulk-upload result types (`EmployeeBulkUploadLayer`, `EnumBulkUploadCheckStatus`), so
the screens report problems the same way. Neither has a `<Menu>` node yet either — URL only.
- **Salary Master Data Bulk Upload** (`/common-interface/salary-master-bulk-upload`; read-only grid at
`/payroll/salary-master-data-view`). Layout in `HRM.BO/Salary/SalaryMasterBulkUploadTemplate.cs`,
logic in `HRM.DA/Service/Salary/SalaryMasterBulkUploadService.cs`, rows saved to
`HistorySalaryMonthly` / `HistorySalaryMonthlyDetail` through `HistorySalaryMonthlyService`. The
workbook is per salary month (row 1 carries the month, checked against the month posted as the
`salaryMonth` form field). **7** layers, not 8, and layers 4–7 all run once layer 3 passes, so one
upload lists every problem of every row. A blank amount is saved as `NULL` — which needs
`HistorySalaryMonthlyAmountNull_DB_Changes.sql` run first. That script was deleted from the root in
`91369150c` (not archived): recover it with
`git show 91369150c^:HistorySalaryMonthlyAmountNull_DB_Changes.sql`. The service opens no transaction itself;
the save is `HistorySalaryMonthlyService`'s one all-or-nothing transaction.
- **Employee Profile Picture Bulk Upload** (second tab of the Employee Bulk Upload screen;
`HRM.DA/Service/EmployeeBulkUpload/EmployeePhotoBulkUploadService.cs`). No file upload: pictures are
copied by hand into `HRM.UI/EmployeePhotoBulkUpload/` on the server (gitignored), each named by
Employee No, and the screen reads that folder. Each picture is stored exactly as an approved ESS
profile-picture request stores it (`EssController.ApproveRequest`: `HREmployeeDA.uplaodFile` +
`EmployeePhotoService.GenerateThumbnail`). The save is all-or-nothing for the whole folder, and
because thousands of pictures take minutes it runs on `EmailLogBackgroundRunner` and the screen
polls `employee-photo-bulk-upload-run/{runId}`. Run state is **in memory** — an app restart loses
it. After a save the controller drops each changed employee's `LandingPageEmployee` cache entry.
### Calendar module
A Google-Calendar-like module (`/calendar/my-calendar`, `/calendar/my-tasks`) on just **two tables**,
`CalendarItem` and `CalendarItemAttendee` (schema: [db/Script/Calendar_DB_Changes.sql](db/Script/Calendar_DB_Changes.sql)):
- One `CalendarItem` table holds all three `ItemType`s: **Event** (1), **Task** (2) and **Schedule Job**
(3, HR only). A Schedule Job is a template: each run creates an ordinary Task, made unique by
`SourceItemID` + `SourceOccurrence`. Its Department targets stay as Department rows and are expanded
at every run. The job itself is never notified about or sent to Outlook.
- **Schedule Email** (`ItemType` 4, HR only, `Calendar.ScheduleEmailsEnabled`) is the same kind of template,
but each run sends an e-mail instead of creating a Task: `Title` is the subject, `Description` the body,
one optional file in `CalendarItemAttachment`. Each run claims a `CalendarEmailRun` row (unique per item +
run moment) and becomes one `MasterEmailLog` batch (`EnumEmailType.ScheduleEmail`, file on the batch
header like `GeneralMail`), sent by `CalendarJobs.SendScheduleEmail` through `IEmailDispatchService` — so
it shows, and is retried, in Mail Manager › Mail Log History. Body/subject tags (`<EMP-NAME>`,
`<DEPARTMENT>`, …) are listed and filled in one place, `HRM.DA/Service/Calendar/ScheduleEmailTags.cs`.
Schema: `ScheduleEmail_DB_Changes.sql` was deleted from the root once applied (commit `ac179c03e`)
and **not** archived in `db/Script/` — recover it with `git show 73f466cd0:ScheduleEmail_DB_Changes.sql`.
- The organizer is `CreatedBy` **and** an attendee row with `Role = Organizer`. Holidays, leave and
birthdays are read-only layers, read live from the existing tables (nothing is copied).
- Repeats are RFC 5545 RRULEs worked out with **Ical.Net** (`HRM.DA/Service/Calendar/CalendarRecurrence.cs`).
Times are stored as floating local times. `NextTriggerAt` is the next reminder (Event/Task) or the
next run (Schedule Job), and `CalendarItemDA.AdvanceTrigger` moves it optimistically, so only one
dispatcher can ever take a given reminder or run.
- **Outlook (ICS mode):** `CalendarJobs.SyncOutlook` mails a `text/calendar` REQUEST/CANCEL built by
`HRM.UI/BackgroundJobs/Calendar/CalendarIcsBuilder.cs`. The UID is stable per item, `SEQUENCE` is
`CalendarItem.OutlookSequence`, and per-person progress is `CalendarItemAttendee.InviteSentSequence`,
so a retry only sends what is missing. Bump `OutlookSequence` only when what the invitation shows
changes. In ICS mode, change notifications are bell-only (the invitation is the e-mail).
`OutlookSync = Graph` (Microsoft 365) is planned but not built.
- The controller only queues jobs (`NotifyChange`, `NotifyOrganizer`, `SyncOutlook`) after a successful
save, through `QueueJob`, which never turns a saved change into an error. All permission checks live
in `CalendarItemService`.
- Frontend: the dialogs (quick add, item editor, item detail, day dialog) and the small month calendar
(`<app-calendar-mini-scheduler>`, a hand-built grid, not the Kendo Scheduler) live in
`ClientApp/src/app/calendar/shared/` as `CalendarSharedModule`, imported by both `CalendarModule` and
`EssModule`. The ESS landing page and the self-service dashboard's drawer show the mini calendar and open
`<app-calendar-day-dialog>` from it (`dateSelected` / `itemSelected`). Change a dialog there once, not per
screen. The mini calendar deliberately leaves out the Leave, Attendance and Schedule Job layers; the older
dot calendar `<app-custom-calendar>` (`custom-components/`) is no longer used by any page.
### Cross-cutting: central email log
Bulk outbound mail — payslips, tax cards, tax certificates, anything sent to many employees at once —
goes through **`IEmailDispatchService`** (`HRM.DA/Service/Mail/EmailDispatchService.cs`), which writes
a `MasterEmailLog` row per send operation and a `MasterEmailLogDetails` row per recipient. Do not
call `MailSender` in a loop for a new bulk-mail feature; the whole point is that failures become
replayable instead of lost. (Single-recipient notifications — workflow, leave, loan — still use
`MailSender` directly, and are not logged.)
The contract:
- **Logged before sent.** `CreateBatch` writes the header and every recipient row (details via
`SqlBulkCopy`) *before* the first mail leaves, so nothing is lost if the run dies halfway.
- **One bad recipient never stops the run.** Missing address, a document that will not build, an SMTP
refusal — each is recorded on that recipient's own row and the loop carries on. `SendOne` never
throws.
- **`Skipped` ≠ `Failed`.** No/invalid e-mail address is `Skipped` (retrying is pointless — fix the
address); everything else is `Failed` and is what `RetryFailed` replays. Retry updates the same rows
in place and never creates a second batch.
- **Attachments are kept** (`MasterEmailLogDetails.AttachmentData`, switchable per batch via
`MasterEmailLog.PreserveAttachment`), which is what lets one retry screen replay *any* mail type
without knowing how that document is produced.
Adding a mail type is two things and nothing else: a member on `EnumEmailType`, and an
`EmailDispatchRequest.AttachmentResolver` that builds the document. The resolver has to live in
`HRM.UI` because `HRM.DA` cannot reference `HRM.Report` — see `SalaryController.sendPayslipForMultiple`
and `IncomeTaxController.SendTaxCardForMultiple` / `SendTaxCertificateForMultiple` for the pattern.
**Build the attachment with the same report call the matching report screen uses** (e.g. tax card =
`RptIncomeTax.ShowMultipleTaxCard`, the `EnumReportType.EssTaxCard` branch of
`ReportController.getCommonReportData`), so the mailed document and the downloaded one cannot drift.
The one exception is `EnumEmailType.GeneralMail` (free-text mail + one optional uploaded file, ≤ 10 MB),
sent from `EmailLogController.sendGeneralMail`. Every recipient gets the *same* file, so it is stored
**once on the batch header** (`MasterEmailLog.ParameterJson`, base64) with `PreserveAttachment = false`,
not copied onto each `MasterEmailLogDetails` row; retry (`BuildGeneralMailResolver`) and
`api/emailLog/downloadAttachment/{masterEmailLogId}/{detailId}` read it back from the header. Follow
that for any future "same file to everyone" mail type.
Batches run on a non-request thread (`HRM.UI/Helpers/EmailLogBackgroundRunner.cs`) and the endpoint
returns the new `masterEmailLogID` immediately; the browser follows the batch by polling
`api/emailLog/getLog/{id}`. Read side + generic retry: `api/emailLog`
(`Controllers/CommonInterface/EmailLogController.cs`).
Frontend: **`<app-master-mail-log>`** (`ClientApp/src/app/master-mail-log/`, its own
`MasterMailLogModule`) is the reusable view — history, live progress, per-recipient breakdown and
retry. Import the module, drop the tag in, and after starting a batch call `watchBatch(id)` on it via
`@ViewChild`. Inputs narrow it (`emailType`, `showTypeFilter`, `showProgress`, `showFilterBar`,
`showLogGrid`, `allowRetry`). Mail Manager (`/payroll/mail-manager`) is the worked example.
Two things to know before building on it:
- **There is no `_DB_Changes.sql` for these two tables anywhere in the repo** — the schema was applied
by hand and the script never committed. Any other client branch or fresh database will fail at
runtime until it is written and run. Treat that as outstanding work.
- `ProcessBatch` only refreshes the header's counters (and its status) when the run *ends*, so a batch
in flight reads `Pending` with `Sent/Failed/Skipped` still at `0`; `Processing` is in the enum but
effectively unused. The per-recipient rows are accurate throughout — it is the header that lags.
The UI compensates with a spinner, not with real numbers.
### Cross-cutting: approval workflow
Most "apply → approve" features (leave, attendance regularization, claims, requisitions) route through
`HRM.DA/Service/Workflow/` — `WorkFlowEng`, `WFMovementTran`, `WFSetup`, `WFType`,
`DelegateResponsibolity`. Before writing a new approval path, look at how an existing module drives
`WFMovementTran`.
## Auth and the current user
JWT bearer (HS512), signing key from `AppSettings.Secret` — always through
`Ease.Core.Utility.JwtSigningKey.FromSecret(...)`, both where tokens are issued (`AuthController`,
`SalaryController`, and the mobile login in `HRM.UI/Controllers/MobileAPI/Controllers/UserController.cs`)
and in `Startup`. Microsoft.IdentityModel 8 refuses an HS512 key under 64 bytes
(IDX10720) and the configured secrets are 40, so the helper stretches a short secret with SHA-512; a raw
`Encoding.ASCII.GetBytes(Secret)` anywhere breaks login. The token carries custom claims, unpacked
everywhere by `CurrentUser.GetCurrentUser(HttpContext.User)` ([HRM.BO/User/Users.cs](HRM.BO/User/Users.cs),
used in ~45 controllers):
`UserID`, `UserName`, `LoginID`, `UserType` (`EnumUserType`), `EmployeeID`, `PayrollTypeID`,
`nextPayProcessDate`, `taxParamId`, `hasDataPermission`.
Gotcha: `dbo.Users` e-mail columns differ **per database**: the older `Email`, and `EmailAddress`, which is
the one the Add/Edit User form writes (`UserEmailAddress_DB_Changes.sql`). Some databases have both, some only
one (the dev database has no `Email` at all), and naming a missing column fails the whole query — the
calendar's Users dropdown once came back silently empty for exactly this reason. Don't hard-code either
column: use the pattern in `CalendarItemDA.UserEmailExpression`, which checks `COL_LENGTH` once per process
and builds `COALESCE(EmailAddress, Email)` from whichever columns exist. Server-side SQL errors that the UI
swallows land in `HRM.UI/Log/Error.log` (`ExceptionLog`), the first place to look.
`PayrollTypeID` is the scoping key threaded through most payroll/attendance queries — when adding a
query that returns employee data, check whether existing siblings filter by it. Reading `EmployeeID`
throws for a self-service (`EnumUserType.Employee`) login that has none, so guard accordingly.
Authorization is **menu-driven, not route-driven**: the server builds the user's permitted menu tree
and the SPA stores it in `localStorage` as `menuList`; `AuthGuard.canActivate()` only checks that a
token exists. A hidden menu item does not mean a protected endpoint — put real checks in the API.
The menu itself is **data, not code**: it is defined in per-client XML files under
`ClientApp/src/assets/resource/` (`Menu.xml`, `Berger-Menu.xml`, `SGS-Menu.xml`, …). An admin uploads
one via Authentication > Configuration > Menu (`FileManagerController.uploadConfigurationfile`), which
stores its attributes in `dbo.ConfigurationAttribute` and syncs name/link/icon onto `dbo.RolePermission`
(matched by `PermissionCode`); `RoleService.GetRolePermissionbyUserID` builds the tree from those rows.
So adding a new screen means adding a `<Menu>` node to the relevant XML(s) and re-uploading it, not
just adding an Angular route. See
[db/Script/MenuIcon_DB_Changes.sql](db/Script/MenuIcon_DB_Changes.sql) for the full flow.
The same upload mechanism (`EnumConfigurationType`: `UI`, `Logic`, `Menu`) carries **per-client
business rules**: the `*LogicConfiguration.xml` files in that folder are uploaded as `Logic` and read
at runtime via `new SystemConfigarationService().GetconfigValue/GetconfigBooleanValue(
EnumConfigurationType.Logic, "<parent>", "<child>")` (~110 call sites, e.g. `"costcenter",
"manadatoryinsalary"`; note the class-name spelling, file `HRM.DA/Service/Common/SystemConfigurationService.cs`).
When behavior differs between clients, look for or add a Logic key rather than branching in code.
## Branches: one product, many client deployments
`origin` (`103.197.204.162:3025/CelHRTeam/cel.hrm`) carries ~79 branches, and they are not short-lived
feature branches. The default/integration branch is **`devqc`**. The rest are long-lived **per-client**
branches (`BergerHR`, `SGSHR`, `IDLC_Payroll_Master`, `Square_PMS*`, `Wartsila`, `LiFungHR`,
`Metlife_fund`, `PetromaxHR`, `ProclozPayroll`, `TexEbo_Payroll`, `Duncan_Payroll`, `HNM`, `PCSHRUAT`,
…) and **per-developer** ones (`dev_<name>`, `dev_<name>Master`).
Two consequences worth holding onto:
- Work moves between client branches by hand, as bulk "transferred from `<branch>`" commits — e.g.
`c8588ce67` "works transfered from square_pms". So a fix made here is *not* automatically in any
other client's branch, and a file can look freshly rewritten when it was only ported. Check
`git log --follow` before assuming a recent change was authored for this branch.
- This is *why* per-client behavior belongs in uploaded `*LogicConfiguration.xml` / `*-Menu.xml` data
and in the `Calendar` appsettings section rather than in `if (client == …)` code: config travels
with the database, code branching has to be re-merged across ~79 branches.
## Configuration (and which parts are actually live)
`HRM.UI/appsettings.json` holds real credentials committed to the repo. Treat it as sensitive: do not
print its contents into chat or logs, and do not commit new secrets alongside code changes.
What actually drives the DB connection:
- `Ease.Core.DataAccess.DbConfig.GetConfig()` reads the **`dbSettings`** section, and it does so by
building its own `ConfigurationBuilder` over `appsettings.json` from `Directory.GetCurrentDirectory()`
— completely outside the ASP.NET config pipeline. Consequence: **`appsettings.Development.json`
cannot override the database connection.** There is exactly one live connection, `dbSettings.Default`.
- Pointing the app at another database means editing which `dbSettings` line is commented out in
`appsettings.json` (the file carries a commented-out "master project DB" alternate).
- The `AppSettings.DbConfig[]` array (with its `"Key": "spadb"`) is **dead config** — nothing binds it;
the `AppSettings` POCO in `Startup.cs` has no such property.
Other live sections: `AppSettings` (`Secret`, `DefaultDB`, `RDLCLocation`, `downloadFolder`,
attendance import settings), `EmailSettings`, `EmployeeApiInfo`, `AdminPendingJob`,
`MobileAppSettings`, `FundInfo`, `OpenAI`, `LDAPSettings`, `Calendar` (bound to
`HRM.BO/Configuration/CalendarSettings.cs`), plus many payroll/fund GL-head keys.
`Startup.cs` has large commented-out blocks — verify against live code before assuming a feature is
on. In particular **Swagger is commented out entirely** even though `AppSettings.Swagger.Enabled` is
`true` in config. Active: JWT bearer, URL-segment API versioning, CORS (`http://localhost:4200`),
session + `AddDistributedMemoryCache`, `ICacheManager`/`MemoryCacheService`, an `OpenAIService` singleton (Semantic Kernel + OpenAI, with
`Controllers/OpenAIController` and the Angular `hrmopen-ai` module), Hangfire (below), and the SPA host.
### Background jobs (Hangfire)
Hangfire (`Hangfire.AspNetCore`/`Hangfire.SqlServer`) runs **in-process inside `HRM.UI`**; it is
currently used only by the Calendar module. All wiring lives in
`HRM.UI/BackgroundJobs/Calendar/CalendarHangfireSetup.cs`, hooked into `Startup` via
`services.AddCalendarBackgroundJobs(Configuration, HostingEnvironment)` and `app.UseCalendarBackgroundJobs()`:
- Storage is the **same database** as the app, via `ConnectionFactory.Default.CreateConnection()`
(so it follows `dbSettings`), in a separate `HangFire` schema that Hangfire auto-creates on first
start — don't put Hangfire tables in a `_DB_Changes.sql` script.
- One server, 4 workers, queues `CalendarJobs.QueueName` + `default`. Job classes are registered in DI
(`AddTransient<CalendarJobs>()`) and invoked by type, so job methods must stay public and their
arguments serializable.
- `CalendarJobs.Dispatch()` is a per-minute recurring job that serves both reminders and schedule-job runs
(HR's Schedule Jobs, `ItemType = 3`, which create a Task per run, made unique by `SourceItemID` +
`SourceOccurrence`); it is added or removed at startup depending on `Calendar.RemindersEnabled` /
`Calendar.ScheduleJobsEnabled`, and runs in server local time (the old daily birthday digest is retired;
startup only removes its recurring job). `Calendar.RedirectAllMailTo` reroutes every outgoing calendar mail
(use it on dev/UAT databases); `SendMail` turns sending off entirely, and in the Development environment
mail is only sent while `RedirectAllMailTo` is set.
- Calendar per-client switches (`OutlookSync`, `ScheduleJobsEnabled`, `MaxAttendees`, …) live in the `Calendar`
section of `appsettings.json`, not in a Logic XML key. `CalendarItemService` receives them through its
constructor (registered with a factory in `ServiceCollectionExtensions`). Some rules are fixed in code, not
settings: every employee may create events, line managers assign tasks to their own team (HR to anyone),
and the birthday / work-anniversary layers only ever show the user's own.
- Dashboard at `/hangfire`, local requests only. `UseCalendarBackgroundJobs()` must stay **before
`UseSpa`**, or the SPA fallback answers `/hangfire` with the Angular page.
## Database change scripts
Schema/proc changes are hand-authored `.sql` scripts named `<Feature>_DB_Changes.sql`, run against
each database **manually**. They live in two places and the distinction is the whole point:
- **Repo root** — the *pending* ones. `ls *_DB_Changes.sql` shows what has not been applied yet
(the list changes every few days — run it rather than trusting a written-down list). Write new
scripts here, in the same commit as the code that needs them.
- **[`db/Script/`](db/Script)** — the archive of shipped ones. Applied scripts used to be deleted
outright; commit `c8588ce67` (2026-10-13) instead *moved* the five applied ones here
(`Calendar`, `MenuIcon`, `AttendanceLeaveSummaryLM`, `TaxParameterEssDeadline`,
`PMS_SquareAlign_IDP`). Read them for precedent — they are the best worked examples of house style
— but don't re-run one against a database that already has it.
The convention is not enforced: `bfd085e0e` (Historical Data Upload) committed
`EmpHistoricalData_DB_Changes.sql` straight into `db/Script/`. So the root listing is not a complete
"pending" list — before deploying a branch to a database, also check `git log -- db/Script` for
scripts added since that database was last updated. It also breaks the other way: applied scripts
are still sometimes deleted instead of moved (`ScheduleEmail`, `UserEmailAddress`,
`HistorySalaryMonthlyAmountNull`, … in `ac179c03e` / `73f466cd0` / `91369150c`), so for those the only
copy is git history (`git show <deleting-commit>^:<file>`) —
`git log --diff-filter=D --name-only -- '*_DB_Changes.sql'` lists them.
Every script is guarded and re-runnable (`IF COL_LENGTH(...) IS NULL`, `IF OBJECT_ID(...) IS NULL`,
`sp_rename` only when the old name is still there), documents its own run order, and states whether
it must run *before* the matching code deploys. Follow that style.
## Frontend (`HRM.UI/ClientApp`, `Erecruitment.UI/ClientApp`)
`HRM.UI` is on **Angular 22.2** (framework 22.2.4, CLI/build/cdk 22.2.5) with **Kendo 25** on the Babylon admin
template; project name `babylon`, output `dist/babylon`; still NgModule-based (`bootstrapModule(AppModule)` with an
explicit `provideZoneChangeDetection()`), templates on the `@if`/`@for` control flow. **PrimeNG is gone** (Parts 1–7b,
2026-11): PrimeNG 22 and `primeicons` 8 are under the paid PrimeUI licence (Community only for orgs under $1M revenue /
5 devs / 10 employees), so never add `primeng`, `@primeuix/*` or `primeicons@8` back — `primeicons` stays on **7.0.0**
(the last MIT release) and `primeflex` stays. `Erecruitment.UI` is a separate, unused Angular 13 app. Entry
`src/main.ts`, root module `src/app/app.module.ts`, routes `src/app/app.routes.ts`.
What the Angular 22 upgrade (Part 8) changed, so don't undo it:
- Angular 22 makes `OnPush` the default, so `ng update` wrote `changeDetection: ChangeDetectionStrategy.Eager` (the
renamed `Default`) on every component — the code mutates arrays/objects in place and needs it. New components
should state it too unless they are really written for `OnPush`.
- In templates `a?.b` now yields `undefined` (JS semantics), not `null`; `ng update` wrapped the spots where that
mattered in `$safeNavigationMigration(...)`. Leave those wrappers alone.
- TypeScript **6.0** (`@angular/build` 22 requires `>=6.0 <6.1`; TS 7 must wait for Angular). `strictTemplates` is off,
so an `extendedDiagnostics` block in `tsconfig.app.json` fails the build (NG4003) — don't add one.
- MSAL is **`@azure/msal-angular` 6 / `@azure/msal-browser` 5** (v6 is the line for Angular 22). The app only uses
`loginRedirect`, which works without MSAL 5's redirect-bridge page; adding `loginPopup`/`ssoSilent` would need that
page and a new redirect URI in each client's Entra app registration. `storeAuthStateInCookie` no longer exists.
- Left on purpose: `@types/node` 24 (matches Node 24), `eslint` 9 (`eslint-plugin-import` does not support 10).
What the earlier 19 → 21 upgrade fixed in place, so don't undo it:
- **Kendo needs a current licence key.** Kendo checks the package *release* date against `telerik-license.txt`
(replace the file, then `npx kendo-ui-license activate`); Kendo 25.3.0 was published 2026-10-07, so an older key shows
a "Your license doesn't cover…" banner and an "Invalid license" watermark.
- Kendo 25 removed `primary` from buttons and grid commands (now `themeColor="primary"`) and `look` (now
`fillMode`); a `<kendo-formfield>` must wrap exactly one form control. The AOT build does **not** report every unknown input on directive-bearing elements — the
grid-command `[primary]` only showed up as a runtime NG0303 — so crawl the menu in dev mode after a UI-kit bump.
- `ess.module` uses `CUSTOM_ELEMENTS_SCHEMA`, so a removed `p-*`/`kendo-*` tag there fails silently, not at build.
- **npm 11 blocks install scripts.** `package.json` `allowScripts` approves `@progress/kendo-licensing`
(its postinstall runs `kendo-ui-license activate`; without it Kendo shows an "unlicensed" watermark) and `esbuild`.
After bumping either, re-run `npm approve-scripts <pkg>` or `npx kendo-ui-license activate`.
- **TabView is an adapter.** Screens use `app-tab-view` / `app-tab-panel`
(`custom-components/tab-view-compat/tab-view-compat.ts`, `TabViewCompatModule`), which keep the old PrimeNG
index-based API (`[(activeIndex)]`, `(onChange)` → `{index}`, `*ngIf` panels counted by visibility,
`<ng-template appTemplate="header">`, `tabView.tabs`) and render a `kendo-tabstrip`. New screens should use
`kendo-tabstrip` directly.
- The ~570 `'src/app/...'` imports resolve through
`paths: { "src/*": ["./src/*"] }` in `tsconfig.json` (no `baseUrl`, which TS 6 deprecates). `ngx-toastr` was removed (every call was commented
out; there is no Angular 22 release).
- Type-only imports must say `type` (`import { type X }`) — the CLI transpiles per file (`isolatedModules`).
- The build is the **esbuild/Vite `@angular/build:application`** builder (webpack and `@angular-devkit/build-angular`
are gone; prod build ~45 s, `ng serve` ready in ~40 s). `outputPath.browser` is `""`, so the output is still
`dist/babylon`, which `deploy.ps1` copies unchanged. AOT is on in development too. Google Fonts load from
`<link>` tags in `src/index.html`: esbuild drops a CSS `@import url(...)` that is not at the top of a file.
- `npm start` runs `scripts/ng-serve.cjs`, not `ng serve` directly. `UseAngularCliServer` (Startup) waits for
webpack's "open your browser on <url>" line, and the Vite dev server only prints "Local: <url>", so the script
echoes that line. Remove it only together with moving Startup off `UseAngularCliServer` (e.g. to SpaProxy).
- `xlsx` is **0.20.3 from `https://cdn.sheetjs.com/...tgz`** (SheetJS no longer publishes to npm; 0.18.5 had a high
advisory), so `npm install` needs that host reachable. 0.20 also fixed 0.18's Asia/Dhaka date bug: with
`cellDates: true`, 0.18 read Excel dates 20 s early, and Historical Career Data Upload (`toMiddayLocal`) saved every
date one day early — records uploaded before the switch may be off by a day. Known, unfixed: `quill` (low). `package.json` `overrides` pin `glob` ^14.0.3 under `@progress/kendo-licensing`
(its CLI only; `kendo-ui-license activate` verified) and `uuid` ^11.1.1 under `exceljs` (the browser uses exceljs's
prebuilt `dist/exceljs.min.js`). What is left in `npm audit` is exceljs's Node-only zip chain (`archiver`, glob 7)
and dev tooling (eslint, karma) — none of it ships to the browser. Install with plain `npm install`/`npm ci`;
`--force` is not needed.
- Feature areas are **lazy-loaded modules** registered in `app.routes.ts` behind `AuthGuard`
(`payroll`, `leave`, `attendance`, `recruitment`, `core-hr`, `fund-admin`, `ess`, `ess-fund`,
`ess-payroll`, `talent-management`, `final-settlement`, `claim`, `grievance-management`, `LMS`,
`hrmopen-ai`, `calendar`, `survey`, …), each under `src/app/<name>/` with its own `<name>.module.ts`.
- `app.api.service.ts` (`ApiService`) is the single HTTP wrapper (`httpGet`, `httpPost`,
`httpPostFile`, `httpDownloadFile`, …). The base URL comes from `environment.apiBaseUrl`
(`src/environments/environment.ts` → `https://localhost:44374/api`) in dev, and from the page's
`<base href>` + `api` in production. The auth token is a **static** `ApiService.AuthenticationToken`
sent as a Bearer header.
- Shared code: `_guards/`, `_models/<Module>/`, `_services/<module>/`, `picker/`/`_picker/`/
`dynamic-picker/`, `custom-components/`, `form-builder/`, `helper/`, `SharedIconModule/`.
- The UI kit is **Kendo UI Angular** (`@progress/kendo-angular-*`, licensed) plus chart.js, sweetalert2, the two
PDF viewers, exceljs/xlsx and MSAL (Azure AD, `SSO.Config.ts`). (Angular Material, Bootstrap, FullCalendar,
apexcharts, Font Awesome, ng-busy and PrimeNG were removed.) New markup uses Kendo or plain HTML. The dialog
pattern to copy:
`@if (show) { <div class="blur-background"><kendo-dialog title="…" [width]="900" maxHeight="90vh" (close)="show = false" (keydown.escape)="$event.stopPropagation()"> … </kendo-dialog></div> }`
(`.blur-background` is in `styles.scss`).
- What PrimeNG left behind, kept on purpose: the Babylon `layout-indigo.css` / `theme-indigo.css` (the app layout
depends on them — never remove), `primeicons` 7 (`pi pi-*`) and `primeflex`; the global rules PrimeNG's Aura theme
used to inject at runtime (`box-sizing`, `.pi` 1rem, `.p-disabled`) live in
`src/styles/components/_primeng-base.scss`; the old `primeng/api` types (`MenuItem`, `SelectItem`, `TreeNode`, …)
live in `_models/common/ui-types.ts`; the sidebar ripple is `@progress/kendo-ripple`'s `register()` in
`AppMenuComponent` (pinned 1.0.2).
- **Compiled `.js`/`.js.map` files are checked in alongside `.ts` sources** (~693 tracked `.js` files
under `src/`). Always edit the `.ts`; never the generated `.js`.
- Long-running actions show the shared loading panel: `<app-loading-panel></app-loading-panel>` in the
template plus `loadingPanel.ShowLoadingPanel = true/false` around the call (~395 templates use it).
Wrap every button/API action that can take a moment, and clear the flag in the error path too.
### App bootstrap and the initial route
Four pieces decide where a page load actually lands, and they are easy to break one at a time:
- Routing is **hash-based** (`{provide: LocationStrategy, useClass: HashLocationStrategy}` in
`app.module.ts`), so every URL is `…/#/path`. `RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})`.
- `path: ''` is `DashboardDemoComponent`. It is not a dashboard so much as a **dispatcher**: its
`ngOnInit` reads `UserType` from the JWT and forwards — `Employee` → `/ess/self-dashboard`, `User` →
`/ess/landing-page`, `SuperUser` stays. So anything that lands on `''` ends up on a dashboard.
- `AppMainComponent`'s constructor calls `authService.logout()` when the load is **not** a reload
(`performance.navigation.type`), which is why opening a deep link in a fresh tab signs the user out.
- `<app-login [hidden]="!isLoginForm()">` sits in
[app.main.component.html](HRM.UI/ClientApp/src/app/app.main.component.html) — `[hidden]`, **not
`*ngIf`**. So `LoginComponent`'s constructor runs once at bootstrap on *every* route, not just on
`/login`. It redirects to `/` when it finds a token, and because `ApiService`'s constructor now
hydrates the static `AuthenticationToken` from `localStorage`, that check went live and started
firing before the router's initial navigation — discarding the URL the user opened and dumping
every deep link on a dashboard. It is now gated on `window.location.hash` actually containing
`/login` ([login.component.ts](HRM.UI/ClientApp/src/app/login.component.ts)). Keep that gate: any
unconditional `router.navigate` in a constructor that runs at bootstrap will beat the initial
navigation and resurrect the same bug.
### Styles
Global stylesheet is `src/styles.scss`, which imports vendor CSS then two local trees:
- `src/styles/vendors/kendo/**` — centralized Kendo class overrides, split by component
(`grid/_rows.scss`, `buttons/_sizing.scss`, `card/_body.scss`, …). These are global/unscoped, so
they need no `::ng-deep`.
- `src/styles/abstracts/_tokens.scss` — app-wide SCSS design tokens (`$brand-*`, `$gray-*`, …). It has
no dependencies of its own; never import a vendor partial from it.
There is an ongoing centralization effort tracked in
[HRM.UI/docs/css-centralization-progress.md](HRM.UI/docs/css-centralization-progress.md): a per-file
checklist of component styles that duplicate Kendo overrides, use `::ng-deep`/`ViewEncapsulation.None`,
or hardcode colors. Before adding a Kendo override to a component stylesheet, check whether a
centralized partial already covers it, and update that document when you migrate a file.
One trap it documents: custom properties declared on `:host` do **not** resolve inside popups Kendo
portals to the document root (`appendTo: 'root'` — dropdown/calendar popups). Use SCSS variables that
compile to literals for those blocks, not `var(--…)`.
## Adding a feature: the full vertical slice
A typical feature commit touches, in order:
1. `HRM.BO/<Module>/<Entity>.cs` (+ the `I<Entity>Service` interface)
2. `HRM.DA/DA/<Module>/<Entity>DA.cs` — `internal static`, `MakeSQL`, takes `TransactionContext`
3. `HRM.DA/Service/<Module>/<Entity>Service.cs` — transaction + `MapObject`/`CreateObject`
4. `HRM.UI/Configurations/DI/ServiceCollectionExtensions.cs` — register it
5. `HRM.UI/Controllers/<Module>/<Module>Controller.cs` — thin endpoint
6. `ClientApp/src/app/_models/<Module>/<entity>.ts` and `_services/<module>/<module>.service.ts`
7. the feature component(s) under `ClientApp/src/app/<feature>/`
8. a root `<Feature>_DB_Changes.sql` if the schema changes
## Editor rules
`.github/copilot-instructions.md` requires: for anything Azure-related, always use the Azure tools and
invoke `azmcp_bestpractices_get` first; if that tool isn't available, ask the user to enable it.

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup>
</configuration>

View File

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9AA39EFC-3B4F-4D3D-928C-5E2C178ED105}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DatabaseComparison</RootNamespace>
<AssemblyName>DatabaseComparison</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Form2.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form2.Designer.cs">
<DependentUpon>Form2.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Form2.resx">
<DependentUpon>Form2.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

625
DatabaseComparison/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,625 @@
namespace DatabaseComparison
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmbSourceDatabase = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtSourceServer = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtSourceUserNane = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtSourcePassword = new System.Windows.Forms.TextBox();
this.btnGetSource = new System.Windows.Forms.Button();
this.cmbDestinationDatabase = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.txtDestinationServer = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.txtDestinationUserNane = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.txtDestinationPassword = new System.Windows.Forms.TextBox();
this.btnGetDestination = new System.Windows.Forms.Button();
this.lsvSourceList = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lblSourceCount = new System.Windows.Forms.Label();
this.lsvDestinationList = new System.Windows.Forms.ListView();
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.lblDestinationCount = new System.Windows.Forms.Label();
this.btnCompate = new System.Windows.Forms.Button();
this.rtbText = new System.Windows.Forms.RichTextBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.button1 = new System.Windows.Forms.Button();
this.grdList = new System.Windows.Forms.DataGridView();
this.colTabName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colColName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDataType = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colLength = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colAllowNull = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDefaultValue = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDR = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colPrecision = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colScale = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.label10 = new System.Windows.Forms.Label();
this.btnCreateScript = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.lblMsg = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.grdList)).BeginInit();
this.SuspendLayout();
//
// cmbSourceDatabase
//
this.cmbSourceDatabase.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSourceDatabase.FormattingEnabled = true;
this.cmbSourceDatabase.Location = new System.Drawing.Point(82, 151);
this.cmbSourceDatabase.Name = "cmbSourceDatabase";
this.cmbSourceDatabase.Size = new System.Drawing.Size(173, 21);
this.cmbSourceDatabase.TabIndex = 0;
this.cmbSourceDatabase.SelectedIndexChanged += new System.EventHandler(this.cmbSourceDatabase_SelectedIndexChanged);
//
// label1
//
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(243, 18);
this.label1.TabIndex = 1;
this.label1.Text = "Source";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 155);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 13);
this.label3.TabIndex = 1;
this.label3.Text = "Database";
//
// txtSourceServer
//
this.txtSourceServer.Location = new System.Drawing.Point(82, 44);
this.txtSourceServer.Name = "txtSourceServer";
this.txtSourceServer.Size = new System.Drawing.Size(173, 20);
this.txtSourceServer.TabIndex = 2;
this.txtSourceServer.Text = "103.197.204.164,1718";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 47);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Server";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 73);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(60, 13);
this.label4.TabIndex = 1;
this.label4.Text = "User Name";
//
// txtSourceUserNane
//
this.txtSourceUserNane.Location = new System.Drawing.Point(82, 70);
this.txtSourceUserNane.Name = "txtSourceUserNane";
this.txtSourceUserNane.Size = new System.Drawing.Size(173, 20);
this.txtSourceUserNane.TabIndex = 2;
this.txtSourceUserNane.Text = "sysuser";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 99);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 13);
this.label5.TabIndex = 1;
this.label5.Text = "Password";
//
// txtSourcePassword
//
this.txtSourcePassword.Location = new System.Drawing.Point(82, 96);
this.txtSourcePassword.Name = "txtSourcePassword";
this.txtSourcePassword.Size = new System.Drawing.Size(173, 20);
this.txtSourcePassword.TabIndex = 2;
this.txtSourcePassword.Text = "cel1@3$5";
//
// btnGetSource
//
this.btnGetSource.Location = new System.Drawing.Point(121, 122);
this.btnGetSource.Name = "btnGetSource";
this.btnGetSource.Size = new System.Drawing.Size(94, 23);
this.btnGetSource.TabIndex = 3;
this.btnGetSource.Text = "Get Database";
this.btnGetSource.UseVisualStyleBackColor = true;
this.btnGetSource.Click += new System.EventHandler(this.btnGetSource_Click);
//
// cmbDestinationDatabase
//
this.cmbDestinationDatabase.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbDestinationDatabase.FormattingEnabled = true;
this.cmbDestinationDatabase.Location = new System.Drawing.Point(352, 151);
this.cmbDestinationDatabase.Name = "cmbDestinationDatabase";
this.cmbDestinationDatabase.Size = new System.Drawing.Size(168, 21);
this.cmbDestinationDatabase.TabIndex = 0;
this.cmbDestinationDatabase.SelectedIndexChanged += new System.EventHandler(this.cmbDestinationDatabase_SelectedIndexChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(282, 155);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(53, 13);
this.label6.TabIndex = 1;
this.label6.Text = "Database";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(282, 47);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(38, 13);
this.label7.TabIndex = 1;
this.label7.Text = "Server";
//
// txtDestinationServer
//
this.txtDestinationServer.Location = new System.Drawing.Point(352, 44);
this.txtDestinationServer.Name = "txtDestinationServer";
this.txtDestinationServer.Size = new System.Drawing.Size(168, 20);
this.txtDestinationServer.TabIndex = 2;
this.txtDestinationServer.Text = "103.197.204.163, 3341";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(282, 73);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(60, 13);
this.label8.TabIndex = 1;
this.label8.Text = "User Name";
//
// txtDestinationUserNane
//
this.txtDestinationUserNane.Location = new System.Drawing.Point(352, 70);
this.txtDestinationUserNane.Name = "txtDestinationUserNane";
this.txtDestinationUserNane.Size = new System.Drawing.Size(168, 20);
this.txtDestinationUserNane.TabIndex = 2;
this.txtDestinationUserNane.Text = "hrpayrolluser";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(282, 99);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(53, 13);
this.label9.TabIndex = 1;
this.label9.Text = "Password";
//
// txtDestinationPassword
//
this.txtDestinationPassword.Location = new System.Drawing.Point(352, 96);
this.txtDestinationPassword.Name = "txtDestinationPassword";
this.txtDestinationPassword.Size = new System.Drawing.Size(168, 20);
this.txtDestinationPassword.TabIndex = 2;
this.txtDestinationPassword.Text = "hrpayrolluser";
//
// btnGetDestination
//
this.btnGetDestination.Location = new System.Drawing.Point(385, 122);
this.btnGetDestination.Name = "btnGetDestination";
this.btnGetDestination.Size = new System.Drawing.Size(94, 23);
this.btnGetDestination.TabIndex = 3;
this.btnGetDestination.Text = "Get Database";
this.btnGetDestination.UseVisualStyleBackColor = true;
this.btnGetDestination.Click += new System.EventHandler(this.btnGetDestination_Click);
//
// lsvSourceList
//
this.lsvSourceList.CheckBoxes = true;
this.lsvSourceList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.lsvSourceList.GridLines = true;
this.lsvSourceList.Location = new System.Drawing.Point(15, 178);
this.lsvSourceList.Name = "lsvSourceList";
this.lsvSourceList.Size = new System.Drawing.Size(240, 410);
this.lsvSourceList.TabIndex = 4;
this.lsvSourceList.UseCompatibleStateImageBehavior = false;
this.lsvSourceList.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Table Name";
this.columnHeader1.Width = 210;
//
// lblSourceCount
//
this.lblSourceCount.AutoSize = true;
this.lblSourceCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblSourceCount.Location = new System.Drawing.Point(19, 608);
this.lblSourceCount.Name = "lblSourceCount";
this.lblSourceCount.Size = new System.Drawing.Size(0, 13);
this.lblSourceCount.TabIndex = 1;
//
// lsvDestinationList
//
this.lsvDestinationList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader2});
this.lsvDestinationList.GridLines = true;
this.lsvDestinationList.Location = new System.Drawing.Point(285, 178);
this.lsvDestinationList.Name = "lsvDestinationList";
this.lsvDestinationList.Size = new System.Drawing.Size(235, 410);
this.lsvDestinationList.TabIndex = 4;
this.lsvDestinationList.UseCompatibleStateImageBehavior = false;
this.lsvDestinationList.View = System.Windows.Forms.View.Details;
//
// columnHeader2
//
this.columnHeader2.Text = "Table Name";
this.columnHeader2.Width = 210;
//
// lblDestinationCount
//
this.lblDestinationCount.AutoSize = true;
this.lblDestinationCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblDestinationCount.Location = new System.Drawing.Point(363, 608);
this.lblDestinationCount.Name = "lblDestinationCount";
this.lblDestinationCount.Size = new System.Drawing.Size(0, 13);
this.lblDestinationCount.TabIndex = 1;
//
// btnCompate
//
this.btnCompate.BackColor = System.Drawing.Color.LightCoral;
this.btnCompate.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCompate.Location = new System.Drawing.Point(285, 594);
this.btnCompate.Name = "btnCompate";
this.btnCompate.Size = new System.Drawing.Size(235, 32);
this.btnCompate.TabIndex = 5;
this.btnCompate.Text = "Compare";
this.btnCompate.UseVisualStyleBackColor = false;
this.btnCompate.Click += new System.EventHandler(this.btnCompate_Click);
//
// rtbText
//
this.rtbText.Location = new System.Drawing.Point(945, 69);
this.rtbText.Name = "rtbText";
this.rtbText.Size = new System.Drawing.Size(22, 17);
this.rtbText.TabIndex = 6;
this.rtbText.Text = "";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(20, 592);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(70, 17);
this.checkBox1.TabIndex = 7;
this.checkBox1.Text = "Select All";
this.checkBox1.UseVisualStyleBackColor = true;
this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// button1
//
this.button1.Location = new System.Drawing.Point(996, 63);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(102, 23);
this.button1.TabIndex = 8;
this.button1.Text = "Copy to Clipboard";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// grdList
//
this.grdList.AllowUserToAddRows = false;
this.grdList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colTabName,
this.colColName,
this.colDataType,
this.colLength,
this.colAllowNull,
this.colDefaultValue,
this.colDR,
this.colPrecision,
this.colScale});
this.grdList.Location = new System.Drawing.Point(530, 44);
this.grdList.MultiSelect = false;
this.grdList.Name = "grdList";
this.grdList.RowHeadersVisible = false;
this.grdList.Size = new System.Drawing.Size(738, 544);
this.grdList.TabIndex = 9;
this.grdList.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdList_CellValueChanged);
this.grdList.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdList_CellValueChanged);
//
// colTabName
//
this.colTabName.HeaderText = "Table Nme";
this.colTabName.Name = "colTabName";
this.colTabName.ReadOnly = true;
this.colTabName.Width = 200;
//
// colColName
//
this.colColName.HeaderText = "Column Name";
this.colColName.Name = "colColName";
this.colColName.ReadOnly = true;
this.colColName.Width = 170;
//
// colDataType
//
this.colDataType.HeaderText = "Data Type";
this.colDataType.Name = "colDataType";
this.colDataType.ReadOnly = true;
this.colDataType.Width = 90;
//
// colLength
//
this.colLength.HeaderText = "Length";
this.colLength.Name = "colLength";
this.colLength.Width = 60;
//
// colAllowNull
//
this.colAllowNull.HeaderText = "Allow Null";
this.colAllowNull.Name = "colAllowNull";
this.colAllowNull.ReadOnly = true;
this.colAllowNull.Width = 60;
//
// colDefaultValue
//
this.colDefaultValue.HeaderText = "Default Value";
this.colDefaultValue.Name = "colDefaultValue";
this.colDefaultValue.Width = 80;
//
// colDR
//
this.colDR.HeaderText = "Value Required";
this.colDR.Name = "colDR";
this.colDR.Width = 60;
//
// colPrecision
//
this.colPrecision.HeaderText = "Precision";
this.colPrecision.Name = "colPrecision";
this.colPrecision.Width = 50;
//
// colScale
//
this.colScale.HeaderText = "Scale";
this.colScale.Name = "colScale";
this.colScale.Width = 50;
//
// label10
//
this.label10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label10.Location = new System.Drawing.Point(282, 9);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(238, 18);
this.label10.TabIndex = 1;
this.label10.Text = "Destination";
this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnCreateScript
//
this.btnCreateScript.BackColor = System.Drawing.Color.PaleGreen;
this.btnCreateScript.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCreateScript.Location = new System.Drawing.Point(1082, 594);
this.btnCreateScript.Name = "btnCreateScript";
this.btnCreateScript.Size = new System.Drawing.Size(186, 32);
this.btnCreateScript.TabIndex = 5;
this.btnCreateScript.Text = "Generate Script";
this.btnCreateScript.UseVisualStyleBackColor = false;
this.btnCreateScript.Click += new System.EventHandler(this.btnCreateScript_Click);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.Olive;
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Location = new System.Drawing.Point(264, 9);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(10, 579);
this.panel1.TabIndex = 10;
//
// lblMsg
//
this.lblMsg.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblMsg.ForeColor = System.Drawing.Color.Blue;
this.lblMsg.Location = new System.Drawing.Point(527, 591);
this.lblMsg.Name = "lblMsg";
this.lblMsg.Size = new System.Drawing.Size(426, 35);
this.lblMsg.TabIndex = 15;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(610, 11);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(149, 20);
this.textBox1.TabIndex = 17;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(540, 14);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(43, 13);
this.label11.TabIndex = 16;
this.label11.Text = "User ID";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(872, 10);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(146, 20);
this.textBox2.TabIndex = 19;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(787, 13);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(79, 13);
this.label12.TabIndex = 18;
this.label12.Text = "Payroll Type ID";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(1122, 11);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(146, 20);
this.textBox3.TabIndex = 21;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(1037, 14);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(70, 13);
this.label13.TabIndex = 20;
this.label13.Text = "Created Date";
this.label13.Click += new System.EventHandler(this.label13_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1274, 630);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label13);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label12);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label11);
this.Controls.Add(this.lblMsg);
this.Controls.Add(this.panel1);
this.Controls.Add(this.grdList);
this.Controls.Add(this.button1);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.rtbText);
this.Controls.Add(this.btnCreateScript);
this.Controls.Add(this.btnCompate);
this.Controls.Add(this.lsvDestinationList);
this.Controls.Add(this.lsvSourceList);
this.Controls.Add(this.btnGetDestination);
this.Controls.Add(this.btnGetSource);
this.Controls.Add(this.txtDestinationPassword);
this.Controls.Add(this.lblDestinationCount);
this.Controls.Add(this.lblSourceCount);
this.Controls.Add(this.label9);
this.Controls.Add(this.txtSourcePassword);
this.Controls.Add(this.txtDestinationUserNane);
this.Controls.Add(this.label5);
this.Controls.Add(this.label8);
this.Controls.Add(this.txtSourceUserNane);
this.Controls.Add(this.txtDestinationServer);
this.Controls.Add(this.label4);
this.Controls.Add(this.label7);
this.Controls.Add(this.txtSourceServer);
this.Controls.Add(this.label6);
this.Controls.Add(this.label2);
this.Controls.Add(this.label3);
this.Controls.Add(this.cmbDestinationDatabase);
this.Controls.Add(this.label10);
this.Controls.Add(this.label1);
this.Controls.Add(this.cmbSourceDatabase);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Compare Database";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.grdList)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbSourceDatabase;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtSourceServer;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtSourceUserNane;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtSourcePassword;
private System.Windows.Forms.Button btnGetSource;
private System.Windows.Forms.ComboBox cmbDestinationDatabase;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtDestinationServer;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtDestinationUserNane;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TextBox txtDestinationPassword;
private System.Windows.Forms.Button btnGetDestination;
private System.Windows.Forms.ListView lsvSourceList;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.Label lblSourceCount;
private System.Windows.Forms.ListView lsvDestinationList;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.Label lblDestinationCount;
private System.Windows.Forms.Button btnCompate;
private System.Windows.Forms.RichTextBox rtbText;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.DataGridView grdList;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button btnCreateScript;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label lblMsg;
private System.Windows.Forms.DataGridViewTextBoxColumn colTabName;
private System.Windows.Forms.DataGridViewTextBoxColumn colColName;
private System.Windows.Forms.DataGridViewTextBoxColumn colDataType;
private System.Windows.Forms.DataGridViewTextBoxColumn colLength;
private System.Windows.Forms.DataGridViewTextBoxColumn colAllowNull;
private System.Windows.Forms.DataGridViewTextBoxColumn colDefaultValue;
private System.Windows.Forms.DataGridViewTextBoxColumn colDR;
private System.Windows.Forms.DataGridViewTextBoxColumn colPrecision;
private System.Windows.Forms.DataGridViewTextBoxColumn colScale;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label13;
}
}

2752
DatabaseComparison/Form1.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="colTabName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colColName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDataType.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colLength.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colAllowNull.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDefaultValue.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDR.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colPrecision.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colScale.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colTabName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colColName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDataType.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colLength.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colAllowNull.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDefaultValue.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDR.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colPrecision.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colScale.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

71
DatabaseComparison/Form2.Designer.cs generated Normal file
View File

@ -0,0 +1,71 @@
namespace DatabaseComparison
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.richTextBox1);
this.panel1.Location = new System.Drawing.Point(12, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(954, 413);
this.panel1.TabIndex = 3;
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(3, 3);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(948, 407);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(978, 437);
this.Controls.Add(this.panel1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.RichTextBox richTextBox1;
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DatabaseComparison
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void ShowDialog(string errorText)
{
richTextBox1.Text = errorText;
this.ShowDialog();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DatabaseComparison
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DatabaseComparison")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DatabaseComparison")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9aa39efc-3b4f-4d3d-928c-5e2c178ed105")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("23.09.18.01")]
[assembly: AssemblyFileVersion("23.09.18.01")]

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DatabaseComparison.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DatabaseComparison.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DatabaseComparison.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

8
Ease.Core/Class1.cs Normal file
View File

@ -0,0 +1,8 @@
using System;
namespace Ease.CoreC
{
public class Class1
{
}
}

View File

@ -0,0 +1,196 @@
using System;
using System.Data;
using Ease.Core.Utility;
using Ease.Core.DataAccess;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Ease.Core.DataAccess
{
#region DataAccess: Connection Facory
public sealed class DBConnections
{
private static DbConfig _allConnections = null;
private static string _defaultConnection = null;
private static readonly object _lock = new object();
public static IConfigurationRoot _configuration;
DBConnections()
{
}
public static DbConfig Connections
{
get
{
if (_allConnections == null)
{
lock (_lock)
{
// create the instance only if the instance is null
if (_allConnections == null)
{
//string str[] = Microsoft.Extensions.Configuration.ConfigurationSection
_allConnections = DbConfig.GetConfig();
}
}
}
// Otherwise return the already existing instance
return _allConnections;
}
}
public static string DefaultConnection
{
get
{
//if (_defaultConnection == null || _defaultConnection == "")
//{
// lock (_lock)
// {
// // create the instance only if the instance is null
// if (_defaultConnection == null)
// {
// _defaultConnection = _allConnections["Default"].ConnectionString;
// }
// }
//}
_defaultConnection = "Default";
// Otherwise return the already existing instance
return _defaultConnection;
}
}
}
public abstract class ConnectionFactory
{
#region Variable declaration
private static int _connectionIdx = 0;
private static List<string> _dataSources;
private static DbConfig.ConnectionNode _cn;
//private static DbConfig _dbCfg = DBConnections.Connections;
#endregion
#region Properties
internal SQLSyntax Syntax
{
get { return _cn.Syntax; }
}
internal static Provider Provider
{
get { return _cn.Provider; }
}
internal static List<string> DataSources
{
get { return _dataSources; }
}
internal static int ConnectionCount
{
get { return DBConnections.Connections.Names.Length; }
}
internal DbConfig.ConnectionNode ConnectionNode
{
get { return _cn; }
}
/// <summary>
/// This property is used to point the default database
/// </summary>
public static ConnectionFactory Default
{
get
{
//_dataSources = new List<string>();
//If no setting have been found
//if (string.IsNullOrEmpty(DBConnections.DefaultConnection))
// throw new ArgumentException(string.Format("Either serviceHandler key in app setting is missing.{0}Or{0}type key in serviceConfiguration is missing.", Environment.NewLine));
////Preparing Datasources
//_dataSources.AddRange(DBConnections.DefaultConnection.Split('~'));
//if (_dataSources == null || _dataSources.Count <= 0)
// throw new Exception("Data source is not specified in defaultDB.");
//Findout actual ConnectionName
// if (DBConnections.Connections != null)
_cn = DBConnections.Connections[DBConnections.DefaultConnection];
if (_cn == null)
throw new Exception(string.Format("Invalid use of configuration setting: {0}",
DBConnections.DefaultConnection));
return _cn.Factory;
}
}
#endregion
#region Functions
internal static void SetConnectionIndex(int connectionIdx)
{
_connectionIdx = connectionIdx;
}
/// <summary>
/// Create an instatnce of connection factory using valid connectioncontext.
/// </summary>
/// <param name="context">Valid connection context.</param>
/// <returns>Return an instatnce of connection factory.</returns>
public static ConnectionFactory ContextConnection(ConnectionContext context)
{
if (context == null || context.ContextKey.Length <= 0)
throw new Exception("Invalid use of configuration setting");
//string conKey = ConfigUtility.GetAppSettings(context.ContextKey);
////If no setting have been found
//if (string.IsNullOrEmpty(conKey))
// throw new ArgumentException(string.Format("Please use serviceHandler key: {0} in app setting.", context.ContextKey));
if (_cn != null && _cn.Name.Equals(context.ContextKey))
return _cn.Factory;
if (DBConnections.Connections != null)
_cn = DBConnections.Connections[context.ContextKey];
if (_cn == null)
throw new Exception("Invalid use of configuration setting");
return _cn.Factory;
}
public static ConnectionFactory CreateConnection(Provider provider, SQLSyntax syntax, string connectionString)
{
if (_cn == null || _cn.ConnectionString.ToLower() != connectionString.ToLower())
{
_cn = new DbConfig.ConnectionNode();
_cn.CreateNode(provider, syntax, connectionString);
}
if (_cn == null)
throw new Exception("Invalid use of configuration setting");
return _cn.Factory;
}
public abstract IDbConnection CreateConnection();
public abstract IDbConnection CreateConnection(ConnectionContext context);
#endregion
}
#endregion
}

View File

@ -0,0 +1,148 @@
using System;
using System.Data;
using Ease.Core.Utility;
using System.Collections.Generic;
namespace Ease.Core.DataAccess
{
#region Conntection context
/// <summary>
/// Summary description for ConnectionContext.
/// Pass key of database connection according to config file
/// </summary>
public sealed class ConnectionContext
{
private readonly string _ctxKey = string.Empty;
public ConnectionContext()
{
_ctxKey = "default";
}
public ConnectionContext(string ctxKey)
{
_ctxKey = ctxKey;
}
public string ContextKey
{
get { return _ctxKey; }
}
}
#endregion
/// <summary>
/// This class is used to help to fill dataset.
/// </summary>
internal class DataAccessHelper
{
#region Fill Data set
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the
/// DataReader records.</param>
/// <param name="from">The quantity of records skipped before placing
/// values on the DataReader on the DataSet.</param>
/// <param name="count">The maximum quantity of records alloed to fill on the
/// DataSet.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName, int from, int count)
{
string fieldName;
DataTable fillTable;
DataRow fillRow;
int recNumber = 0;
int totalRecords = from + count;
//If table name is null then set the string
if (tableName == null)
{
tableName = "unknownTable";
}
//If table does not exist in data set then add table
if (dataSet.Tables[tableName] == null)
{
dataSet.Tables.Add(tableName);
}
// Get the DataTable reference
if (tableName == null)
{
fillTable = dataSet.Tables[0];
}
else
{
fillTable = dataSet.Tables[tableName];
}
while (dataReader.Read())
{
if (recNumber++ >= from)
{
fillRow = fillTable.NewRow();
for (int fieldIdx = 0; fieldIdx < dataReader.FieldCount; fieldIdx++)
{
fieldName = dataReader.GetName(fieldIdx);
Type fieldType = dataReader.GetValue(fieldIdx).GetType();
if (fillTable.Columns.IndexOf(fieldName) == -1)
{
fillTable.Columns.Add(fieldName, fieldType);
}
fillRow[fieldName] = GetValue(dataReader.GetValue(fieldIdx), fieldType);
}
fillTable.Rows.Add(fillRow);
}
if (count != 0 && totalRecords <= recNumber)
{
break;
}
}
dataSet.AcceptChanges();
}
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the DataReader records.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName)
{
Fill(dataReader, dataSet, tableName, 0, 0);
}
#endregion
#region private function
private static object GetValue(object fieldValue, Type fieldType)
{
switch (fieldType.Name)
{
case "Int16":
case "Int32":
case "Int64":
case "UInt16":
case "UInt32":
case "UInt64":
return fieldValue == DBNull.Value ? 0 : fieldValue;
}
return fieldValue;
}
#endregion
}
}

View File

@ -0,0 +1,810 @@
using System;
using System.Linq;
using System.Data;
using System.Globalization;
namespace Ease.Core.DataAccess
{
#region DataAccess: Data Handler
/// <summary>
/// Handle the null value
/// </summary>
public class DataReader
{
private DataTable _table;
private IDataReader _reader;
private bool _isOracleDB = false;
public DataReader(IDataReader reader)
{
_reader = reader;
_table = _reader.GetSchemaTable();
}
#region Get Null value
public static bool? GetNullValue(bool value, bool nullIfValue)
{
return (value == nullIfValue) ? null : (bool?)value;
}
public static byte? GetNullValue(byte value, byte nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static sbyte? GetNullValue(sbyte value, sbyte nullIfValue)
{
return (value == nullIfValue) ? null : (sbyte?)value;
}
public static short? GetNullValue(short value, short nullIfValue)
{
return (value == nullIfValue) ? null : (short?)value;
}
public static ushort? GetNullValue(ushort value, ushort nullIfValue)
{
return (value == nullIfValue) ? null : (ushort?)value;
}
public static int? GetNullValue(int value, int nullIfValue)
{
return (value == nullIfValue) ? null : (int?)value;
}
public static uint? GetNullValue(uint value, uint nullIfValue)
{
return (value == nullIfValue) ? null : (uint?)value;
}
public static ulong? GetNullValue(ulong value, ulong nullIfValue)
{
return (value == nullIfValue) ? null : (ulong?)value;
}
public static long? GetNullValue(long value, long nullIfValue)
{
return (value == nullIfValue) ? null : (long?)value;
}
public static decimal? GetNullValue(decimal value, decimal nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static double? GetNullValue(double value, double nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static float? GetNullValue(float value, float nullIfValue)
{
return (value == nullIfValue) ? null : (float?)value;
}
public static char? GetNullValue(char value, char nullIfValue)
{
return (value == nullIfValue) ? null : (char?)value;
}
public static object GetNullValue(string value, string nullIfValue)
{
return (value == nullIfValue) ? null : value;
}
public static DateTime? GetNullValue(DateTime value, DateTime nullIfValue)
{
return (value == nullIfValue) ? null : (DateTime?)value;
}
public static DateTime? GetNullValue(DateTime? value, DateTime nullIfValue)
{
return (value == nullIfValue) ? null : (DateTime?)value;
}
public static Guid? GetNullValue(Guid value, Guid nullIfValue)
{
return (value == nullIfValue) ? null : (Guid?)value;
}
public static bool? GetNullValue(bool? value)
{
return (value == null || value == false) ? null : (bool?)value;
}
public static byte? GetNullValue(byte? value)
{
return (value == null || value == 0) ? null : (byte?)value;
}
public static sbyte? GetNullValue(sbyte? value)
{
return (value == null || value == 0) ? null : (sbyte?)value;
}
public static short? GetNullValue(short? value)
{
return (value == null || value == 0) ? null : (short?)value;
}
public static ushort? GetNullValue(ushort? value)
{
return (value == null || value == 0) ? null : (ushort?)value;
}
public static int? GetNullValue(int? value)
{
return (value == null || value == 0) ? null : (int?)value;
}
public static uint? GetNullValue(uint? value)
{
return (value == null || value == 0) ? null : (uint?)value;
}
public static ulong? GetNullValue(ulong? value)
{
return (value == null || value == 0) ? null : (ulong?)value;
}
public static long? GetNullValue(long? value)
{
return (value == null || value == 0) ? null : (long?)value;
}
public static decimal? GetNullValue(decimal? value)
{
return (value == null || value == 0) ? null : (decimal?)value;
}
public static double? GetNullValue(double? value)
{
return (value == null || value == 0) ? null : (double?)value;
}
public static float? GetNullValue(float? value)
{
return (value == null || value == 0) ? null : (float?)value;
}
public static char? GetNullValue(char? value)
{
return (value == null || (byte)value == 0) ? null : (char?)value;
}
public static string GetNullValue(string value)
{
return (string.IsNullOrEmpty(value)) ? null : value;
}
public static DateTime? GetNullValue(DateTime? value)
{
return (value == null || value == DateTime.MinValue) ? null : (DateTime?)value;
}
public static Guid? GetNullValue(Guid? value)
{
return value;
}
#endregion
#region Default Null Values
public bool? GetBoolean(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (bool?)value.ToBoolean(null);
}
public byte? GetByte(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (byte?)value.ToByte(null);
}
public sbyte? GetSByte(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (sbyte?)value.ToSByte(null);
}
public short? GetInt16(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (short?)value.ToInt16(null);
}
public ushort? GetUInt16(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (ushort?)value.ToUInt16(null);
}
public int? GetInt32(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (int?)value.ToInt32(null);
}
public uint? GetUInt32(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (uint?)value.ToUInt32(null);
}
public long? GetInt64(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (long?)value.ToInt64(null);
}
public ulong? GetUInt64(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (ulong?)value.ToUInt64(null);
}
public decimal? GetDecimal(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (decimal?)value.ToDecimal(null);
}
public double? GetDouble(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (double?)value.ToDouble(null);
}
public float? GetFloat(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (float?)value.ToSingle(null);
}
public char? GetChar(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (char?)value.ToChar(null);
}
public string GetString(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : value.ToString(null);
}
public DateTime? GetDateTime(int i)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? null : (DateTime?)value.ToDateTime(null);
}
public TimeSpan? GetTime(int i)
{
object value = _reader.GetValue(i);
return value == DBNull.Value ? null : (TimeSpan?)((TimeSpan)value);
}
public Guid? GetGuid(int i)
{
object value = _reader.GetValue(i);
return value == DBNull.Value ? null : (Guid?)value;
}
public byte[] GetLob(int i)
{
return (byte[])(_reader.IsDBNull(i) ? (byte[])null : _reader.GetValue(i));
}
public bool? GetBoolean(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (bool?)value.ToBoolean(null);
}
public byte? GetByte(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (byte?)value.ToByte(null);
}
public sbyte? GetSByte(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (sbyte?)value.ToSByte(null);
}
public short? GetInt16(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (short?)value.ToInt16(null);
}
public ushort? GetUInt16(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (ushort?)value.ToUInt16(null);
}
public int? GetInt32(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? (int?)null : (int?)value.ToInt32(null);
}
public uint? GetUInt32(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (uint?)value.ToUInt32(null);
}
public long? GetInt64(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (long?)value.ToInt64(null);
}
public ulong? GetUInt64(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (ulong?)value.ToUInt64(null);
}
public decimal? GetDecimal(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (decimal?)value.ToDecimal(null);
}
public double? GetDouble(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (double?)value.ToDouble(null);
}
public float? GetFloat(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (float?)value.ToSingle(null);
}
public char? GetChar(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (char?)value.ToChar(null);
}
public string GetString(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : value.ToString(null);
}
public DateTime? GetDateTime(string name)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? null : (DateTime?)value.ToDateTime(null);
}
public TimeSpan? GetTime(string name)
{
object value = _reader[name];
return value == DBNull.Value ? null : (TimeSpan?)((TimeSpan)value);
}
public Guid? GetGuid(string name)
{
object value = _reader[name];
return value == DBNull.Value ? null : (Guid?)value;
}
public byte[] GetLob(string name)
{
return (byte[])(_reader[name] == DBNull.Value ? (byte[])null : _reader[name]);
}
#endregion
#region Parameterized Null Value
bool columnExists(string columnName)
{
columnName = (from DataRow dr in _table.Rows
where Convert.ToString(dr["ColumnName"]).ToLower().Equals(columnName.ToLower())
select Convert.ToString(dr["ColumnName"])).FirstOrDefault();
return !string.IsNullOrEmpty(columnName);
}
public bool GetBoolean(int i, bool valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToBoolean(null);
}
public byte GetByte(int i, byte valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToByte(null);
}
public sbyte GetSByte(int i, sbyte valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToSByte(null);
}
public short GetInt16(int i, short valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToInt16(null);
}
public ushort GetUInt16(int i, ushort valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToUInt16(null);
}
public int GetInt32(int i, int valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToInt32(null);
}
public uint GetUInt32(int i, uint valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToUInt32(null);
}
public ulong GetUInt64(int i, ulong valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToUInt64(null);
}
public long GetInt64(int i, long valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToInt64(null);
}
public decimal GetDecimal(int i, decimal valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToDecimal(null);
}
public double GetDouble(int i, double valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToDouble(null);
}
public float GetFloat(int i, float valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToSingle(null);
}
public char GetChar(int i, char valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToChar(null);
}
public string GetString(int i, string valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToString(null);
}
public DateTime GetDateTime(int i, DateTime valueIfNull)
{
IConvertible value = (IConvertible)_reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : value.ToDateTime(null);
}
public TimeSpan GetTime(int i, TimeSpan valueIfNull)
{
object value = _reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : (TimeSpan)value;
}
public Guid GetGuid(int i, Guid valueIfNull)
{
object value = _reader.GetValue(i);
return value == DBNull.Value ? valueIfNull : (Guid)value;
}
public bool GetBoolean(string name, bool valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToBoolean(null);
}
public byte GetByte(string name, byte valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToByte(null);
}
public sbyte GetSByte(string name, sbyte valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToSByte(null);
}
public short GetInt16(string name, short valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToInt16(null);
}
public ushort GetUInt16(string name, ushort valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt16(null);
}
public int GetInt32(string name, int valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToInt32(null);
}
public uint GetUInt32(string name, uint valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt32(null);
}
public ulong GetUInt64(string name, ulong valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt64(null);
}
public long GetInt64(string name, long valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToInt64(null);
}
public decimal GetDecimal(string name, decimal valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToDecimal(null);
}
public double GetDouble(string name, double valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToDouble(null);
}
public float GetFloat(string name, float valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToSingle(null);
}
public char GetChar(string name, char valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToChar(null);
}
public string GetString(string name, string valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToString(null);
}
public DateTime GetDateTime(string name, DateTime valueIfNull)
{
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNull : value.ToDateTime(null);
}
public TimeSpan GetTime(string name, TimeSpan valueIfNull)
{
object value = _reader[name];
return value == DBNull.Value ? valueIfNull : (TimeSpan)value;
}
public Guid GetGuid(string name, Guid valueIfNull)
{
object value = _reader[name];
return value == DBNull.Value ? valueIfNull : (Guid)value;
}
public bool GetBoolean(string name, bool fldExists, bool valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
if (value == null || value == DBNull.Value)
return valueIfNullOrFldNotExists;
if (value.ToString().Trim().Equals("1") || value.ToString().Trim().Equals("-1") ||
value.ToString().Trim().ToLower().Equals("true") || value.ToString().Trim().ToLower().Equals("yes"))
return true;
else if (value.ToString().Trim().Equals("0") || value.ToString().Trim().ToLower().Equals("false") ||
value.ToString().Trim().ToLower().Equals("no"))
return false;
else
return value.ToBoolean(null);
}
public byte GetByte(string name, bool fldExists, byte valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToByte(null);
}
public sbyte GetSByte(string name, bool fldExists, sbyte valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToSByte(null);
}
public short GetInt16(string name, bool fldExists, short valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToInt16(null);
}
public ushort GetUInt16(string name, bool fldExists, ushort valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToUInt16(null);
}
public int GetInt32(string name, bool fldExists, int valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToInt32(null);
}
public uint GetUInt32(string name, bool fldExists, uint valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToUInt32(null);
}
public ulong GetUInt64(string name, bool fldExists, ulong valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToUInt64(null);
}
public long GetInt64(string name, bool fldExists, long valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToInt64(null);
}
public decimal GetDecimal(string name, bool fldExists, decimal valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToDecimal(null);
}
public double GetDouble(string name, bool fldExists, double valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToDouble(null);
}
public float GetFloat(string name, bool fldExists, float valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToSingle(null);
}
public char GetChar(string name, bool fldExists, char valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToChar(null);
}
public string GetString(string name, bool fldExists, string valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToString(null);
}
public DateTime GetDateTime(string name, bool fldExists, DateTime valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
IConvertible value = (IConvertible)_reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : value.ToDateTime(null);
}
public TimeSpan GetTime(string name, bool fldExists, TimeSpan valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
object value = _reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : (TimeSpan)value;
}
public Guid GetGuid(string name, bool fldExists, Guid valueIfNullOrFldNotExists)
{
if (fldExists && _table != null && !this.columnExists(name))
return valueIfNullOrFldNotExists;
object value = _reader[name];
return value == DBNull.Value ? valueIfNullOrFldNotExists : (Guid)value;
}
#endregion
public bool Read()
{
return _reader.Read();
}
public void Close()
{
_reader.Close();
_reader.Dispose();
_table.Dispose();
_table = null;
_reader = null;
}
}
#endregion
}

View File

@ -0,0 +1,266 @@
using System;
using System.Xml;
using Ease.Core.Utility;
using System.Configuration;
using Ease.Core.DataAccess;
using System.Collections.Generic;
using Ease.Core.DataAccess.SQL;
//using Ease.Core.DataAccess.Odbc;
//using Ease.Core.DataAccess.OleDb;
using Ease.Core.DataAccess.Oracle;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.IO;
namespace Ease.Core.DataAccess
{
public class DbConfig
{
private static IConfigurationRoot _config;
private string[] _names;
private Dictionary<string, ConnectionNode> _connectionHash = new Dictionary<string, ConnectionNode>();
public string[] Names
{
get { return _names; }
}
public ConnectionNode this[string name]
{
get
{
if (name == null)
throw new Exception("Connection name cannot be null");
ConnectionNode node;
if (!_connectionHash.TryGetValue(name, out node))
throw new Exception("Inavalid connection name: " + name);
return node;
}
}
public static DbConfig GetConfig()
{
DbConfig config = new DbConfig();
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_config = builder.Build();
Dictionary<string, string> valuesBD = _config.GetSection("dbSettings").Get<Dictionary<string, string>>();
config.ConnectionParse(valuesBD);
return config;
}
//protected override void Parse(XmlElement node)
//{
// //List<ConnectionNode> connections = ReadChildren<ConnectionNode>(node, "connection");
// //_names = new string[connections.Count];
// //for (int i = 0; i < connections.Count; i++)
// //{
// // _names[i] = connections[i].Name;
// // _connectionHash[connections[i].Name] = connections[i];
// //}
//}
public void ConnectionParse(Dictionary<string, string> nodes)
{
List<ConnectionNode> connections = new List<ConnectionNode>();
_names = new string[nodes.Count];
int i = 0;
foreach (KeyValuePair<string, string> entry in nodes)
{
_names[i] = entry.Key;
ConnectionNode item = new ConnectionNode();
item.Parse(entry.Value);
_connectionHash.Add(entry.Key, item);
i = i + 1;
}
}
public class ConnectionNode
{
internal void CreateNode(Provider provider, SQLSyntax sqlSyntex, string connectionString)
{
_name = "Dynamic";
_syntax = sqlSyntex;
_provider = provider;
_connectionString = connectionString;
// createNode();
//####
if (_factory == null)
throw new Exception(string.Format("Unsupported Provider: {0}", _provider.ToString()));
}
public ConnectionNode()
{
_connectionString = "";
}
private string _name;
public string Name
{
get { return _name; }
}
private Provider _provider;
internal Provider Provider
{
get { return _provider; }
}
private ConnectionFactory _factory;
public ConnectionFactory Factory
{
get { return _factory; }
}
private string _connectionString;
internal string ConnectionString
{
get { return _connectionString; }
}
private SQLSyntax _syntax;
internal SQLSyntax Syntax
{
get { return _syntax; }
}
public void Parse(string Connvalue)
{
string[] svalue = Connvalue.Split(";");
//CheckRequiredAttributes(node, "name");
//CheckRequiredAttributes(node, "provider");
//CheckRequiredAttributes(node, "connectionString");
//CheckRequiredAttributes(node, "sqlSyntax");
const string provider = "provider";
const string sqlSyntax = "sqlSyntax";
const string passwordKey = "password";
const string EncryptKey = "Cel.Admin";
string[] tokens = Connvalue.Split(';');
Connvalue = string.Empty;
foreach (string token in tokens)
{
string[] tokenValues = token.Split('=');
if (tokenValues.Length > 1)
{
if (tokenValues[0] == provider)
{
#region Provider
switch (tokenValues[1])
{
case "sql":
_provider = Provider.Sql;
break;
case "oraclenative":
_provider = Provider.OracleNative;
break;
case "oracle":
_provider = Provider.Oracle;
break;
case "oledb":
_provider = Provider.OleDb;
break;
case "odbc":
_provider = Provider.Odbc;
break;
default:
throw new Exception("Unsupported Provider: " + tokenValues[1]);
}
#endregion Provider
}
else if (tokenValues[0] == sqlSyntax)
{
switch (tokenValues[1])
{
case "SQL":
_factory = new SqlFactory();
break;
case "Oracle":
_factory = new OracleFactory();
break;
//case Provider.OleDb:
// _factory = new OleDbFactory();
// break;
//case Provider.Odbc:
// _factory = new OdbcFactory();
// break;
default:
break;
}
}
else if (tokenValues[0] == passwordKey)
{
string password = Global.CipherFunctions.Decrypt(EncryptKey, tokenValues[1]);
_connectionString += string.Format(";{0}={1}", passwordKey, password);
}
else
{
_connectionString += _connectionString.Length > 0 ? ";" : "";
_connectionString += token;
}
}
}
}
void createNode()
{
#region Parse Password
const string passwordKey = "password";
const string EncryptKey = "Cel.Admin";
if (_connectionString.IndexOf(passwordKey) != -1)
{
string[] tokens = _connectionString.Split(';');
_connectionString = string.Empty;
foreach (string token in tokens)
{
string[] tokenValues = token.Split('=');
if (tokenValues.Length > 1)
{
if (tokenValues[0] == passwordKey)
{
string password = Global.CipherFunctions.Decrypt(EncryptKey, tokenValues[1]);
_connectionString += string.Format(";{0}={1}", passwordKey, password);
}
else
{
_connectionString += _connectionString.Length > 0 ? ";" : "";
_connectionString += token;
}
}
}
}
#endregion
}
}
}
}

View File

@ -0,0 +1,296 @@
using System;
using System.Data;
using System.Globalization;
namespace Ease.Core.DataAccess
{
#region DataAccess: MakeSQL
public sealed class SQLParser
{
#region Declaraion & Constructor
private static SQLSyntax _sqlSyntax;
private SQLParser()
{
_sqlSyntax = SQLSyntax.SQL;
}
#endregion
#region DateTime Formatting Functions
static string GetDateLiteral(DateTime dt)
{
string s = string.Empty;
switch (_sqlSyntax)
{
case SQLSyntax.Access:
s = "#" + dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) + "#";
break;
case SQLSyntax.Oracle:
s = "TO_DATE('" + dt.ToString("dd MM yyyy", CultureInfo.InvariantCulture) + "', '" + "DD MM YYYY" +
"')";
break;
case SQLSyntax.Informix:
s = string.Format("DATETIME ({0}) YEAR TO DAY",
dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
break;
default:
s = "'" + dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) + "'";
break;
}
return s;
}
static string GetDateTimeLiteral(DateTime dt)
{
string s = string.Empty;
switch (_sqlSyntax)
{
case SQLSyntax.Access:
s = "#" + dt.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture) + "#";
break;
case SQLSyntax.Oracle:
s = "TO_DATE('" + dt.ToString("dd MM yyyy HH mm ss", CultureInfo.InvariantCulture) +
"', 'DD MM YYYY HH24 MI SS')";
break;
case SQLSyntax.Informix:
s = string.Format("DATETIME ({0}) YEAR TO SECOND",
dt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
break;
default:
s = "'" + dt.ToString("dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture) + "'";
break;
}
return s;
}
static string GetTimeLiteral(DateTime dt)
{
string s = string.Empty;
switch (_sqlSyntax)
{
case SQLSyntax.Access:
s = "#" + dt.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + "#";
break;
case SQLSyntax.Oracle:
s = "TO_DATE('" + dt.ToString("HH mm ss", CultureInfo.InvariantCulture) + "', 'HH24 MI SS')";
break;
case SQLSyntax.Informix:
s = string.Format("DATETIME ({0}) HOUR TO SECOND",
dt.ToString("HH:mm:ss", CultureInfo.InvariantCulture));
break;
default:
s = "'" + dt.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + "'";
break;
}
return s;
}
#endregion
#region Make SQL function
/// <summary>
/// This function returns actual T-SQL command.
/// </summary>
/// <param name="sqlSyntax">T-SQL command will be on database Oracle, SQL Server, Access, Informix.</param>
/// <param name="sql">T-SQL command according to CEL style.</param>
/// <param name="args">Comma delimited value according to CEL style.</param>
/// <returns>Return the actual T-SQL command.</returns>
public static string MakeSQL(SQLSyntax sqlSyntax, string sql, params object[] args)
{
_sqlSyntax = sqlSyntax;
return MakeSQL(sql, args);
}
/// <summary>
/// This function returns actual T-SQL command.
/// </summary>
/// <param name="sql">T-SQL command according to CEL style.</param>
/// <param name="args">Comma delimited value according to CEL style.</param>
/// <returns>Return the actual T-SQL command.</returns>
public static string MakeSQL(string sql, params object[] args)
{
if (args.Length <= 0)
return sql;
int argIndex = -1;
string retSQL = string.Empty;
string[] argSQL = new string[args.Length];
int i = sql.IndexOf("%");
while (i != -1)
{
retSQL = retSQL + sql.Substring(0, i);
if (i == sql.Length - 1)
throw new InvalidExpressionException("Invalid place holder character.");
string c = sql.Substring(i + 1, 1);
sql = sql.Substring(i + 2);
if (c.IndexOfAny(new char[] { '%', '{' }) != -1)
{
switch (c)
{
case "%":
retSQL = retSQL + "%";
break;
case "{":
int next = sql.IndexOf("}");
if (next < 1)
throw new InvalidExpressionException("Invalid rrdinal variable.");
int ord = Convert.ToInt32(sql.Substring(0, next));
if (ord < 0 || ord > argIndex)
throw new IndexOutOfRangeException("Invalid rrdinal variable.");
retSQL = retSQL + argSQL[ord];
sql = sql.Substring(next + 1);
break;
}
}
else if (c.IndexOfAny(new char[] { 's', 'n', 'd', 't', 'T', 'D', 'b', 'q', 'u' }) != -1)
{
if (++argIndex > args.Length - 1)
throw new ArgumentException("Too few arguments passed.");
if (args[argIndex] == null)
{
argSQL[argIndex] = "NULL";
}
else
{
try
{
switch (c)
{
case "s":
string s = Convert.ToString(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = "'" + s.Replace("'", "''") + "'";
break;
case "u":
string u = Convert.ToString(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = "N'" + u.Replace("'", "''") + "'";
break;
case "n":
decimal n = Convert.ToDecimal(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = n.ToString(CultureInfo.InvariantCulture);
break;
case "d":
DateTime d = Convert.ToDateTime(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = GetDateLiteral(d);
break;
case "t":
DateTime t = Convert.ToDateTime(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = GetTimeLiteral(t);
break;
case "T":
string T = Convert.ToString(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = "'" + T.Replace("'", "''") + "'";
break;
case "D":
DateTime D = Convert.ToDateTime(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = GetDateTimeLiteral(D);
break;
case "b":
bool b = Convert.ToBoolean(args[argIndex], CultureInfo.InvariantCulture);
if (_sqlSyntax == SQLSyntax.Access)
argSQL[argIndex] = b.ToString(CultureInfo.InvariantCulture);
else
argSQL[argIndex] = (b ? "1" : "0");
break;
case "q":
string q = Convert.ToString(args[argIndex], CultureInfo.InvariantCulture);
argSQL[argIndex] = q;
break;
}
}
catch
{
throw new ArgumentException(string.Format("Invalid argument no: {0}", argIndex));
}
}
retSQL = retSQL + argSQL[argIndex];
}
else
{
throw new InvalidExpressionException("Invalid place holder character.");
}
i = sql.IndexOf("%");
}
retSQL = retSQL + sql;
// Handle the (==)
i = retSQL.IndexOf("==");
while (i != -1)
{
string rVal = retSQL.Substring(i + 2).Trim().Substring(0);
if (rVal.ToUpper().StartsWith("NULL"))
retSQL = retSQL.Substring(0, i) + " IS " + retSQL.Substring(i + 2);
else
retSQL = retSQL.Substring(0, i) + "=" + retSQL.Substring(i + 2);
i = retSQL.IndexOf("==", i + 2);
}
//Handle the (<>)
i = retSQL.IndexOf("<>");
while (i != -1)
{
string rVal = retSQL.Substring(i + 2).Trim().Substring(1);
if (rVal.ToUpper().StartsWith("NULL"))
retSQL = retSQL.Substring(0, i) + " IS NOT " + retSQL.Substring(i + 2);
i = retSQL.IndexOf("<>", i + 2);
}
return retSQL;
}
#endregion
#region TagSQL Function
/// <summary>
/// This function return T-SQL command by adding WHERE/AND depending on commandText.
/// </summary>
/// <param name="commandText">Previous T-SQL command.</param>
/// <returns>Return T-SQL command after addition of WHERE/AND maintaining the space.</returns>
public static string TagSQL(string commandText)
{
return string.Format("{0} {1} ", commandText.Trim(), (commandText.Trim().Length <= 0 ? "WHERE" : "AND"));
}
#endregion
}
#endregion
}

View File

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace Ease.Core.DataAccess
{
#region Null Handler
public class NullHandler
{
private IDataReader _reader;
public NullHandler()
{
}
public static object GetNullValue(int Value)
{
if (Value <= 0)
{
return null;
}
else
{
return Value;
}
}
public static object GetNullValue(DateTime Value)
{
if (DateTime.MinValue == Value)
{
return null;
}
else
{
return Value;
}
}
public static object GetNullValue(string Value)
{
if (Value.Length <= 0)
{
return null;
}
else
{
return Value;
}
}
public NullHandler(IDataReader reader)
{
_reader = reader;
}
public IDataReader Reader
{
get { return _reader; }
}
public bool IsNull(int index)
{
return _reader.IsDBNull(index);
}
#region Default Null Values
public int GetInt32(int i)
{
return _reader.IsDBNull(i) ? 0 : _reader.GetInt32(i);
}
public byte GetByte(int i)
{
return _reader.IsDBNull(i) ? (byte)0 : _reader.GetByte(i);
}
public decimal GetDecimal(int i)
{
return _reader.IsDBNull(i) ? 0 : _reader.GetDecimal(i);
}
public decimal GetDecimal(string sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (decimal)0 : Convert.ToDecimal(_reader[sFieldName]);
}
public long GetInt64(int i)
{
return _reader.IsDBNull(i) ? (long)0 : _reader.GetInt64(i);
}
public double GetDouble(int i)
{
return _reader.IsDBNull(i) ? 0 : _reader.GetDouble(i);
}
public bool GetBoolean(int i)
{
return _reader.IsDBNull(i) ? false : _reader.GetBoolean(i);
}
public Guid GetGuid(int i)
{
return _reader.IsDBNull(i) ? Guid.Empty : _reader.GetGuid(i);
}
public DateTime GetDateTime(int i)
{
return _reader.IsDBNull(i) ? DateTime.MinValue : _reader.GetDateTime(i);
}
public float GetFloat(int i)
{
return _reader.IsDBNull(i) ? 0 : _reader.GetFloat(i);
}
public string GetString(int i)
{
return _reader.IsDBNull(i) ? null : _reader.GetString(i);
}
public char GetChar(int i)
{
return _reader.IsDBNull(i) ? '\0' : _reader.GetChar(i);
}
public short GetInt16(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (Int16)0 : Convert.ToInt16(_reader[sFieldName]);
}
public int GetInt32(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (Int32)0 : Convert.ToInt32(_reader[sFieldName]);
}
public byte GetByte(String sFieldName)
{
return _reader[sFieldName] == DBNull.Value ? (byte)0 : Convert.ToByte(_reader[sFieldName]);
}
public long GetInt64(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (Int64)0 : Convert.ToInt64(_reader[sFieldName]);
}
public Double GetDouble(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (Double)0 : Convert.ToDouble(_reader[sFieldName]);
}
public bool GetBoolean(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? false : Convert.ToBoolean(_reader[sFieldName]);
}
public DateTime GetDateTime(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? DateTime.MinValue : Convert.ToDateTime(_reader[sFieldName]);
}
public char GetChar(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? '\0' : Convert.ToChar(_reader[sFieldName]);
}
public string GetString(String sFieldName)
{
return (_reader[sFieldName] == DBNull.Value) ? (string)"" : Convert.ToString(_reader[sFieldName]);
}
//public Image GetImage(String sFieldName)
//{
// try
// {
// byte[] imageData = null;
// long byteSize = 0;
// byteSize = _reader.GetBytes(_reader.GetOrdinal(sFieldName), 0, null, 0, 0);
// imageData = new byte[byteSize];
// long bytesread = 0;
// int curpos = 0, chunkSize = 500;
// while (bytesread < byteSize)
// {
// // chunkSize is an arbitrary application defined value
// bytesread += _reader.GetBytes(_reader.GetOrdinal(sFieldName), curpos, imageData, curpos, chunkSize);
// curpos += chunkSize;
// }
// byte[] imgData = imageData;
// MemoryStream ms = new MemoryStream(imgData);
// Image oImage = Image.FromStream((Stream)ms);
// return oImage;
// }
// catch (Exception ex)
// {
// throw new Exception("Failed to get Image: " + ex.Message);
// }
//}
#endregion
#region Parameterized Null Value
public int GetInt32(int i, int valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetInt32(i);
}
public byte GetByte(int i, byte valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetByte(i);
}
public decimal GetDecimal(int i, decimal valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetDecimal(i);
}
public long GetInt64(int i, long valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetInt64(i);
}
public double GetDouble(int i, double valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetDouble(i);
}
public bool GetBoolean(int i, bool valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetBoolean(i);
}
public Guid GetGuid(int i, Guid valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetGuid(i);
}
public DateTime GetDateTime(int i, DateTime valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetDateTime(i);
}
public float GetFloat(int i, float valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetFloat(i);
}
public string GetString(int i, string valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetString(i);
}
public char GetChar(int i, char valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetChar(i);
}
public short GetInt16(int i, short valueIfNull)
{
return _reader.IsDBNull(i) ? valueIfNull : _reader.GetInt16(i);
}
#endregion
}
#endregion
}

View File

@ -0,0 +1,52 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 17/04/2009 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Data;
using System.Collections;
using System.Configuration;
using Ease.Core.Utility;
using System.Data.OracleClient;
namespace Ease.Core.DataAccess.Oracle
{
#region DataAccess: Oracle Connection Factory
public sealed class OracleFactory : ConnectionFactory
{
/// <summary>
/// Create an instance of IDbConnection for oracle using default connectionstring.
/// </summary>
/// <returns>Retuen an instance of OracleConnection.</returns>
public override System.Data.IDbConnection CreateConnection()
{
return new OracleConnection(base.ConnectionNode.ConnectionString);
}
/// <summary>
/// Create an instance of IDbConnection for oracle using ConnectionContext.
/// </summary>
/// <param name="context">Valid ConnectionContext.</param>
/// <returns>Return instatnce of OracleConnection.</returns>
public override System.Data.IDbConnection CreateConnection(ConnectionContext context)
{
if (context == null || context.ContextKey.Length <= 0)
throw new Exception("There is no key in the Connection Context");
return new OracleConnection(ConnectionFactory.ContextConnection(context).ConnectionNode.ConnectionString);
}
internal OracleFactory()
{
}
}
#endregion
}

View File

@ -0,0 +1,335 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 17/04/2009 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Data;
using System.Data.OracleClient;
using Ease.Core.DataAccess;
using Ease.Core.Utility;
namespace Ease.CoreV35.DataAccess.Oracle
{
#region DataAccess: Oracle Helper
public sealed class OracleHelperExtension
{
private OracleHelperExtension()
{
}
#region Fill Data set
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the
/// DataReader records.</param>
/// <param name="from">The quantity of records skipped before placing
/// values on the DataReader on the DataSet.</param>
/// <param name="count">The maximum quantity of records alloed to fill on the
/// DataSet.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName, int from, int count)
{
DataAccessHelper.Fill(dataReader, dataSet, tableName, from, count);
}
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the DataReader records.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName)
{
OracleHelperExtension.Fill(dataReader, dataSet, tableName, 0, 0);
}
#endregion
#region Parameter
/// <summary>
/// Return OracleParameter object according to parameter.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</direction>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateParam(OracleType pType, ParameterDirection direction, object pValue)
{
return OracleHelperExtension.CreateParam(string.Empty, pType, direction, pValue);
}
/// <summary>
/// Return OracleParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateParam(string pName, OracleType pType, ParameterDirection direction)
{
return OracleHelperExtension.CreateParam(pName, pType, direction, null);
}
/// <summary>
/// Return OracleParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</direction>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateParam(string pName, OracleType pType, ParameterDirection direction,
object pValue)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = direction;
if (pType == OracleType.VarChar)
param.Size = 1000;
param.Value = pValue;
return param;
}
/// <summary>
/// Return OracleParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateParam(string pName, OracleType pType, ParameterDirection direction,
int size, object pValue)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = direction;
param.Size = size;
param.Value = pValue;
return param;
}
#endregion
#region Input Parameter
/// <summary>
/// Return input direction OracleParameter object.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateInParam(OracleType pType, object pValue)
{
return OracleHelperExtension.CreateInParam(string.Empty, pType, pValue);
}
/// <summary>
/// Return input direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateInParam(string pName, OracleType pType)
{
return OracleHelperExtension.CreateInParam(pName, pType, null);
}
/// <summary>
/// Return input direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateInParam(string pName, OracleType pType, object pValue)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = ParameterDirection.Input;
if (pType == OracleType.VarChar)
param.Size = 1000;
param.Value = pValue;
return param;
}
/// <summary>
/// Return input direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateInParam(string pName, OracleType pType, object pValue, int size)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = ParameterDirection.Input;
param.Size = size;
param.Value = pValue;
return param;
}
#endregion
#region Output Parameter
/// <summary>
/// Return output direction OracleParameter object.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateOutParam(OracleType pType, object pValue)
{
return OracleHelperExtension.CreateOutParam(string.Empty, pType, pValue);
}
/// <summary>
/// Return output direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateOutParam(string pName, OracleType pType)
{
return OracleHelperExtension.CreateOutParam(pName, pType, null);
}
/// <summary>
/// Return output direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateOutParam(string pName, OracleType pType, object pValue)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = ParameterDirection.Output;
if (pType == OracleType.VarChar)
{
param.Size = 1000;
}
param.Value = pValue;
return param;
}
/// <summary>
/// Return output direction OracleParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of OracleParameter.</returns>
public static OracleParameter CreateOutParam(string pName, OracleType pType, object pValue, int size)
{
OracleParameter param = new OracleParameter(pName, pType);
param.Direction = ParameterDirection.Output;
param.Size = size;
param.Value = pValue;
return param;
}
#endregion
#region Add Parameter
public static OracleCommand CreateCommand(string name)
{
OracleCommand command = new OracleCommand(name);
return command;
}
public static void AddParameter(OracleCommand command, string name, OracleType type,
ParameterDirection direction, object Value)
{
OracleParameter param = command.CreateParameter();
param.ParameterName = name;
param.OracleType = type;
param.Direction = direction;
if (type == OracleType.VarChar)
param.Size = 4000;
param.Value = Value;
command.Parameters.Add(param);
}
public static void AddParameter(OracleCommand command, string name, OracleType type,
ParameterDirection direction)
{
OracleHelperExtension.AddParameter(command, name, type, direction, null);
}
#endregion
#region GetBlob
public static OracleLob GetBlob(TransactionContext tc, byte[] bytes)
{
OracleLob tblob = GetTempBlob(tc);
tblob.BeginBatch(OracleLobOpenMode.ReadWrite);
tblob.Write(bytes, 0, bytes.Length);
tblob.EndBatch();
return tblob;
}
public static OracleLob GetTempBlob(TransactionContext tc)
{
OracleCommand command =
new OracleCommand("DECLARE t BLOB; BEGIN DBMS_LOB.CREATETEMPORARY(t, false, 0); :tempblob := t; END;");
AddParameter(command, "tempblob", OracleType.Blob, ParameterDirection.Output);
tc.PrepareCommand(command);
command.ExecuteNonQuery();
return (OracleLob) (command.Parameters[0]).Value;
}
#endregion
#region private function
private static object GetValue(object fieldValue, Type fieldType)
{
switch (fieldType.Name)
{
case "Int16":
case "Int32":
case "Int64":
if (fieldValue == DBNull.Value)
return 0;
else
return fieldValue;
}
return fieldValue;
}
#endregion
}
#endregion
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,690 @@
using System;
using System.Data;
using System.Globalization;
namespace Ease.Core.DataAccess
{
#region DataAccess: Data Handler
/// <summary>
/// Handle the null value
/// </summary>
public class RowReader
{
private DataRow _row;
public RowReader(DataRow row)
{
_row = row;
}
#region Get ID
public long GetID(Type[] types, params int[] fldIdxs)
{
if (types == null || fldIdxs == null || types.Length != fldIdxs.Length)
throw new Exception("Invalid use of array for ID.");
string value = string.Empty;
foreach (int fldIdx in fldIdxs)
{
if (_row[fldIdx] == null || _row[fldIdx] == DBNull.Value)
return long.MinValue;
value += value.Length > 0 ? "|" : "";
value += this.GetID(types[fldIdx], _row[fldIdx]);
}
return long.Parse(value);
}
public long GetID(Type[] types, params string[] names)
{
if (types == null || names == null || types.Length != names.Length)
throw new Exception("Invalid use of array for ID.");
int fldIdx = -1;
string value = string.Empty;
foreach (string name in names)
{
fldIdx++;
if (_row[name] == null || _row[name] == DBNull.Value)
return long.MinValue;
value += value.Length > 0 ? "|" : "";
value += this.GetID(types[fldIdx], _row[name]);
}
return long.Parse(value);
}
private string GetID(Type fldType, object fldValue)
{
if (fldType == typeof(int) || fldType == typeof(uint))
return string.Format("i:{0}", fldValue);
else if (fldType == typeof(long) || fldType == typeof(ulong) || fldType == typeof(decimal))
return string.Format("l:{0}", fldValue);
else
throw new Exception("Invalid use of type for ID");
}
#endregion
#region Get Null value
public static bool? GetNullValue(bool value, bool nullIfValue)
{
return (value == nullIfValue) ? null : (bool?)value;
}
public static byte? GetNullValue(byte value, byte nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static sbyte? GetNullValue(sbyte value, sbyte nullIfValue)
{
return (value == nullIfValue) ? null : (sbyte?)value;
}
public static short? GetNullValue(short value, short nullIfValue)
{
return (value == nullIfValue) ? null : (short?)value;
}
public static ushort? GetNullValue(ushort value, ushort nullIfValue)
{
return (value == nullIfValue) ? null : (ushort?)value;
}
public static int? GetNullValue(int value, int nullIfValue)
{
return (value == nullIfValue) ? null : (int?)value;
}
public static uint? GetNullValue(uint value, uint nullIfValue)
{
return (value == nullIfValue) ? null : (uint?)value;
}
public static ulong? GetNullValue(ulong value, ulong nullIfValue)
{
return (value == nullIfValue) ? null : (ulong?)value;
}
public static long? GetNullValue(long value, long nullIfValue)
{
return (value == nullIfValue) ? null : (long?)value;
}
public static decimal? GetNullValue(decimal value, decimal nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static double? GetNullValue(double value, double nullIfValue)
{
return (value == nullIfValue) ? null : (byte?)value;
}
public static float? GetNullValue(float value, float nullIfValue)
{
return (value == nullIfValue) ? null : (float?)value;
}
public static char? GetNullValue(char value, char nullIfValue)
{
return (value == nullIfValue) ? null : (char?)value;
}
public static object GetNullValue(string value, string nullIfValue)
{
return (value == nullIfValue) ? null : value;
}
public static DateTime? GetNullValue(DateTime value, DateTime nullIfValue)
{
return (value == nullIfValue) ? null : (DateTime?)value;
}
public static Guid? GetNullValue(Guid value, Guid nullIfValue)
{
return (value == nullIfValue) ? null : (Guid?)value;
}
public static bool? GetNullValue(bool? value)
{
return (value == null || value == false) ? null : (bool?)value;
}
public static byte? GetNullValue(byte? value)
{
return (value == null || value == 0) ? null : (byte?)value;
}
public static sbyte? GetNullValue(sbyte? value)
{
return (value == null || value == 0) ? null : (sbyte?)value;
}
public static short? GetNullValue(short? value)
{
return (value == null || value == 0) ? null : (short?)value;
}
public static ushort? GetNullValue(ushort? value)
{
return (value == null || value == 0) ? null : (ushort?)value;
}
public static int? GetNullValue(int? value)
{
return (value == null || value == 0) ? null : (int?)value;
}
public static uint? GetNullValue(uint? value)
{
return (value == null || value == 0) ? null : (uint?)value;
}
public static ulong? GetNullValue(ulong? value)
{
return (value == null || value == 0) ? null : (ulong?)value;
}
public static long? GetNullValue(long? value)
{
return (value == null || value == 0) ? null : (long?)value;
}
public static decimal? GetNullValue(decimal? value)
{
return (value == null || value == 0) ? null : (decimal?)value;
}
public static double? GetNullValue(double? value)
{
return (value == null || value == 0) ? null : (double?)value;
}
public static float? GetNullValue(float? value)
{
return (value == null || value == 0) ? null : (float?)value;
}
public static char? GetNullValue(char? value)
{
return (value == null || (byte)value == 0) ? null : (char?)value;
}
public static string GetNullValue(string value)
{
return (string.IsNullOrEmpty(value)) ? null : value;
}
public static DateTime? GetNullValue(DateTime? value)
{
return (value == null || value == DateTime.MinValue) ? null : (DateTime?)value;
}
public static Guid? GetNullValue(Guid? value)
{
return value;
}
public static Object GetNullValue(long value)
{
if (value == null || value == long.MinValue)
return null;
return value;
}
#endregion
#region Default Null Values
public bool? GetBoolean(int i)
{
IConvertible value = (IConvertible)_row[i];
if (value == null || value == DBNull.Value)
return null;
if (value.ToString().Trim().Equals("1") || value.ToString().Trim().Equals("-1") ||
value.ToString().Trim().ToLower().Equals("true") || value.ToString().Trim().ToLower().Equals("yes"))
return true;
else if (value.ToString().Trim().Equals("0") || value.ToString().Trim().ToLower().Equals("false") ||
value.ToString().Trim().ToLower().Equals("no"))
return false;
else
return (bool?)value.ToBoolean(null);
}
public byte? GetByte(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (byte?)value.ToByte(null);
}
public sbyte? GetSByte(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (sbyte?)value.ToSByte(null);
}
public short? GetInt16(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (short?)value.ToInt16(null);
}
public ushort? GetUInt16(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (ushort?)value.ToUInt16(null);
}
public int? GetInt32(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (int?)value.ToInt32(null);
}
public uint? GetUInt32(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (uint?)value.ToUInt32(null);
}
public long? GetInt64(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (long?)value.ToInt64(null);
}
public ulong? GetUInt64(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (ulong?)value.ToUInt64(null);
}
public decimal? GetDecimal(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (decimal?)value.ToDecimal(null);
}
public double? GetDouble(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (double?)value.ToDouble(null);
}
public float? GetFloat(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (float?)value.ToSingle(null);
}
public char? GetChar(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (char?)value.ToChar(null);
}
public string GetString(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : value.ToString(null);
}
public DateTime? GetDateTime(int i)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? null : (DateTime?)value.ToDateTime(null);
}
public Guid? GetGuid(int i)
{
object value = _row[i];
return value == DBNull.Value ? null : (Guid?)value;
}
public byte[] GetLob(int i)
{
return (byte[])(_row.IsNull(i) ? (byte[])null : _row[i]);
}
public bool? GetBoolean(string name)
{
IConvertible value = (IConvertible)_row[name];
if (value == null || value == DBNull.Value)
return null;
if (value.ToString().Trim().Equals("1") || value.ToString().Trim().Equals("-1") ||
value.ToString().Trim().ToLower().Equals("true") || value.ToString().Trim().ToLower().Equals("yes"))
return true;
else if (value.ToString().Trim().Equals("0") || value.ToString().Trim().ToLower().Equals("false") ||
value.ToString().Trim().ToLower().Equals("no"))
return false;
else
return (bool?)value.ToBoolean(null);
}
public byte? GetByte(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (byte?)value.ToByte(null);
}
public sbyte? GetSByte(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (sbyte?)value.ToSByte(null);
}
public short? GetInt16(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (short?)value.ToInt16(null);
}
public ushort? GetUInt16(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (ushort?)value.ToUInt16(null);
}
public int? GetInt32(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? (int?)null : (int?)value.ToInt32(null);
}
public uint? GetUInt32(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (uint?)value.ToUInt32(null);
}
public long? GetInt64(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (long?)value.ToInt64(null);
}
public ulong? GetUInt64(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (ulong?)value.ToUInt64(null);
}
public decimal? GetDecimal(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (decimal?)value.ToDecimal(null);
}
public double? GetDouble(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (double?)value.ToDouble(null);
}
public float? GetFloat(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (float?)value.ToSingle(null);
}
public char? GetChar(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (char?)value.ToChar(null);
}
public string GetString(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : value.ToString(null);
}
public DateTime? GetDateTime(string name)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? null : (DateTime?)value.ToDateTime(null);
}
public Guid? GetGuid(string name)
{
object value = _row[name];
return value == DBNull.Value ? null : (Guid?)value;
}
public byte[] GetLob(string name)
{
return (byte[])(_row[name] == DBNull.Value ? (byte[])null : _row[name]);
}
#endregion
#region Parameterized Null Value
public bool GetBoolean(int i, bool valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
if (value == null || value == DBNull.Value)
return valueIfNull;
if (value.ToString().Trim().Equals("1") || value.ToString().Trim().Equals("-1") ||
value.ToString().Trim().ToLower().Equals("true") || value.ToString().Trim().ToLower().Equals("yes"))
return true;
else if (value.ToString().Trim().Equals("0") || value.ToString().Trim().ToLower().Equals("false") ||
value.ToString().Trim().ToLower().Equals("no"))
return false;
else
return value.ToBoolean(null);
}
public byte GetByte(int i, byte valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToByte(null);
}
public sbyte GetSByte(int i, sbyte valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToSByte(null);
}
public short GetInt16(int i, short valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToInt16(null);
}
public ushort GetUInt16(int i, ushort valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToUInt16(null);
}
public int GetInt32(int i, int valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToInt32(null);
}
public uint GetUInt32(int i, uint valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToUInt32(null);
}
public ulong GetUInt64(int i, ulong valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToUInt64(null);
}
public long GetInt64(int i, long valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToInt64(null);
}
public decimal GetDecimal(int i, decimal valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToDecimal(null);
}
public double GetDouble(int i, double valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToDouble(null);
}
public float GetFloat(int i, float valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToSingle(null);
}
public char GetChar(int i, char valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToChar(null);
}
public string GetString(int i, string valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToString(null);
}
public DateTime GetDateTime(int i, DateTime valueIfNull)
{
IConvertible value = (IConvertible)_row[i];
return value == DBNull.Value ? valueIfNull : value.ToDateTime(null);
}
public Guid GetGuid(int i, Guid valueIfNull)
{
object value = _row[i];
return value == DBNull.Value ? valueIfNull : (Guid)value;
}
public bool GetBoolean(string name, bool valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
if (value == null || value == DBNull.Value)
return valueIfNull;
if (value.ToString().Trim().Equals("1") || value.ToString().Trim().Equals("-1") ||
value.ToString().Trim().ToLower().Equals("true") || value.ToString().Trim().ToLower().Equals("yes"))
return true;
else if (value.ToString().Trim().Equals("0") || value.ToString().Trim().ToLower().Equals("false") ||
value.ToString().Trim().ToLower().Equals("no"))
return false;
else
return value.ToBoolean(null);
}
public byte GetByte(string name, byte valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToByte(null);
}
public sbyte GetSByte(string name, sbyte valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToSByte(null);
}
public short GetInt16(string name, short valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToInt16(null);
}
public ushort GetUInt16(string name, ushort valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt16(null);
}
public int GetInt32(string name, int valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToInt32(null);
}
public uint GetUInt32(string name, uint valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt32(null);
}
public ulong GetUInt64(string name, ulong valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToUInt64(null);
}
public long GetInt64(string name, long valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToInt64(null);
}
public decimal GetDecimal(string name, decimal valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToDecimal(null);
}
public double GetDouble(string name, double valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToDouble(null);
}
public float GetFloat(string name, float valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToSingle(null);
}
public char GetChar(string name, char valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToChar(null);
}
public string GetString(string name, string valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToString(null);
}
public DateTime GetDateTime(string name, DateTime valueIfNull)
{
IConvertible value = (IConvertible)_row[name];
return value == DBNull.Value ? valueIfNull : value.ToDateTime(null);
}
public Guid GetGuid(string name, Guid valueIfNull)
{
object value = _row[name];
return value == DBNull.Value ? valueIfNull : (Guid)value;
}
#endregion
}
#endregion
}

View File

@ -0,0 +1,56 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Source: UIP |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Data;
using Ease.Core.Utility;
using System.Collections;
using System.Configuration;
using Microsoft.Data.SqlClient;
namespace Ease.Core.DataAccess.SQL
{
#region DataAccess: SQL Connection Factory
/// <summary>
/// Summary description for SQLFactory.
/// </summary>
public sealed class SqlFactory : ConnectionFactory
{
/// <summary>
/// Create an instance of IDbConnection for MS SQL using default connectionstring.
/// </summary>
/// <returns>Retuen an instance of IDbConnection for MS SQL.</returns>
public override System.Data.IDbConnection CreateConnection()
{
return new SqlConnection(base.ConnectionNode.ConnectionString);
}
/// <summary>
/// Create an instance of IDbConnection for MS SQL using ConnectionContext.
/// </summary>
/// <param name="context">Valid ConnectionContext.</param>
/// <returns>Return instatnce of IDbConnection for MS SQL.</returns>
public override System.Data.IDbConnection CreateConnection(ConnectionContext context)
{
if (context == null || context.ContextKey.Length <= 0)
throw new Exception("There is no key in the Connection Context");
return new SqlConnection(ConnectionFactory.ContextConnection(context).ConnectionNode.ConnectionString);
}
internal SqlFactory()
{
}
}
#endregion
}

View File

@ -0,0 +1,306 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Data;
using Ease.Core.Utility;
using Microsoft.Data.SqlClient;
namespace Ease.Core.DataAccess.SQL
{
#region DataAccess: SQL Helper Extension
public sealed class SqlHelperExtension
{
#region Constructor
private SqlHelperExtension()
{
}
#endregion
#region Fill Data set
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the
/// DataReader records.</param>
/// <param name="from">The quantity of records skipped before placing
/// values on the DataReader on the DataSet.</param>
/// <param name="count">The maximum quantity of records alloed to fill on the
/// DataSet.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName, int from, int count)
{
DataAccessHelper.Fill(dataReader, dataSet, tableName, from, count);
}
/// <summary>
/// Fills a typed DataSet using the DataReader's current result. This method
/// allows paginated access to the database.
/// </summary>
/// <param name="dataReader">The DataReader used to fetch the values.</param>
/// <param name="dataSet">The DataSet used to store the values.</param>
/// <param name="tableName">The name of the DataSet table used to add the DataReader records.</param>
public static void Fill(IDataReader dataReader, DataSet dataSet, string tableName)
{
SqlHelperExtension.Fill(dataReader, dataSet, tableName, 0, 0);
}
#endregion
#region Parameter
/// <summary>
/// Return SqlParameter object according to parameter.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</direction>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateParam(SqlDbType pType, ParameterDirection direction, object pValue)
{
return SqlHelperExtension.CreateParam(string.Empty, pType, direction, pValue);
}
/// <summary>
/// Return SqlParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateParam(string pName, SqlDbType pType, ParameterDirection direction)
{
return SqlHelperExtension.CreateParam(pName, pType, direction, null);
}
/// <summary>
/// Return SqlParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</direction>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateParam(string pName, SqlDbType pType, ParameterDirection direction,
object pValue)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = direction;
if (pType == SqlDbType.VarChar)
param.Size = 1000;
param.Value = pValue;
return param;
}
/// <summary>
/// Return SqlParameter object according to parameter.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="direction">Direction of parameter.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateParam(string pName, SqlDbType pType, ParameterDirection direction,
object pValue, int size)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = direction;
param.Size = size;
if ((pType == SqlDbType.Char || pType == SqlDbType.VarChar || pType == SqlDbType.Text
|| pType == SqlDbType.NChar || pType == SqlDbType.NText || pType == SqlDbType.NVarChar) && size > 0)
{
string value = Global.StringFuncions.IsEmptyOrNull(pValue) ? string.Empty : pValue.ToString();
param.Value = Global.StringFuncions.Left(value, size);
}
else
{
param.Value = pValue;
}
return param;
}
#endregion
#region Input Parameter
/// <summary>
/// Return input direction SqlParameter object.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateInParam(SqlDbType pType, object pValue)
{
return SqlHelperExtension.CreateInParam(string.Empty, pType, pValue);
}
/// <summary>
/// Return input direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateInParam(string pName, SqlDbType pType)
{
return SqlHelperExtension.CreateInParam(pName, pType, null);
}
/// <summary>
/// Return input direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateInParam(string pName, SqlDbType pType, object pValue)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = ParameterDirection.Input;
if (pType == SqlDbType.VarChar)
param.Size = 1000;
param.Value = pValue;
return param;
}
/// <summary>
/// Return input direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateInParam(string pName, SqlDbType pType, object pValue, int size)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = ParameterDirection.Input;
param.Size = size;
if ((pType == SqlDbType.Char || pType == SqlDbType.VarChar || pType == SqlDbType.Text
|| pType == SqlDbType.NChar || pType == SqlDbType.NText || pType == SqlDbType.NVarChar) && size > 0)
{
string value = Global.StringFuncions.IsEmptyOrNull(pValue) ? string.Empty : pValue.ToString();
param.Value = Global.StringFuncions.Left(value, size);
}
else
{
param.Value = pValue;
}
return param;
}
#endregion
#region Output Parameter
/// <summary>
/// Return output direction SqlParameter object.
/// </summary>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateOutParam(SqlDbType pType, object pValue)
{
return SqlHelperExtension.CreateOutParam(string.Empty, pType, pValue);
}
/// <summary>
/// Return output direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateOutParam(string pName, SqlDbType pType)
{
return SqlHelperExtension.CreateOutParam(pName, pType, null);
}
/// <summary>
/// Return output direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateOutParam(string pName, SqlDbType pType, object pValue)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = ParameterDirection.Output;
if (pType == SqlDbType.VarChar)
param.Size = 1000;
param.Value = pValue;
return param;
}
/// <summary>
/// Return output direction SqlParameter object.
/// </summary>
/// <param name="pName">Name of parameter.</param>
/// <param name="pType">Type of data.</param>
/// <param name="pValue">Value of parametetr.</param>
/// <param name="size">If varchar then lenth of value.</param>
/// <returns>Instatnce of SqlParameter.</returns>
public static SqlParameter CreateOutParam(string pName, SqlDbType pType, object pValue, int size)
{
SqlParameter param = new SqlParameter(pName, pType);
param.Direction = ParameterDirection.Output;
param.Size = size;
param.Value = pValue;
return param;
}
#endregion
#region Add Parameter
public static SqlCommand CreateCommand(string name)
{
SqlCommand command = new SqlCommand(name);
return command;
}
public static void AddParameter(SqlCommand command, string name, SqlDbType type, ParameterDirection direction,
object value)
{
SqlParameter param = command.CreateParameter();
param.ParameterName = name;
param.SqlDbType = type;
param.Direction = direction;
if (type == SqlDbType.VarChar)
param.Size = 1000;
param.Value = value;
command.Parameters.Add(param);
}
public static void AddParameter(SqlCommand command, string name, SqlDbType type, ParameterDirection direction)
{
SqlHelperExtension.AddParameter(command, name, type, direction, null);
}
#endregion
}
#endregion
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,349 @@
using System;
using System.Data;
using Ease.Core.DataAccess.SQL;
//using Ease.Core.DataAccess.Odbc;
//using Ease.Core.DataAccess.OleDb;
using Ease.Core.DataAccess.Oracle;
namespace Ease.Core.DataAccess
{
#region DataAccess: Transaction Helper Factory
public abstract class TransactionFactory
{
#region Default Helper
private static TransactionFactory _default;
public static TransactionFactory Default
{
get
{
if (_default == null)
{
#region Default TransactionHelper
switch (ConnectionFactory.Provider)
{
case Provider.Sql:
_default = new SqlHelper();
break;
case Provider.Oracle:
//_default = new OracleHelper();
break;
case Provider.OleDb:
//_default = new OleDbHelper();
break;
case Provider.Odbc:
//_default = new OdbcHelper();
break;
default:
break;
}
#endregion
}
return _default;
}
}
#endregion
#region Context Helper
public static TransactionFactory ContextTransactionHelper(ConnectionContext context)
{
TransactionFactory ctxFactory;
switch (ConnectionFactory.Provider)
{
//case Provider.Oracle:
// ctxFactory = new OracleHelper();
// break;
//case Provider.OleDb:
// ctxFactory = new OleDbHelper();
// break;
//case Provider.Odbc:
// ctxFactory = new OdbcHelper();
// break;
default:
ctxFactory = new SqlHelper();
break;
}
return ctxFactory;
}
#endregion
#region Execute NonQuery
public abstract int ExecuteNonQuery(int commandTimeout, string connectionString, CommandType commandType,
string commandText);
public abstract int ExecuteNonQuery(int commandTimeout, string connectionString, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract int ExecuteNonQuery(int commandTimeout, string connectionString, string spName,
params object[] parameterValues);
public abstract int ExecuteNonQuery(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText);
public abstract int ExecuteNonQuery(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract int ExecuteNonQuery(int commandTimeout, IDbConnection connection, string spName,
params object[] parameterValues);
public abstract int ExecuteNonQuery(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText);
public abstract int ExecuteNonQuery(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract int ExecuteNonQuery(int commandTimeout, IDbTransaction transaction, string spName,
params object[] parameterValues);
#endregion ExecuteNonQuery
#region Execute DataTable
public abstract DataTable ExecuteDataTable(int commandTimeout, string connectionString, CommandType commandType,
string commandText);
public abstract DataTable ExecuteDataTable(int commandTimeout, string connectionString, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract DataTable ExecuteDataTable(int commandTimeout, string connectionString, string spName,
params object[] parameterValues);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbConnection connection,
CommandType commandType, string commandText);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbConnection connection,
CommandType commandType, string commandText, params IDataParameter[] commandParameters);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbConnection connection, string spName,
params object[] parameterValues);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbTransaction transaction,
CommandType commandType, string commandText);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbTransaction transaction,
CommandType commandType, string commandText, params IDataParameter[] commandParameters);
public abstract DataTable ExecuteDataTable(int commandTimeout, IDbTransaction transaction, string spName,
params object[] parameterValues);
#endregion ExecuteDataTable
#region Execute Dataset
public abstract DataSet ExecuteDataset(int commandTimeout, string connectionString, CommandType commandType,
string commandText);
public abstract DataSet ExecuteDataset(int commandTimeout, string connectionString, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract DataSet ExecuteDataset(int commandTimeout, string connectionString, string spName,
params object[] parameterValues);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbConnection connection, string spName,
params object[] parameterValues);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract DataSet ExecuteDataset(int commandTimeout, IDbTransaction transaction, string spName,
params object[] parameterValues);
#endregion ExecuteDataset
#region Execute Reader
private enum IDbConnectionOwnership
{
/// <summary>Connection is owned and managed by OleDbHelper</summary>
Internal,
/// <summary>Connection is owned and managed by the caller</summary>
External
}
public abstract IDataReader ExecuteReader(int commandTimeout, string connectionString, CommandType commandType,
string commandText);
public abstract IDataReader ExecuteReader(int commandTimeout, string connectionString, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract IDataReader ExecuteReader(int commandTimeout, string connectionString, string spName,
params object[] parameterValues);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbConnection connection, string spName,
params object[] parameterValues);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbTransaction transaction,
CommandType commandType, string commandText);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbTransaction transaction,
CommandType commandType, string commandText, params IDataParameter[] commandParameters);
public abstract IDataReader ExecuteReader(int commandTimeout, IDbTransaction transaction, string spName,
params object[] parameterValues);
#endregion ExecuteReader
#region Execute Scalar
public abstract object ExecuteScalar(int commandTimeout, string connectionString, CommandType commandType,
string commandText);
public abstract object ExecuteScalar(int commandTimeout, string connectionString, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract object ExecuteScalar(int commandTimeout, string connectionString, string spName,
params object[] parameterValues);
public abstract object ExecuteScalar(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText);
public abstract object ExecuteScalar(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract object ExecuteScalar(int commandTimeout, IDbConnection connection, string spName,
params object[] parameterValues);
public abstract object ExecuteScalar(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText);
public abstract object ExecuteScalar(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText, params IDataParameter[] commandParameters);
public abstract object ExecuteScalar(int commandTimeout, IDbTransaction transaction, string spName,
params object[] parameterValues);
#endregion ExecuteScalar
#region FillDataset
public abstract void FillDataset(int commandTimeout, string connectionString, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames);
public abstract void FillDataset(int commandTimeout, string connectionString, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames, params IDataParameter[] commandParameters);
public abstract void FillDataset(int commandTimeout, string connectionString, string spName, DataSet dataSet,
string[] tableNames, params object[] parameterValues);
public abstract void FillDataset(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames);
public abstract void FillDataset(int commandTimeout, IDbConnection connection, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames, params IDataParameter[] commandParameters);
public abstract void FillDataset(int commandTimeout, IDbConnection connection, string spName, DataSet dataSet,
string[] tableNames, params object[] parameterValues);
public abstract void FillDataset(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames);
public abstract void FillDataset(int commandTimeout, IDbTransaction transaction, CommandType commandType,
string commandText, DataSet dataSet, string[] tableNames, params IDataParameter[] commandParameters);
public abstract void FillDataset(int commandTimeout, IDbTransaction transaction, string spName, DataSet dataSet,
string[] tableNames, params object[] parameterValues);
#endregion
#region Update Dataset
public abstract void UpdateDataset(IDbCommand insertCommand, IDbCommand deleteCommand, IDbCommand updateCommand,
DataSet dataSet, string tableName);
#endregion
#region Create Command
public abstract IDbCommand CreateCommand(IDbConnection connection, string spName,
params string[] sourceColumns);
#endregion
#region Execute NonQuery TypedParams
public abstract int ExecuteNonQueryTypedParams(int commandTimeout, string connectionString, string spName,
DataRow dataRow);
public abstract int ExecuteNonQueryTypedParams(int commandTimeout, IDbConnection connection, string spName,
DataRow dataRow);
public abstract int ExecuteNonQueryTypedParams(int commandTimeout, IDbTransaction transaction, string spName,
DataRow dataRow);
#endregion
#region Execute Dataset TypedParams
public abstract DataSet ExecuteDatasetTypedParams(int commandTimeout, string connectionString, string spName,
DataRow dataRow);
public abstract DataSet ExecuteDatasetTypedParams(int commandTimeout, IDbConnection connection, string spName,
DataRow dataRow);
public abstract DataSet ExecuteDatasetTypedParams(int commandTimeout, IDbTransaction transaction, string spName,
DataRow dataRow);
#endregion
#region Execute Reader TypedParams
public abstract IDataReader ExecuteReaderTypedParams(int commandTimeout, string connectionString, string spName,
DataRow dataRow);
public abstract IDataReader ExecuteReaderTypedParams(int commandTimeout, IDbConnection connection,
string spName, DataRow dataRow);
public abstract IDataReader ExecuteReaderTypedParams(int commandTimeout, IDbTransaction transaction,
string spName, DataRow dataRow);
#endregion
#region Execute Scalar TypedParams
public abstract object ExecuteScalarTypedParams(int commandTimeout, string connectionString, string spName,
DataRow dataRow);
public abstract object ExecuteScalarTypedParams(int commandTimeout, IDbConnection connection, string spName,
DataRow dataRow);
public abstract object ExecuteScalarTypedParams(int commandTimeout, IDbTransaction transaction, string spName,
DataRow dataRow);
#endregion
}
#endregion
}

View File

@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup Label="Globals">
<SccProjectName></SccProjectName>
<SccProvider></SccProvider>
<SccAuxPath></SccAuxPath>
<SccLocalPath></SccLocalPath>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Class1.cs" />
<Compile Remove="Utility\ClientConfuration.cs" />
<Compile Remove="Utility\ClientStorage.cs" />
<Compile Remove="Utility\ConfigurationElement.cs" />
<Compile Remove="Utility\ConfigUtility.cs" />
<Compile Remove="Utility\IAsyncStatusHandle.cs" />
<Compile Remove="Utility\LateBoundObject.cs" />
<Compile Remove="Utility\ZipHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Remove="jsconfig1.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="10.0.14" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.14" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="23.26.400" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="10.0.14" />
<PackageReference Include="System.Data.OleDb" Version="10.0.14" />
<PackageReference Include="System.Data.OracleClient" Version="1.0.8" />
</ItemGroup>
</Project>

555
Ease.Core/EnumHelper.cs Normal file
View File

@ -0,0 +1,555 @@
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
namespace Ease.Core
{
public sealed class EnumHelper
{
private EnumHelper()
{
}
/// <summary>
/// Use EnumFormatter.ToString() instead.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[Obsolete("Use EnumFormatter.ToString()")]
public static string GetDescription(Enum value)
{
return EnumFormatter.ToString(value);
}
}
/// <summary>
/// Provides formatting functions to convert enumeration values
/// to user-friendly strings by breaking proper-case enumeration
/// name into seperate words. Use the ToString() method to get
/// user-friendly text. Use the Parse method to parse a user-firendly
/// text to an enumeration value.
/// </summary>
public sealed class EnumFormatter
{
private static Dictionary<string, EnumItemCollection> _hashEnums;
static EnumFormatter()
{
_hashEnums = new Dictionary<string, EnumItemCollection>();
}
/// <summary>
/// convert enumeration values to user-friendly string
/// by breaking proper-case enumeration
/// name into seperate words. RecceivedFromOtherDepot = "Recceived From Other Depot".
/// </summary>
/// <param name="value">The value to be converted</param>
/// <returns>Formatted string</returns>
public static string ToString(Enum value)
{
string s = value.ToString();
StringBuilder desc = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (!char.IsLower(s[i]) && i > 0 && char.IsLower(s[i - 1]))
{
desc.Append(" ");
}
desc.Append(s[i]);
}
return desc.ToString();
}
/// <summary>
/// Parse a formatted enumeration name into the value.
/// "Recceived From Other Depot" --> RecceivedFromOtherDepot.
/// Throws FormattingException if fails to convert to
/// an enumeration value for the specified type.
/// </summary>
/// <param name="enumType">The type to convert to.</param>
/// <param name="text">Text to parse</param>
/// <returns></returns>
public static Enum Parse(Type enumType, string text)
{
text = text.Replace(" ", "");
return (Enum)Enum.Parse(enumType, text);
}
/// <summary>
/// Return the actual value in integer.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <param name="value">Value to be converted.</param>
/// <returns>Integer value.</returns>
public static int GetValue(Type enumType, Enum value)
{
return (Convert.ToInt32(Enum.Format(enumType, value, "d")));
}
/// <summary>
/// Return the integer value.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <param name="text">Friendly name or actual name.</param>
/// <returns>Return an integer value.</returns>
public static int GetValue(Type enumType, string text)
{
text = text.Replace(" ", "");
return Convert.ToInt32(Enum.Parse(enumType, text));
}
/// <summary>
/// Return the nteger value index zero based.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <param name="value">Enum value.</param>
/// <returns>Return an integer index.</returns>
public static int GetIndex(Type enumType, Enum value)
{
string s = value.ToString();
return GetIndex(enumType, s);
}
/// <summary>
/// Return the nteger value index zero based.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <param name="text">Friendly name or actual name.</param>
/// <returns>Return an integer index.</returns>
public static int GetIndex(Type enumType, string text)
{
if (_hashEnums.ContainsKey(enumType.FullName))
{
EnumItemCollection items = _hashEnums[enumType.FullName];
if (items != null)
{
text = text.Replace(" ", "");
EnumItem item = items[text];
if (item != null)
return item.Index;
}
}
return -1;
}
/// <summary>
/// Return string array of enum.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <returns>Array of string.</returns>
public static string[] GetNames(Type enumType)
{
EnumItemCollection items = EnumFormatter.GetObjects(enumType);
if (items != null)
return items.GetNames();
return new string[] { };
}
/// <summary>
/// Return EnumItemCollection object.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <returns>Return EnumItemCollection object.</returns>
public static EnumItemCollection GetObjects(Type enumType)
{
EnumItemCollection items;
if (_hashEnums.ContainsKey(enumType.FullName))
{
items = (EnumItemCollection)_hashEnums[enumType.FullName];
if (items != null)
return items;
}
int index = 0;
string[] names = Enum.GetNames(enumType);
items = new EnumItemCollection();
foreach (string name in names)
{
string s = name;
StringBuilder desc = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (!char.IsLower(s[i]) && i > 0 && char.IsLower(s[i - 1]))
{
desc.Append(" ");
}
desc.Append(s[i]);
}
s = desc.ToString();
EnumItem item = new EnumItem(index, name, s, EnumFormatter.GetValue(enumType, name));
items.Add(item);
index++;
}
_hashEnums.Add(enumType.FullName, items);
return items;
}
/// <summary>
/// Return EnumItemCollection object.
/// </summary>
/// <param name="enumType">From based on which enum.</param>
/// <param name="values">Array of enums value.</param>
/// <returns>Return EnumItemCollection object.</returns>
public static EnumItemCollection GetObjects(Type enumType, Array values)
{
EnumItemCollection items;
#region From Cached Items
if (_hashEnums.ContainsKey(enumType.FullName))
{
EnumItemCollection cachedItems = (EnumItemCollection)_hashEnums[enumType.FullName];
if (cachedItems != null)
{
items = new EnumItemCollection();
foreach (EnumItem cachedItem in cachedItems)
{
foreach (Enum value in values)
{
int enumValue = Convert.ToInt32(Enum.Format(enumType, value, "d"));
if (cachedItem.Value == enumValue)
{
EnumItem item = new EnumItem(cachedItem.Index, cachedItem.Name, cachedItem.FriendlyName,
cachedItem.Value);
items.Add(item);
break;
}
}
}
return items;
}
}
#endregion
#region Items agains Passed enums array
string[] names = Enum.GetNames(enumType);
items = new EnumItemCollection();
foreach (string name in names)
{
string s = name;
StringBuilder desc = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (!char.IsLower(s[i]) && i > 0 && char.IsLower(s[i - 1]))
{
desc.Append(" ");
}
desc.Append(s[i]);
}
s = desc.ToString();
int enumValue = Convert.ToInt32(Enum.Parse(enumType, name, true));
foreach (Enum value in values)
{
int enumParamValue = Convert.ToInt32(Enum.Format(enumType, value, "d"));
if (enumValue == enumParamValue)
{
EnumItem item = new EnumItem(items.Count, name, s, enumValue);
items.Add(item);
break;
}
}
}
#endregion
return items;
}
}
#region Helper Class
public sealed class EnumItem
{
#region Constructor
internal EnumItem(int index, string name, string friendlyName, int value)
{
_name = name;
_index = index;
_value = value;
_friendlyName = friendlyName;
}
#endregion
#region Properies
#region Property Index : int
private readonly int _index;
public int Index
{
get { return _index; }
}
#endregion
#region Property Name : string
private readonly string _name;
public string Name
{
get { return _name; }
}
#endregion
#region Property FriendlyName : string
private readonly string _friendlyName;
public string FriendlyName
{
get { return _friendlyName; }
}
#endregion
#region Property Value : int
private readonly int _value;
public int Value
{
get { return _value; }
}
#endregion
#endregion
#region Functions
/// <summary>
/// Use to create an EnumItem object
/// </summary>
/// <param name="enumType">Type of Enum i.e TypeOf(UserTypeEnum) </param>
/// <param name="value">Value of enum i.e UserTypeEnum.Admin</param>
/// <returns>Returns an instatnce of EnumItem</returns>
public static EnumItem FromValue(Type enumType, Enum value)
{
int enumValue = Convert.ToInt32(Enum.Format(enumType, value, "d"));
return EnumItem.FromValue(enumType, enumValue);
}
/// <summary>
/// Use to create an EnumItem object
/// </summary>
/// <param name="enumType">Type of Enum i.e TypeOf(UserTypeEnum) </param>
/// <param name="value">Valid enum value in int</param>
/// <returns>Returns an instatnce of EnumItem</returns>
public static EnumItem FromValue(Type enumType, int value)
{
int idx = -1;
EnumItem item = null;
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
idx += 1;
int val = Convert.ToInt32(Enum.Parse(enumType, name, true));
if (val != value)
continue;
string s = name;
StringBuilder desc = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (!char.IsLower(s[i]) && i > 0 && char.IsLower(s[i - 1]))
desc.Append(" ");
desc.Append(s[i]);
}
s = desc.ToString();
item = new EnumItem(idx, name, s, value);
break;
}
return item;
}
/// <summary>
/// Use to create an EnumItem object
/// </summary>
/// <param name="enumType">Type of Enum i.e TypeOf(UserTypeEnum) </param>
/// <param name="value">Valid value of enum in string i.e Admin</param>
/// <returns>Returns an instatnce of EnumItem</returns>
public static EnumItem FromValue(Type enumType, string value)
{
int enumValue = 0;
if (!int.TryParse(value, out enumValue))
enumValue = -99999;
if (enumValue == -99999)
throw new Exception(string.Format("Invalid use of value: {0}", value));
return EnumItem.FromValue(enumType, enumValue);
}
/// <summary>
/// Use to create an EnumItem object
/// </summary>
/// <param name="enumType">Type of Enum i.e TypeOf(UserTypeEnum)</param>
/// <param name="values">Custom arry of enum i.e new UserTypeEnum[]{UserTypeEnum.SuperUser, UserTypeEnum.Admin}</param>
/// <param name="value">Value of enum i.e UserTypeEnum.Admin</param>
/// <returns>Returns an instatnce of EnumItem</returns>
public static EnumItem FromValue(Type enumType, Array values, Enum value)
{
int idx = -1;
EnumItem item = null;
int enumValue = Convert.ToInt32(Enum.Format(enumType, value, "d"));
foreach (Enum arValue in values)
{
idx += 1;
string name = arValue.ToString();
int val = Convert.ToInt32(Enum.Parse(enumType, name, true));
if (val != enumValue)
continue;
string s = name;
StringBuilder desc = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
if (!char.IsLower(s[i]) && i > 0 && char.IsLower(s[i - 1]))
desc.Append(" ");
desc.Append(s[i]);
}
s = desc.ToString();
item = new EnumItem(idx, name, s, enumValue);
break;
}
if (item == null)
return new EnumItem(-1, "Unknown", "Unknown", enumValue);
return item;
}
#endregion
}
public sealed class EnumItemCollection : CollectionBase
{
#region Constructor
private Hashtable _hashTable;
internal EnumItemCollection()
{
_hashTable = new Hashtable();
InnerList.Clear();
}
#endregion
#region Functions
internal void Add(EnumItem item)
{
if (!_hashTable.ContainsKey(item.Name))
{
_hashTable.Add(item.Name, item);
InnerList.Add(item);
}
}
public EnumItem this[Enum value]
{
get
{
string s = value.ToString();
return this[s];
}
}
public EnumItem this[string valueMember]
{
get
{
valueMember = valueMember.Replace(" ", "");
if (_hashTable.ContainsKey(valueMember))
return (EnumItem)_hashTable[valueMember];
return null;
}
}
public EnumItem this[int index]
{
get { return (EnumItem)InnerList[index]; }
}
internal string[] GetNames()
{
string[] names = null;
if (this.Count > 0)
{
names = new string[this.Count];
for (int index = 0; index < this.Count; index++)
{
names[index] = this[index].FriendlyName;
}
}
return names;
}
#endregion
}
public class EnumDescription
{
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes
(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
}
#endregion
}

117
Ease.Core/Enums.cs Normal file
View File

@ -0,0 +1,117 @@
using System;
namespace Ease.Core
{
#region EnuSQL Syntax Enum
public enum SQLSyntax
{
Access = 1,
SQL,
Oracle,
Informix
}
#endregion
[Serializable]
public enum EnumTrainingCharacter
{
Class_Room_Education = 1,
On_the_job_training = 2,
Developmental_relationships = 3,
Functional_Developments = 4
}
#region Provider
public enum Provider
{
Sql = 1,
OracleNative,
Oracle,
OleDb,
Odbc
}
#endregion
#region Enumeration: ObjectState
public enum ObjectState
{
New,
Modified,
Saved
}
#endregion
#region Action enumeration
public enum ActionEnum : short
{
Insert = 1,
Update = 2,
Delete = 3
}
#endregion
#region Date format Enum
/// <summary>
/// This function return actual date according
/// to passed parameter (optional time format after date, then a space
/// and foramt 'hh:mm:ss AM/PM'
/// </summary>
public enum FormatOptions : byte
{
ddMMyyyy = 1,
MMddyyyy = 2,
ddMMMyyyy = 3
}
#endregion
#region Create Mode
internal enum CreateMode
{
Local,
Remote
}
#endregion
#region Address Type: outlook
public enum AddressType : int
{
Home,
Business,
Other
}
#endregion
[Serializable]
public enum enumCompetency
{
None = 0,
Value = 1,
Competency = 2
}
[Serializable]
public enum EnumResidence
{
None = 0,
Own = 1,
Rented = 2
}
}

View File

@ -0,0 +1,354 @@
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ease.Core.Model;
using Ease.Core.Utility;
using System.ComponentModel.DataAnnotations.Schema;
namespace Ease.Core.Model
{
#region Framwwork: Business Object
#region Framwwork: Event delegate
public delegate void ObjectIDChanged(long newID);
#endregion
public abstract class ObjectTemplate
{
private int _sortOrder;
protected ObjectState _objectState;
protected int _id = int.MinValue;
//private Dictionary<string, string> _auditTrail;
//The event handler need to be non serialized
//public event ObjectIDChanged IDChanged;
public ObjectTemplate()
{
_objectState = ObjectState.New;
}
/// <summary>
/// ID of the object
/// </summary>
public int ID
{
get { return _id; }
set { _id = value; }
}
/// <summary>
/// State of the object IsNew/Not
/// </summary>
//public bool IsNew
//{
// get { return _objectState == ObjectState.New; }
//}
public bool IsNew
{
get { return _id <= 0; }
}
/// <summary>
/// State of the object IsModified/Not
/// </summary>
//public bool IsModified
//{
// get { return _objectState == ObjectState.Modified; }
//}
/// <summary>
/// State of the object IsSaved/Not
/// </summary>
//public bool IsSaved
//{
// get { return _objectState == ObjectState.Saved; }
//}
//public bool IsUnassigned
//{
// get { return _id == long.MinValue; }
//}
[NotMapped]
public int SortOrder
{
get { return _sortOrder; }
set { _sortOrder = value; }
}
/// <summary>
/// Set modified state of the object
/// </summary>
protected void SetObjectStateModified()
{
if (_objectState == ObjectState.Saved)
_objectState = ObjectState.Modified;
}
/// <summary>
/// Set ID of the object
/// </summary>
/// <param name="id">A valid ID for the object.</param>
public void SetID(int id)
{
_id = id;
//if (IDChanged != null)
// IDChanged(_id);
}
/// <summary>
/// Set state of the object
/// </summary>
/// <param name="state">A valid state.</param>
protected internal void SetState(ObjectState state)
{
_objectState = state;
}
protected virtual internal void SetReadOnlyProperties(params object[] propertyValues)
{
}
public override string ToString()
{
return GetType().Name + " (" + _id.ToString() + ")";
}
public override bool Equals(object obj)
{
if (obj == null || (obj.GetType() != this.GetType()))
return false;
return _id.Equals((obj as ObjectTemplate)._id);
}
public override int GetHashCode()
{
if ((object)_id == null)
return base.GetHashCode();
else
return _id.GetHashCode();
}
public static bool operator ==(ObjectTemplate template1, ObjectTemplate template2)
{
if ((object)template1 != null)
return template1.Equals(template2);
else
return ((object)template2 == null);
}
public static bool operator !=(ObjectTemplate template1, ObjectTemplate template2)
{
if ((object)template1 != null)
return !template1.Equals(template2);
else
return !((object)template2 == null);
}
/// <summary>
/// Make clone of the current instance rather reference
/// </summary>
/// <returns>Return another instance of current instance rather reference.</returns>
protected ObjectTemplate Clone()
{
return this.CopyObject();
}
/// <summary>
/// Create string value from current instance.
/// </summary>
/// <param name="key">For further reconstruct.</param>
/// <param name="delimiter">Delimiter for each property for current instance.</param>
/// <param name="properties">Name of the property(ies) by which string will consturct.</param>
/// <returns>Return delimited string.</returns>
protected virtual string LineData(int key, string delimiter, params string[] properties)
{
if (delimiter.IndexOf('|') >= 0)
throw new Exception("Invalid use of separator: '|'. User separator other than '|'.");
string line = string.Format("{0}", key);
PropertyInfo[] pis = this.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (string property in properties)
{
foreach (PropertyInfo pi in pis)
{
if (pi.Name.ToLower().Equals(property.ToLower()))
{
string value = string.Empty;
object val = pi.GetValue(this, null);
if (val != null)
{
if (pi.PropertyType.IsEnum)
value = Convert.ToInt32(val).ToString("0");
else if (pi.PropertyType == typeof(long))
value = Convert.ToInt32(val).ToString("0");
else if (pi.PropertyType == typeof(int))
value = Convert.ToInt32(val).ToString("0");
else if (pi.PropertyType == typeof(double))
value = Convert.ToDouble(val).ToString("0.0000");
else if (pi.PropertyType == typeof(DateTime))
value = Convert.ToDateTime(val).ToString("MM/dd/yyyy");
else if (pi.PropertyType == typeof(bool))
value = Convert.ToBoolean(val) ? "1" : "0";
else
{
value = val.ToString();
value = value.Replace(Environment.NewLine, "*^*");
}
}
line = string.Format("{0}{1}{2}", line, delimiter, value);
break;
}
}
}
return line;
}
/// <summary>
/// Create an instatnce of BaseType.
/// </summary>
/// <param name="baseType">Type of object to create an instance.</param>
/// <param name="delimiter">Delimiter in the string to separate each property.</param>
/// <param name="objString">Delimited string to create object.</param>
/// <param name="properties">Set property(ies) of object.</param>
/// <returns>Return an instance of basetype.</returns>
protected ObjectTemplate CreateObjectFromString(Type baseType, string delimiter, string objString,
params string[] properties)
{
if (delimiter.IndexOf('|') >= 0)
throw new Exception("Invalid use of separator: '|'. User separator other than '|'.");
ObjectTemplate ot =
(ObjectTemplate)ObjectUtility.CreateInstance(baseType.FullName, new object[] { }, baseType);
PropertyInfo[] props = baseType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
int index = objString.IndexOf(delimiter);
if (index != -1)
objString = objString.Substring(index + 1);
string[] values = objString.Split(delimiter.ToCharArray());
index = -1;
if (values.Length != properties.Length)
throw new Exception("No of properties and values are not same");
foreach (string property in properties)
{
index++;
foreach (PropertyInfo prop in props)
{
if (prop.Name.ToLower().Equals(property.ToLower()))
{
object value = values[index];
if (prop.PropertyType.IsEnum)
prop.SetValue(ot, Enum.Parse(prop.PropertyType, value.ToString(), true), null);
else if (prop.PropertyType.Equals(typeof(bool)))
prop.SetValue(ot, Convert.ToBoolean(Convert.ToInt32(value)), null);
else if (prop.PropertyType.Equals(typeof(DateTime)))
prop.SetValue(ot, Convert.ToDateTime(value), null);
else if (prop.PropertyType.Equals(typeof(double)))
prop.SetValue(ot, Convert.ToDouble(value), null);
else if (prop.PropertyType.Equals(typeof(decimal)))
prop.SetValue(ot, Convert.ToDecimal(value), null);
else if (prop.PropertyType.Equals(typeof(Int16)))
prop.SetValue(ot, Convert.ToInt16(value), null);
else if (prop.PropertyType.Equals(typeof(Int32)))
prop.SetValue(ot, Convert.ToInt32(value), null);
else if (prop.PropertyType.Equals(typeof(Int64)))
prop.SetValue(ot, Convert.ToInt64(value), null);
else if (prop.PropertyType.Equals(typeof(byte)))
prop.SetValue(ot, Convert.ToByte(value), null);
else
{
value = value.ToString().Replace("*^*", Environment.NewLine);
prop.SetValue(ot, value, null);
}
break;
}
}
}
return ot;
}
internal ObjectTemplate CopyObject()
{
ObjectTemplate cot =
Ease.Core.Utility.ObjectUtility.CreateInstance(this.GetType().FullName, new object[] { },
this.GetType()) as ObjectTemplate;
foreach (FieldInfo fi in this.GetType()
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
fi.SetValue(cot, fi.GetValue(this));
return cot;
}
/// <summary>
/// Keep Track whether value of property has been changed or not
/// and property value cannot be null.
/// </summary>
/// <typeparam name="T">Type of property i.e string/int/DateTime e.t.c.</typeparam>
/// <param name="propertyName">Name of the property i.e "Description".</param>
/// <param name="currentValue">Existing value of the property i.e "Computer Ease Ltd"</param>
/// <param name="newValue">New value of the property i.e. "CEL"</param>
//protected void OnPropertyChange<T>(string propertyName, T currentValue, T newValue)
// where T : IEquatable<T>
//{
// if ((newValue != null && !newValue.Equals(currentValue)) || (newValue == null && currentValue != null))
// {
// if (_objectState != ObjectState.New)
// {
// if (_auditTrail == null)
// _auditTrail = new Dictionary<string, string>();
// _auditTrail[propertyName] = string.Format("{0} => {1}", currentValue, newValue);
// _objectState = ObjectState.Modified;
// }
// }
//}
/// <summary>
/// Keep Track whether value of property has been changed or not
/// and property value may be null.
/// </summary>
/// <typeparam name="T">Type of property i.e string/int/DateTime e.t.c.</typeparam>
/// <param name="propertyName">Name of the property i.e "Description".</param>
/// <param name="currentValue">Existing value of the property i.e "Computer Ease Ltd"</param>
/// <param name="newValue">New value of the property i.e. "CEL"</param>
//protected void OnPropertyChange<T>(string propertyName, Nullable<T> currentValue, Nullable<T> newValue)
// where T : struct
//{
// if ((newValue != null && !newValue.Equals(currentValue)) || (newValue == null && currentValue != null))
// {
// if (_objectState != ObjectState.New)
// {
// if (_auditTrail == null)
// _auditTrail = new Dictionary<string, string>();
// _auditTrail[propertyName] = string.Format("{0} => {1}", currentValue, newValue);
// _objectState = ObjectState.Modified;
// }
// }
//}
}
#endregion
}

View File

@ -0,0 +1,44 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Special thanks to Asif Ahamed Siddiqui |
| Author: S. M. Russel, Last modified date: 128/12/2007 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Runtime.Serialization;
namespace Ease.Core.Model
{
#region Framework: Service Exception Object
public class ServiceException : ApplicationException
{
public ServiceException() : base()
{
}
public ServiceException(string message) : base(message)
{
}
public ServiceException(string message, Exception inner) : base(message, inner)
{
}
public ServiceException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
#endregion
}

View File

@ -0,0 +1,184 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Special thanks to Asif Ahamed Siddiqui |
| Author: S. M. Russel, Last modified date: 18/04/2009 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Reflection;
using System.Collections;
using Ease.Core.Utility;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Collections.Specialized;
namespace Ease.Core.Model
{
#region Framework: Service Factory
/// <summary>
/// ServiceFactory Class proIDes functionality to Create Service Objects as Remote objects or In-Process objects depending on a configuratio Setting.
/// This key wtritten in appSettings section and default key 'serviceHandler'
/// </summary>
internal enum CreateMode
{
Local,
Remote
}
public class ServiceFactory
{
private string _asmFullName;
private ListDictionary _assemblies;
private Dictionary<string, object> _cachedTypes;
/// <summary>
/// Constructor for ServiceFactory
/// </summary>
/// <param name="sectionKey">
/// Define sectionKey . Use the follwoing format :-
/// For Remote: "Application server-url:port/ServiceAssembly;ServiceAssembly"
/// Example : value="100.100.100.29:49500/Services;Services.Core;Sales.ProductHierarchy"
/// For Local : "ServiceAssembly/Datasource;ServiceAssembly/Datasource".
/// Example : value="Services.dll/TELDMS;Services.Core.dll/SalesCore;Sales.ProductHierarchy.dll/SalesMktHierarchy"
/// </param>
public ServiceFactory(string sectionKey)
{
if (_cachedTypes == null) _cachedTypes = new Dictionary<string, object>();
return;
}
/// <summary>
/// Create service of parameter type which belongs current service
/// assembly (Only one service assembly is used).
/// </summary>
/// <typeparam name="T">Any interface</typeparam>
/// <param name="type">Type of interface from business object which is implemented in service assembly.</param>
/// <returns>Return appropriate service if found
/// otherwise throw an exception 'Error Creating Service'.
/// </returns>
public T CreateService<T>(Type type)
{
object service = null;
try
{
string serviceName = type.Name.StartsWith("I") ? type.Name.Substring(1) : type.Name;
#region Individual objects are configured
lock (_cachedTypes)
{
string serverEP = type.Assembly.FullName;
serverEP = serverEP.Substring(0, serverEP.IndexOf('.'));
serverEP = serverEP + ".DA";
string endPoint = serverEP + ".dll";
string targetAssembly = type.Assembly.FullName.Replace("BO", "DA") + "." + serviceName;
if (_cachedTypes.ContainsKey(targetAssembly) == false)
{
Assembly assembly = Assembly.Load(serverEP);
foreach (Type svcType in assembly.GetTypes())
{
// if (svcType.IsMarshalByRef && svcType.IsSubclassOf(typeof(ServiceTemplate)))
if (svcType.IsSubclassOf(typeof(ServiceTemplate)))
{
string key = assembly.FullName + "." + svcType.Name;
if (!_cachedTypes.ContainsKey(key))
_cachedTypes.Add(key, svcType);
}
}
}
Type implType = (Type)_cachedTypes[targetAssembly];
service = implType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
implType.InvokeMember("SetEndPoint",
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, service,
new object[] { endPoint });
}
#endregion
}
catch (Exception e)
{
throw new Exception(string.Format("Error Creating Service for type: {0}", type.Name), e);
}
if (service == null)
throw new Exception(string.Format("Error Creating Service for type: {0}", type.Name));
return (T)service;
}
/// <summary>
/// Create service of parameter type which belongs to nsOfService namespance
/// (use multiple service assembly).
/// </summary>
/// <typeparam name="T">Any interface</typeparam>
/// <param name="type">Type of interface from business object which is implemented in service assembly.</param>
/// <param name="nsOfService">Type belongs to which namespace. </param>
/// <returns>Return appropriate service if found
/// otherwise throw an exception 'Error Creating Service'.
/// </returns>
public T CreateService<T>(Type type, string nsOfService)
{
object service = null;
try
{
string serviceName = type.Name.StartsWith("I") ? type.Name.Substring(1) : type.Name;
#region Individual objects are configured
//Checking mode for current type
string serverEP = type.Assembly.FullName;
serverEP = serverEP.Substring(0, serverEP.IndexOf('.'));
serverEP = serverEP + ".DA";
string EndPoint = serverEP + ".dll";
// serverEP = svcParts[0];
serverEP = serverEP.Substring(0, serverEP.Length - 4);
Assembly assembly = Assembly.Load(serverEP);
if (!_assemblies.Contains(serverEP))
{
_assemblies.Add(serverEP, assembly.FullName);
foreach (Type svcType in assembly.GetTypes())
{
//if (svcType.IsMarshalByRef && svcType.IsSubclassOf(typeof(ServiceTemplate)))
if (svcType.IsSubclassOf(typeof(ServiceTemplate)))
{
string key = assembly.FullName + "." + svcType.Name;
if (!_cachedTypes.ContainsKey(key))
_cachedTypes.Add(key, svcType);
}
}
}
string asmFullName = _assemblies[nsOfService].ToString();
Type implType = (Type)_cachedTypes[asmFullName + "." + serviceName];
service = implType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
implType.InvokeMember("SetEndPoint",
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, service,
new object[] { EndPoint });
#endregion
}
catch (Exception e)
{
throw new Exception(string.Format("Error Creating Service for type: {0}", type.Name), e);
}
if (service == null)
throw new Exception(string.Format("Error Creating Service for type: {0}", type.Name));
return (T)service;
}
}
#endregion
}

View File

@ -0,0 +1,102 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 18/04/2009 |
|-------------------------------------------------------------------------------|
*/
using Ease.Core.DataAccess;
using System.Collections.Generic;
namespace Ease.Core.Model
{
#region Framework: Service base
public abstract class ServiceTemplate
{
private string _svcName;
private string _endPoint;
public ServiceTemplate(string svcName)
{
_svcName = svcName;
}
public ServiceTemplate()
{
_svcName = "";
}
public bool IsAlive
{
get { return true; }
}
public string ServiceName
{
get { return _svcName; }
set { _svcName = value; }
}
internal void SetEndPoint(string value)
{
_endPoint = value;
}
protected string EndPoint
{
get { return _endPoint; }
}
protected void SetObjectID(ObjectTemplate ot, int id)
{
ot.SetID(id);
}
protected void SetObjectID(ObjectTemplate ot, long id)
{
ot.SetID((int)id);
}
protected void SetObjectState(ObjectTemplate ot, ObjectState state)
{
ot.SetState(state);
}
protected void SetObjectReadOnlyProperties(ObjectTemplate ot, params object[] propertyValues)
{
ot.SetReadOnlyProperties(propertyValues);
}
protected abstract T CreateObject<T>(DataReader dr)
where T : ObjectTemplate;
/// <summary>
/// Return collection of objects of type T.
/// </summary>
/// <typeparam name="T">Type of object.</typeparam>
/// <param name="dr">A valid datareader.</param>
/// <returns>Return List of type T.</returns>
protected List<T> CreateObjects<T>(DataReader dr)
where T : ObjectTemplate
{
List<T> list = new List<T>();
while (dr.Read())
{
T ot = this.CreateObject<T>(dr);
ot.SetState(ObjectState.Saved);
list.Add(ot);
}
return list;
}
}
#endregion
}

View File

@ -0,0 +1,69 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 18/04/2009 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Collections.Generic;
namespace Ease.Core.Model
{
#region Services
/// <summary>
///This class returns the appropriate service factory according to configuration
/// </summary>
public class Services
{
private static ServiceFactory _factory;
private const string defaultKey = "serviceHandler";
private static Dictionary<string, ServiceFactory> _keyBaseServices;
static Services()
{
_keyBaseServices = new Dictionary<string, ServiceFactory>();
_factory = new ServiceFactory(defaultKey);
}
/// <summary>
/// Return default service facory
/// </summary>
public static ServiceFactory Factory
{
get { return _factory; }
}
/// <summary>
/// Crete an instance of services.
/// </summary>
/// <param name="serviceHandlerKey">Key is used handle services</param>
public Services(string serviceHandlerKey)
{
if (_keyBaseServices.ContainsKey(serviceHandlerKey))
return;
ServiceFactory svc = new ServiceFactory(serviceHandlerKey);
_keyBaseServices.Add(serviceHandlerKey, svc);
}
/// <summary>
/// Return Service factory according to parameter.
/// </summary>
/// <param name="svcKey">Valid key of existing services</param>
/// <returns></returns>
public ServiceFactory KeyBaseFactory(string svcKey)
{
if (_keyBaseServices != null && _keyBaseServices.ContainsKey(svcKey))
return _keyBaseServices[svcKey];
return null;
}
}
#endregion
}

View File

@ -0,0 +1,40 @@

using System;
using System.Xml;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace Ease.Core.Utility
{
//public sealed class ClientConfuration
//{
// private static readonly Dictionary<string, string> _clientConfig = new Dictionary<string, string>();
// static ClientConfuration()
// {
// XmlReaderSettings settings = new XmlReaderSettings();
// XmlReader reader = XmlReader.Create("ClientConfig.xml", settings);
// while (reader.Read())
// {
// if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("setting", StringComparison.CurrentCultureIgnoreCase))
// {
// string key = reader.GetAttribute("key");
// string value = reader.GetAttribute("value");
// _clientConfig.Add(key, value);
// }
// }
// }
// public static string GetValue(string key)
// {
// string value;
// if (!_clientConfig.TryGetValue(key, out value))
// value = string.Empty;
// return value;
// }
//}
}

View File

@ -0,0 +1,125 @@
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Ease.Core.Utility
{
//public sealed class ClientStorage
//{
// private static readonly object SyncRoot = new object();
// private static IsolatedStorageFile _store = IsolatedStorageFile.GetUserStoreForAssembly();
// public static object GetData(string path)
// {
// Stream stream = null;
// try
// {
// stream = new IsolatedStorageFileStream(path, FileMode.Open, _store);
// if (stream == null)
// return null;
// IFormatter formatter = new BinaryFormatter();
// return formatter.Deserialize(stream);
// }
// catch(Exception)
// {
// return null;
// }
// finally
// {
// if (stream != null)
// stream.Close();
// }
// }
// public static void SetData(string path, object value)
// {
// lock (SyncRoot)
// {
// if (value == null)
// {
// try
// {
// if (_store.GetFileNames(path).Length > 0)
// {
// _store.DeleteFile(path);
// return;
// }
// }
// catch (DirectoryNotFoundException)
// {
// return;
// }
// }
// Stream stream = null;
// try
// {
// string[] dirs = path.Split('/');
// if (dirs.Length > 1)
// {
// string dir = string.Join("/", dirs, 0, dirs.Length - 1);
// _store.CreateDirectory(dir);
// }
// stream = new IsolatedStorageFileStream(path, FileMode.OpenOrCreate, _store);
// if (stream != null)
// {
// IFormatter formatter = new BinaryFormatter();
// formatter.Serialize(stream, value);
// }
// }
// catch (Exception) {}
// finally
// {
// if (stream != null)
// stream.Close();
// }
// }
// }
// public static bool Contains(string path)
// {
// try
// {
// return _store.GetFileNames(path).Length > 0;
// }
// catch (DirectoryNotFoundException)
// {
// return false;
// }
// }
// public static void Remove(string path)
// {
// lock (SyncRoot)
// {
// if (path.EndsWith("/"))
// {
// foreach (string subDir in _store.GetDirectoryNames(path))
// {
// Remove(subDir);
// }
// }
// try
// {
// foreach (string file in _store.GetFileNames(path))
// {
// _store.DeleteFile(Path.Combine(Path.GetDirectoryName(path), file));
// }
// }
// catch (DirectoryNotFoundException) { }
// }
// }
// public static void ClearStorage()
// {
// _store.Remove();
// _store = IsolatedStorageFile.GetUserStoreForDomain();
// }
//}
}

View File

@ -0,0 +1,99 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Configuration;
using System.Collections.Specialized;
namespace Ease.Core.Utility
{
#region Framework: Configuration related class
/// <summary>
/// Summary description for ConfigUtility.
/// </summary>
//public sealed class ConfigUtility
//{
// /// <summary>
// /// If section does not exist the return instance of NameValueCollection
// /// </summary>
// /// <param name="sectionName">A valid name of section</param>
// /// <returns>Return the NameValueCollection object</returns>
// public static NameValueCollection GetConfigSettings(string sectionName)
// {
// object configSection = null; //#### ConfigurationManager.GetSection(sectionName);
// if (configSection == null|| !(configSection is NameValueCollection))
// return new NameValueCollection();
// return (NameValueCollection)configSection;
// }
// /// <summary>
// /// If section does not exist return new instance of object rather than null
// /// </summary>
// /// <param name="sectionName">A valid section in the config file</param>
// /// <returns>Return a instatnce of system.object</returns>
// public static object GetConfig(string sectionName)
// {
// object configSection = null; //#### ConfigurationManager.GetSection(sectionName);
// if (configSection == null|| !(configSection is NameValueCollection))
// return new object();
// return configSection;
// }
// /// <summary>
// /// If key does not exist in appSettings section return empty string othewise actual value
// /// </summary>
// /// <param name="keyName">A valid key from the appSettings section</param>
// /// <returns>Return string if key exist in the appSettings section else empty string </returns>
// public static string GetAppSettings(string keyName)
// {
// string configValue = null; //#### ConfigurationManager.AppSettings[keyName];
// if (string.IsNullOrEmpty(configValue))
// return string.Empty;
// return configValue;
// }
// /// <summary>
// /// Returns the a string according to specified parameter
// /// </summary>
// /// <param name="sectionName">A valid name of section</param>
// /// <param name="key">A valid name of key of given section</param>
// /// <returns>Returns string if the key exist in the key else empty string</returns>
// public static string GetConfigSetting(string sectionName, string key)
// {
// NameValueCollection configSection = ConfigUtility.GetConfigSettings(sectionName);
// if (configSection == null || configSection.Count == 0 || configSection[key].Trim().Length<=0)
// return string.Empty;
// return configSection[key];
// }
// /// <summary>
// /// Set app settings
// /// </summary>
// /// <param name="key">Valid key</param>
// /// <param name="value">value</param>
// public static void SetAppSettings(string key, string value)
// {
// //#### ConfigurationManager.AppSettings.Set(key, value);
// }
// /// <summary>
// /// Hide the constructor
// /// </summary>
// private ConfigUtility(){}
//}
#endregion
}

View File

@ -0,0 +1,104 @@

using System;
using System.Xml;
using System.Configuration;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace Ease.Core.Utility
{
//public abstract class ConfigElementTemplate<ElementT>
// where ElementT : ConfigElementTemplate<ElementT>, new()
//{
// protected XmlNamespaceManager _nm;
// protected static ElementT GetConfig(string section)
// {
// return new ElementT(); //#### (ElementT)ConfigurationManager.GetSection(section);
// }
// //object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section)
// //{
// // try
// // {
// // _nm = new XmlNamespaceManager(section.OwnerDocument.NameTable);
// // _nm.AddNamespace("_cfg_", section.NamespaceURI);
// // Parse(section as XmlElement);
// // return this;
// // }
// // catch (ConfigurationErrorsException)
// // {
// // throw;
// // }
// // catch (Exception e)
// // {
// // throw new ConfigurationErrorsException(e.Message, e, section);
// // }
// //}
// protected void CheckRequiredAttributes(XmlElement node, params string[] attributes)
// {
// foreach (string attribute in attributes)
// {
// //####
// //if (!node.HasAttribute(attribute))
// // throw new ConfigurationErrorsException("Required Attribute: " + attribute + " is missing", node);
// }
// }
// //protected void RaiseError(XmlElement node, string message, params object[] args)
// //{
// // throw new ConfigurationErrorsException(string.Format(message, args), node);
// //}
// protected List<ChildT> ReadChildren<ChildT>(XmlElement node, string name)
// where ChildT : ConfigChildElementTemplate<ChildT, ElementT>, new()
// {
// List<ChildT> list = new List<ChildT>();
// AddChildren<ChildT>(node, name, list);
// return list;
// }
// protected void AddChildren<ChildT>(XmlElement node, string name, IList<ChildT> list)
// where ChildT : ConfigChildElementTemplate<ChildT, ElementT>, new()
// {
// foreach (XmlElement childNode in node.SelectNodes("_cfg_:" + name, _nm))
// {
// ChildT child = new ChildT();
// child._nm = _nm;
// child.Parent = (ElementT)this;
// try
// {
// child.Parse(childNode);
// }
// //####
// //catch (ConfigurationException)
// //{
// // throw;
// //}
// catch (Exception e)
// {
// //####
// //throw new ConfigurationErrorsException(e.Message, e, childNode);
// }
// list.Add(child);
// }
// }
// protected abstract void Parse(XmlElement node);
//}
//public abstract class ConfigChildElementTemplate<ElementT, ParentT> : ConfigElementTemplate<ElementT>
// where ElementT : ConfigChildElementTemplate<ElementT, ParentT>, new()
// where ParentT : ConfigElementTemplate<ParentT>, new()
//{
// protected ParentT _parent;
// public ParentT Parent
// {
// get { return _parent; }
// internal set { _parent = value; }
// }
//}
}

View File

@ -0,0 +1,367 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Text;
using System.Security.Cryptography;
namespace Ease.Core.Utility
{
internal class Encryption
{
#region Declaration & Constructor
internal const string DefaultPublicKey = "CoMEaLtD";
internal const string DefaultPrivateKey = "CeL.DhK.LaL1@3$5";
internal Encryption()
{
}
#endregion
#region Helper functions
protected string ByteToHex(byte[] value)
{
string s = string.Empty;
for (int i = 0; i < value.Length; i++)
s += ByteToHex(value[i]);
return s;
}
protected string ByteToHex(byte value)
{
return Convert.ToString(value, 16).PadLeft(2, '0').ToUpper();
}
protected string IntToHex(int intData)
{
return Convert.ToString(intData, 16).PadLeft(2, '0');
}
protected byte[] HexToBytes(string value)
{
byte[] bytes = new byte[value.Length / 2];
for (int i = 0; i < value.Length; i += 2)
bytes[i / 2] = HexToByte(value.Substring(i, 2));
return bytes;
}
protected byte HexToByte(string value)
{
return Convert.ToByte(value, 16);
}
protected int HexToInt(string hexData)
{
return Convert.ToInt32(hexData, 16);
}
#endregion
#region Encrypt & Decrypt
internal string Encrypt(string key, string data)
{
try
{
char[] dataChrs, keyChrs;
string encryptedData = string.Empty;
//Save Length of Pass
data = (char)(data.Length) + data;
//Pad Password with space upto 10 Characters
if (data.Length < 10)
data = data.PadRight(10);
dataChrs = data.ToCharArray();
//Make the key big enough
while (key.Length < data.Length)
{
key += key;
}
key = key.Substring(0, data.Length);
keyChrs = key.ToCharArray();
//Encrypting Data
for (int i = 0; i < data.Length; i++)
{
char textChr = dataChrs[i];
char keyChr = keyChrs[i];
encryptedData += IntToHex((int)(textChr) ^ (int)(keyChr));
}
return encryptedData.ToUpper();
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
internal string Decrypt(string key, string data)
{
string decryptedData = string.Empty;
//Taking Lenght, half of Encrypting data
int len = data.Length / 2;
//Making key is big Enough
while (key.Length < len)
{
key += key;
}
key = key.Substring(0, len);
char[] keyChrs = key.ToCharArray();
char[] textChrs = data.ToCharArray();
//Decripting data
for (int i = 0; i < len; i++)
{
string textByte = string.Empty;
for (int j = i * 2; j < (i * 2 + 2); j++)
{
textByte += string.Format("{0}", textChrs.GetValue(j));
}
char textChr = (char)HexToInt(textByte);
char keyChr = keyChrs[i];
decryptedData += (char)((int)(keyChr) ^ (int)(textChr));
}
len = (int)decryptedData.ToCharArray()[0];
decryptedData = decryptedData.Substring(1, len);
return decryptedData;
}
#endregion
}
internal class TDSEncryption : Encryption
{
#region Declaration & Constructor
private TripleDESCryptoServiceProvider _tdesCSP;
internal TDSEncryption()
{
_tdesCSP = new TripleDESCryptoServiceProvider();
}
#endregion
#region Helper function
void initialize(string privateKey, string publicKey)
{
try
{
#region Make the key 128 bit
if (privateKey.Length < 16)
privateKey = privateKey.PadLeft(16);
if (privateKey.Length > 16)
privateKey = privateKey.Substring(0, 16);
#endregion
#region Make IV 64 bit
if (publicKey.Length < 8)
publicKey = publicKey.PadLeft(8);
if (publicKey.Length > 8)
publicKey = publicKey.Substring(0, 8);
#endregion
_tdesCSP.Key = ASCIIEncoding.ASCII.GetBytes(privateKey);
_tdesCSP.IV = ASCIIEncoding.ASCII.GetBytes(publicKey);
}
catch
{
throw new Exception("Invaid Key");
}
}
void destroy()
{
try
{
if (_tdesCSP != null)
_tdesCSP.Clear();
_tdesCSP = null;
}
catch
{
}
}
#endregion
#region Encrypt & Decrypt
internal string Encrypt(string privateKey, string publicKey, string data)
{
string value = string.Empty;
try
{
this.initialize(privateKey, publicKey);
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(data);
value = this.ByteToHex(_tdesCSP.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
this.destroy();
}
catch
{
throw new Exception("Invalid Message");
}
return value;
}
internal string Decrypt(string privateKey, string publicKey, string data)
{
string value = string.Empty;
try
{
this.initialize(privateKey, publicKey);
byte[] buffer = this.HexToBytes(data);
value = ASCIIEncoding.ASCII.GetString(_tdesCSP.CreateDecryptor()
.TransformFinalBlock(buffer, 0, buffer.Length));
this.destroy();
}
catch
{
throw new Exception("Invalid Message");
}
return value;
}
#endregion
}
internal class AESEncryption : Encryption
{
#region Declaration & Constructor
private AesCryptoServiceProvider _aesCSP;
internal AESEncryption()
{
_aesCSP = new AesCryptoServiceProvider();
}
#endregion
#region Helper functions
void initialize(string privateKey, string publicKey)
{
try
{
#region Make the key 256 bit
if (privateKey.Length < 32)
privateKey = privateKey.PadLeft(32);
if (privateKey.Length > 32)
privateKey = privateKey.Substring(0, 32);
#endregion
#region Make IV 128 bit
if (publicKey.Length < 16)
publicKey = publicKey.PadLeft(16);
if (publicKey.Length > 16)
publicKey = publicKey.Substring(0, 16);
#endregion
_aesCSP.Key = ASCIIEncoding.ASCII.GetBytes(privateKey);
_aesCSP.IV = ASCIIEncoding.ASCII.GetBytes(publicKey);
}
catch
{
throw new Exception("Invaid Key");
}
}
void destroy()
{
try
{
if (_aesCSP != null)
_aesCSP.Clear();
_aesCSP = null;
}
catch
{
}
}
#endregion
#region Encrypt & Decrypt
public string Encrypt(string privatekey, string publickey, string data)
{
string value = string.Empty;
try
{
this.initialize(privatekey, publickey);
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(data);
value = this.ByteToHex(_aesCSP.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
this.destroy();
}
catch
{
throw new Exception("Invalid Message");
}
return value;
}
public string Decrypt(string privatekey, string publickey, string data)
{
string value = string.Empty;
try
{
this.initialize(privatekey, publickey);
byte[] buffer = this.HexToBytes(data);
value = ASCIIEncoding.ASCII.GetString(_aesCSP.CreateDecryptor()
.TransformFinalBlock(buffer, 0, buffer.Length));
this.destroy();
}
catch
{
throw new Exception("Invalid Message");
}
return value;
}
#endregion
}
}

View File

@ -0,0 +1,225 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.IO;
using System.Collections;
using System.Diagnostics;
using Ease.Core.Utility;
using System.Collections.Generic;
namespace Ease.Core.Utility
{
#region Utility: Exception Log
/// <summary>
/// This object is used to log error raised in service.
/// This class cannot be inherited.
/// This class cannot be instantiated.
/// All functions are static.
/// </summary>
public sealed class ExceptionLog
{
private static string _mode;
private static int _maxSize;
private static int _maxFiles;
private static string _source;
private static object _syncObject = new object();
static ExceptionLog()
{
AppConfigParser config = new AppConfigParser();
string configvalue = ""; //#### ConfigUtility.GetAppSettings("exceptionHandler");
if (!string.IsNullOrEmpty(configvalue))
config.Parse(configvalue);
//Mod of error
_mode = "File";
//if (config.Contains("mode"))
// _mode = config["mode"];
//Source property
_source = "Log";
//if (config.Contains("source"))
// _source = config["source"];
//No max of file in this folder
_maxFiles = 10;
//if (config.Contains("maxFiles"))
//{
// try
// {
// _maxFiles = int.Parse(config["maxFiles"]); //1 KB
// }
// catch { }
//}
//File size
_maxSize = 5000 * 1024; //5 MB
//if (config.Contains("maxFileSize"))
//{
// try
// {
// _maxSize = int.Parse(config["maxFileSize"]) * 1024; //1 KB
// }
// catch { }
//}
}
private static void WriteToEventLog(string log)
{
try
{
//####
EventLog.WriteEntry(_source, log, EventLogEntryType.Error);
}
catch
{
WriteToFile(log);
}
}
private static void WriteToFile(string log)
{
string path = Path.Combine(Environment.CurrentDirectory, _source);
string logFileSpec = Path.Combine(path, "Error.log");
try
{
lock (_syncObject)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
StreamWriter writer;
if (!File.Exists(logFileSpec))
{
writer = File.CreateText(logFileSpec);
}
else
{
FileInfo fi = new FileInfo(Path.Combine(path, logFileSpec));
if (fi.Length > _maxSize)
{
// Check no of files
ArrayList fileList = new ArrayList(Directory.GetFiles(path, "~*.log"));
if (fileList.Count >= _maxFiles - 1)
{
fileList.Sort();
for (int i = 0; i <= fileList.Count - _maxFiles + 1; i++)
File.Delete((string)fileList[i]);
}
fi.MoveTo(Path.Combine(path, "~" + DateTime.Now.Ticks.ToString() + ".log"));
writer = File.CreateText(logFileSpec);
}
else
{
writer = File.AppendText(logFileSpec);
}
}
writer.WriteLine(log);
writer.Flush();
writer.Close();
}
}
catch
{
}
}
/// <summary>
/// Log application into file/eventviewer according to configuration of application file.
/// </summary>
/// <param name="e">Valid instance of an exception object.</param>
public static void Write(Exception e)
{
string log = new string('*', 80) + Environment.NewLine;
log += string.Format(" TimeStamp: {0} {1}{2}", DateTime.Today.ToShortDateString(),
DateTime.Now.ToLongTimeString(), Environment.NewLine);
log += new string('*', 80) + Environment.NewLine;
while (e != null)
{
log += Environment.NewLine;
log += string.Format("Exception..: {0}{1}", e.GetType().Name, Environment.NewLine);
log += string.Format("Source.....: {0}{1}", e.Source, Environment.NewLine);
log += string.Format("Message....: {0}{1}", e.Message, Environment.NewLine);
log += string.Format("Stack Trace: {0}", e.StackTrace.Trim());
e = e.InnerException;
log += Environment.NewLine + new string('-', 80) + Environment.NewLine;
}
if (_mode == "EventLog")
{
WriteToEventLog(log);
}
else if (_mode == "File")
{
WriteToFile(log);
}
}
/// <summary>
/// Log application into file/eventviewer according to configuration of application file.
/// </summary>
/// <param name="e">Valid instance of an ServiceException object.</param>
/// ####
//public static void Write(ServiceException e)
//{
// Write(e as Exception);
//}
private ExceptionLog()
{
}
}
internal sealed class AppConfigParser
{
private Dictionary<string, string> _attributes;
public void Parse(string configValue)
{
_attributes = new Dictionary<string, string>();
string[] segments = configValue.Trim().Split(';');
foreach (string segment in segments)
{
string[] keyValue = segment.Trim().Split('=');
if (keyValue.Length != 2)
continue;
string key = keyValue[0].Trim();
string value = keyValue[1].Trim();
_attributes.Add(key, value);
}
}
public bool Contains(string key)
{
return _attributes.ContainsKey(key);
}
public string this[string key]
{
get { return _attributes[key]; }
}
public AppConfigParser()
{
}
}
#endregion
}

1590
Ease.Core/Utility/Global.cs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Text;
using System.Collections.Generic;
namespace Ease.Core.Utility
{
public interface IAsyncStatusHandle
{
void UpdateStatus(string msg, params object[] args);
bool CancelRequested();
}
}

View File

@ -0,0 +1,23 @@
using System.Security.Cryptography;
using System.Text;
namespace Ease.Core.Utility
{
/// <summary>
/// The key every JWT of the application is signed and validated with (HmacSha512Signature).
/// Since Microsoft.IdentityModel 7 (.NET 8+ JwtBearer), HS512 refuses a key shorter than 512 bits
/// (IDX10720), so a shorter AppSettings.Secret is stretched to 64 bytes with SHA-512. A secret of
/// 64 bytes or more is used as it is. Token issuing and token validation must both use this, or
/// every login fails with an invalid signature.
/// </summary>
public static class JwtSigningKey
{
private const int MinimumKeyBytes = 64;
public static byte[] FromSecret(string secret)
{
byte[] key = Encoding.ASCII.GetBytes(secret);
return key.Length >= MinimumKeyBytes ? key : SHA512.HashData(key);
}
}
}

View File

@ -0,0 +1,179 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Ease.Core.Utility
{
//public sealed class LateBoundObject : IDisposable
//{
// private Type _t;
// private object _o;
// private Context _ctx;
// #region Context
// private class Context
// {
// private List<LateBoundObject> _objects = new List<LateBoundObject>();
// public void AddObject(LateBoundObject o)
// {
// _objects.Add(o);
// }
// public void Release()
// {
// foreach (LateBoundObject lbo in _objects)
// {
// if (lbo != null && lbo._o != null && Marshal.IsComObject(lbo._o))
// {
// try
// {
// Marshal.ReleaseComObject(lbo._o);
// }
// catch { }
// }
// }
// }
// }
// #endregion
// public static bool IsValidProgID(string progID)
// {
// Type t = Type.GetTypeFromProgID(progID);
// return t != null;
// }
// private LateBoundObject(Context ctx, object o)
// {
// _ctx = ctx;
// _ctx.AddObject(this);
// _o = o;
// if (_o != null)
// _t = _o.GetType();
// }
// public LateBoundObject(string progID)
// {
// _ctx = new Context();
// _ctx.AddObject(this);
// _t = Type.GetTypeFromProgID(progID);
// if (_t == null)
// throw new ArgumentException("Invalid ProgID " + progID, "progID");
// try
// {
// _o = _t.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public object Value
// {
// get { return _o; }
// }
// public LateBoundObject GetProperty(string name)
// {
// try
// {
// return new LateBoundObject(_ctx, _t.InvokeMember(name, BindingFlags.GetProperty, null, _o, null));
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public LateBoundObject GetProperty(string name, params object[] args)
// {
// try
// {
// return new LateBoundObject(_ctx, _t.InvokeMember(name, BindingFlags.GetProperty, null, _o, args));
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public void SetProperty(string name, object val)
// {
// try
// {
// _t.InvokeMember(name, BindingFlags.SetProperty, null, _o, new object[] { val });
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public void SetProperty(string name, object val, params object[] args)
// {
// try
// {
// object[] args1 = new object[args.Length + 1];
// args.CopyTo(args1, 0);
// args1[args1.Length - 1] = val;
// _t.InvokeMember(name, BindingFlags.SetProperty, null, _o, args1);
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public LateBoundObject ExecuteMethod(string name, params object[] args)
// {
// try
// {
// return new LateBoundObject(_ctx, _t.InvokeMember(name, BindingFlags.InvokeMethod, null, _o, args));
// }
// catch (TargetInvocationException e)
// {
// if (e.InnerException != null)
// throw e.InnerException;
// else
// throw;
// }
// }
// public void Dispose()
// {
// _ctx.Release();
// }
//}
}

View File

@ -0,0 +1,478 @@
/*
|-------------------------------------------------------------------------------|
| Copyright © Computer Ease Limited |
| Address: 1/9 Bloack-A Lalmatia, Dhaka-1207, Bangladesh |
| Email: info@celimited.com, cease@bol-online.com, web: www.celimited.com |
| Unauthorized copy or distribution is strictly prohibited |
| Author: S. M. Russel, Last modified date: 23/07/2012 |
|-------------------------------------------------------------------------------|
*/
using System;
using System.Reflection;
using System.Collections;
using System.Globalization;
namespace Ease.Core.Utility
{
#region Framework: Object utility
/// <summary>
/// Summary description for ObjectUtility.
/// </summary>
public sealed class ObjectUtility
{
#region Create Instance
/// <summary>
/// Create instance reference of an object for the given class full name
/// </summary>
/// <param name="className">A valid class name</param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string className)
{
return ObjectUtility.CreateInstance(className, null);
}
/// <summary>
/// Create instance reference of an object for the given class full name
/// </summary>
/// <param name="className">A valid class name</param>
/// <param name="args">Argument with comma separated</param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string className, object[] args)
{
return ObjectUtility.CreateInstance(className, args, typeof(ObjectUtility));
}
/// <summary>
/// Create instance reference of an object for the given class full name
/// </summary>
/// <param name="className">A valid class name</param>
/// <param name="args"></param>
/// <param name="type">Type of object to be created </param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string className, object[] args, System.Type type)
{
return ObjectUtility.CreateInstance(className, args, type, true);
}
/// <summary>
/// Create instance reference of an object for the given class full name
/// into the given assembly
/// </summary>
/// <param name="assembly">A valid assembly name and must be located withing the same folder</param>
/// <param name="className">A valid class name</param>
/// <param name="args"></param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string assembly, string className, object[] args)
{
return ObjectUtility.CreateInstance(assembly, className, args, true);
}
/// <summary>
/// Create instance reference of an object for the given class full name
/// into the given assembly
/// </summary>
/// <param name="assembly">A valid assembly name and must be located withing the same folder</param>
/// <param name="className">A valid class name</param>
/// <param name="args"></param>
/// <param name="throwNullError"></param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string assembly, string className, object[] args, bool throwNullError)
{
Type type = null;
Assembly asm = null;
try
{
asm = Assembly.Load(assembly);
}
catch (Exception ex)
{
throw new ArgumentException(
string.Format("Failed to load the assembly '{0}' due to following message:\n{1}", assembly,
ex.Message), "assembly", ex);
}
try
{
type = asm.GetType(className, true);
}
catch (Exception ex)
{
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Class {0} does not exists in assembly {1}", className,
asm.FullName), "className", ex);
}
return ObjectUtility.CreateInstance(className, args, type, throwNullError);
}
/// <summary>
/// Create instance reference of an object for the given class full name
/// </summary>
/// <param name="className"></param>
/// <param name="args"></param>
/// <param name="type"></param>
/// <param name="throwNullError"></param>
/// <returns>Returns an instance of the class</returns>
public static object CreateInstance(string className, object[] args, System.Type type, bool throwNullError)
{
if (type == null)
type = typeof(ObjectUtility);
object obj = null;
if (args == null)
obj = type.Assembly.CreateInstance(className);
else
obj = type.Assembly.CreateInstance(className, false,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, args, null, null);
if (obj == null && throwNullError)
throw new ArgumentException(string.Format("Class {0} does not exists in assembly {1}", className,
type.Assembly.FullName));
return obj;
}
#endregion
#region Get Custome Attribute
/// <summary>
/// Finds out the custom attribute in the value
/// </summary>
/// <param name="Type">Tyep of attribute</param>
/// <param name="value">Instance of an object </param>
/// <returns>Returns the attribute if found otherwise null</returns>
public static object GetCustomAttribute(Type type, object value)
{
if (type == null || value == null)
return null;
object[] attrs = null;
Type valueType = value.GetType();
if (valueType.IsEnum)
{
FieldInfo field = valueType.GetField(value.ToString());
if (field == null)
return null;
attrs = field.GetCustomAttributes(type, true);
}
else
{
if (value is PropertyInfo)
attrs = ((PropertyInfo)value).GetCustomAttributes(type, true);
else
attrs = valueType.GetCustomAttributes(type, true);
}
if (attrs != null && attrs.Length > 0)
return attrs[0];
return null;
}
/// <summary>
/// Find out the property from the given type, where property can
/// consists of key path.
/// </summary>
/// <param name="type"></param>
/// <param name="property"></param>
/// <returns>Returns PropertyInfo object of the given property</returns>
public static object GetProperty(Type type, string property)
{
if (type == null || string.IsNullOrEmpty(property))
return null;
if (property.IndexOf(".") == -1)
return type.GetProperty(property,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
PropertyInfo propertyInfo = null;
string[] propertyPath = property.Split('.');
foreach (string prop in propertyPath)
{
if (!string.IsNullOrEmpty(prop))
{
propertyInfo = type.GetProperty(prop,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (propertyInfo == null)
return null;
type = propertyInfo.PropertyType;
}
}
return propertyInfo;
}
#endregion
#region Get Property Value
/// <summary>
/// Find out the property from the given type, where property can
/// consists of key path and returns the value of the property
/// </summary>
/// <param name="source"></param>
/// <param name="property"></param>
/// <returns>Returns value of the given property</returns>
public static object GetPropertyValue(object source, string property)
{
return ObjectUtility.GetPropertyValue(source, property, new object[] { });
}
/// <summary>
/// Find out the property from the given type, where property can
/// consists of key path and returns the value of the property
/// </summary>
/// <param name="source"></param>
/// <param name="property"></param>
/// <param name="indexes"></param>
/// <returns>Returns value of the given property</returns>
public static object GetPropertyValue(object source, string property, object[] indexes)
{
if (source == null || string.IsNullOrEmpty(property))
return null;
if (property.IndexOf(".") == -1)
return source.GetType().GetProperty(property).GetValue(source, indexes);
string[] propertyPath = property.Split('.');
foreach (string prop in propertyPath)
{
if (!(string.IsNullOrEmpty(prop)))
{
PropertyInfo propertyInfo = source.GetType().GetProperty(prop);
if (propertyInfo == null)
return null;
source = propertyInfo.GetValue(source, indexes);
}
}
return source;
}
#endregion
#region Get Properties
/// <summary>
/// Find out all properties that have set functionality from the given type
/// </summary>
/// <param name="type"></param>
/// <returns>Returns list of PropertyInfo object of the given type</returns>
public static object[] GetProperties(Type type)
{
if (type == null)
return null;
return (object[])type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
/// <summary>
/// Find out all properties that have set functionality from the given type
/// </summary>
/// <param name="type"></param>
/// <param name="attributeType"></param>
/// <returns>Returns list of PropertyInfo object of the given type</returns>
public static object[] GetProperties(Type type, Type attributeType)
{
ArrayList list = new ArrayList();
if (attributeType != null)
{
PropertyInfo[] props = (PropertyInfo[])ObjectUtility.GetProperties(type);
foreach (PropertyInfo prop in props)
{
object[] attributes = prop.GetCustomAttributes(attributeType, true);
if (attributes != null && attributes.Length > 0)
list.Add(prop);
}
}
return (object[])list.ToArray(typeof(PropertyInfo));
}
/// <summary>
/// Find out all properties that have set functionality from the given type
/// </summary>
/// <param name="type"></param>
/// <param name="attributeType"></param>
/// <param name="includeChildProperties"></param>
/// <returns>Returns list of PropertyInfo object of the given type</returns>
public static object[] GetProperties(Type type, Type attributeType, bool includeChildProperties,
Type ignoreType)
{
ArrayList list = new ArrayList();
if (attributeType != null)
{
PropertyInfo[] props = (PropertyInfo[])ObjectUtility.GetProperties(type);
foreach (PropertyInfo prop in props)
{
object[] attributes = prop.GetCustomAttributes(attributeType, true);
if (attributes != null && attributes.Length > 0)
list.Add(prop);
else
{
if (includeChildProperties && prop.PropertyType.BaseType != null
&& prop.PropertyType.BaseType.Equals(type.BaseType))
{
attributes = prop.GetCustomAttributes(ignoreType, true);
if (attributes != null && attributes.Length == 0)
list.AddRange(ObjectUtility.GetProperties(prop.PropertyType, attributeType,
includeChildProperties, ignoreType));
}
}
}
}
return (object[])list.ToArray(typeof(PropertyInfo));
}
#endregion
#region Get Source Property Value
/// <summary>
/// Find the property value from the given object
/// </summary>
/// <param name="source"></param>
/// <param name="property"></param>
/// <returns></returns>
public static object GetSourcePropertyValue(object source, object property)
{
PropertyInfo prop = property as PropertyInfo;
if (prop == null)
return source;
object src = source;
if (source.GetType().Equals(prop.DeclaringType) == false)
{
src = null;
PropertyInfo[] props = (PropertyInfo[])ObjectUtility.GetProperties(source.GetType());
if (props != null && props.Length > 0)
{
foreach (PropertyInfo sourceProp in props)
{
if (sourceProp.PropertyType.Equals(prop.DeclaringType))
{
src = ObjectUtility.GetPropertyValue(source, sourceProp.Name);
break;
}
else
{
if (sourceProp.PropertyType.BaseType != null &&
sourceProp.PropertyType.BaseType.Equals(prop.DeclaringType.BaseType))
{
object objVal = ObjectUtility.GetPropertyValue(src, sourceProp.Name);
if (objVal != null)
src = ObjectUtility.GetSourcePropertyValue(objVal, prop);
if (src != null)
break;
}
}
}
}
}
return src;
}
#endregion
#region Set Property
/// Find out the property from the given object, where property can
/// consists of key path and set the value for that property.
/// </summary>
/// <param name="source"></param>
/// <param name="property"></param>
/// <param name="value"></param>
/// <param name="index"></param>
public static void SetProperty(object source, object property, object value, object[] index)
{
PropertyInfo pi = property as PropertyInfo;
if (pi == null)
return;
object src = ObjectUtility.GetSourcePropertyValue(source, pi);
if (src != null)
ObjectUtility.SetProperty(src, pi.Name, value, index);
}
/// <summary>
/// Find out the property from the given object, where property can
/// consists of key path and set the value for that property.
/// </summary>
/// <param name="source"></param>
/// <param name="propertyName"></param>
/// <param name="value"></param>
/// <param name="index"></param>
public static void SetProperty(object source, string propertyName, object value, object[] index)
{
PropertyInfo prop = (PropertyInfo)ObjectUtility.GetProperty(source.GetType(), propertyName);
if (prop == null)
throw new ArgumentNullException(string.Format(CultureInfo.CurrentCulture,
"Class {0} does not have a property named {1}", source.GetType().FullName, propertyName));
try
{
if (prop.PropertyType.IsEnum)
prop.SetValue(source, Enum.Parse(prop.PropertyType, value.ToString(), true), index);
else if (prop.PropertyType.Equals(typeof(bool)))
prop.SetValue(source, Convert.ToBoolean(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(DateTime)))
prop.SetValue(source, Convert.ToDateTime(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(double)))
prop.SetValue(source, Convert.ToDouble(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(decimal)))
prop.SetValue(source, Convert.ToDecimal(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(Int16)))
prop.SetValue(source, Convert.ToInt16(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(Int32)))
prop.SetValue(source, Convert.ToInt32(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(Int64)))
prop.SetValue(source, Convert.ToInt64(value, CultureInfo.CurrentCulture), index);
else if (prop.PropertyType.Equals(typeof(byte)))
prop.SetValue(source, Convert.ToByte(value, CultureInfo.CurrentCulture), index);
else
prop.SetValue(source, value, index);
}
catch
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
"System failed to set value for property named {0} of class {1}", prop.Name,
source.GetType().FullName));
}
}
#endregion
}
#endregion
}

View File

@ -0,0 +1,405 @@

using System;
using System.IO;
using System.Text;
using System.Data;
using System.Diagnostics;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
using Ease.Core.Model;
using System.Collections.Generic;
namespace Ease.Core.Utility
{
public class ZipHelper
{
#region Constructor
private ZipHelper()
{
}
#endregion
#region Compress functions
/// <summary>
/// Compress string.
/// </summary>
/// <param name="text">Text to be compressed.</param>
/// <returns>Return compressed string. </returns>
public static string Compress(string text)
{
byte[] compressed;
try
{
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] zipBuffer = new byte[ms.Length];
ms.Read(zipBuffer, 0, zipBuffer.Length);
compressed = new byte[zipBuffer.Length + 4];
Buffer.BlockCopy(zipBuffer, 0, compressed, 4, zipBuffer.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressed, 0, 4);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Convert.ToBase64String(compressed);
}
/// <summary>
/// Compress a DataSet.
/// </summary>
/// <param name="data">DataSet to be compressed.</param>
/// <returns>Return comressed string.</returns>
public static string Compress(DataSet data)
{
byte[] compressed;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
data.WriteXml(zip, XmlWriteMode.WriteSchema);
}
compressed = ms.ToArray();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Convert.ToBase64String(compressed);
}
/// <summary>
/// Compress a DataTable.
/// </summary>
/// <param name="data">DatTable to be compressed.</param>
/// <returns>Return comressed string.</returns>
public static string Compress(DataTable data)
{
byte[] compressed;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
data.WriteXml(zip, XmlWriteMode.WriteSchema);
}
compressed = ms.ToArray();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Convert.ToBase64String(compressed);
}
/// <summary>
/// Compress instance of an object.
/// </summary>
/// <typeparam name="T">Type of object to be compressed.</typeparam>
/// <param name="ot">Instatnce of T type object.</param>
/// <returns>Return compressed string.</returns>
public static string Compress<T>(T ot)
where T : ObjectTemplate
{
byte[] compressed;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(zip, ot);
}
compressed = ms.ToArray();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Convert.ToBase64String(compressed);
}
/// <summary>
/// Compress instance of an object of type T.
/// </summary>
/// <typeparam name="T">>Type of object</typeparam>
/// <param name="ost">Instatnce of T type object collection.</param>
/// <returns>Return compressed string.</returns>
public static string Compress<T>(List<T> ost)
where T : ObjectTemplate
{
byte[] compressed;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(zip, ost);
}
compressed = ms.ToArray();
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Convert.ToBase64String(compressed);
}
/// <summary>
/// Compress a file
/// </summary>
/// <param name="srcFileName">Name of the file to be compressed.</param>
/// <param name="fileName">Name of the compressed file to be saved.</param>
public static void Compress(string srcFileName, string fileName)
{
try
{
byte[] buffer;
using (FileStream fsSrc = new FileStream(srcFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
buffer = new byte[fsSrc.Length];
fsSrc.Read(buffer, 0, buffer.Length);
}
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (GZipStream zip = new GZipStream(fs, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
#endregion
#region Decompress functions
/// <summary>
/// Convert from compressed string into actual string.
/// </summary>
/// <param name="text">Compressed string to be decompressed.</param>
/// <returns>Return actual string after decompression. </returns>
public static string Decompress(string text)
{
byte[] buffer;
try
{
using (MemoryStream ms = new MemoryStream())
{
byte[] data = Convert.FromBase64String(text);
int length = BitConverter.ToInt32(data, 0);
ms.Write(data, 4, data.Length - 4);
buffer = new byte[length];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return Encoding.UTF8.GetString(buffer);
}
/// <summary>
/// Reconstruct actual DataSet.
/// </summary>
/// <param name="text">Compressed string to be decompressed.</param>
/// <returns>Return actual DataSet.</returns>
public static DataSet DecompressDataSet(string text)
{
DataSet ds = new DataSet();
try
{
byte[] data = Convert.FromBase64String(text);
using (MemoryStream ms = new MemoryStream(data))
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
ds.ReadXml(zip, XmlReadMode.ReadSchema);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return ds;
}
/// <summary>
/// Reconstruct actual DataTable.
/// </summary>
/// <param name="text">Compressed string to be decompressed.</param>
/// <returns>Return actual DataTable.</returns>
public static DataTable DecompressDataTable(string text)
{
DataTable dt = new DataTable();
try
{
byte[] data = Convert.FromBase64String(text);
using (MemoryStream ms = new MemoryStream(data))
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
dt.ReadXml(zip);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return dt;
}
/// <summary>
/// Reconstruct the actual object.
/// </summary>
/// <typeparam name="T">Type of object to be decompressed.</typeparam>
/// <param name="text">Compressed string to be decompressed.</param>
/// <returns>Return ObjectTemplate of type T</returns>
public static T DecompressObject<T>(string text)
where T : ObjectTemplate
{
T instance;
try
{
byte[] data = Convert.FromBase64String(text);
using (MemoryStream ms = new MemoryStream(data))
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
BinaryFormatter bf = new BinaryFormatter();
instance = (T)bf.Deserialize(zip);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return instance;
}
/// <summary>
/// Reconstruct the actual objects.
/// </summary>
/// <typeparam name="T">Type of object to be decompressed.</typeparam>
/// <param name="text">Compressed string to be decompressed.</param>
/// <returns>Return collection ObjectTemplate of type T</returns>
public static List<T> DecompressObjects<T>(string text)
where T : ObjectTemplate
{
List<T> instance;
try
{
byte[] data = Convert.FromBase64String(text);
using (MemoryStream ms = new MemoryStream(data))
{
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
BinaryFormatter bf = new BinaryFormatter();
instance = (List<T>)bf.Deserialize(zip);
}
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return instance;
}
/// <summary>
/// Decompress source file.
/// </summary>
/// <param name="srcFileName">Name of the compressed file.</param>
/// <param name="fileName">Name of the decompressed file to be saved.</param>
public static void Decompress(string srcFileName, string fileName)
{
try
{
int length = 0;
const int bz = 4096;
DateTime ct = DateTime.Now;
byte[] buffer = new byte[bz];
FileStream fsi = new FileStream(srcFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
FileStream fso = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
using (GZipStream zip = new GZipStream(fsi, CompressionMode.Decompress, true))
{
while (true)
{
length = zip.Read(buffer, 0, bz);
if (length != 0)
fso.Write(buffer, 0, length);
if (length != bz)
break;
}
}
if (fso != null)
{
fso.Close();
fso.Dispose();
fso = null;
}
if (fsi != null)
{
fsi.Close();
fsi.Dispose();
fsi = null;
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
#endregion
}
}

18
Ease.Core/jsconfig1.json Normal file
View File

@ -0,0 +1,18 @@
{
"exclude": [
"**/bin",
"**/bower_components",
"**/jspm_packages",
"**/node_modules",
"**/obj",
"**/platforms"
],
"connectionString": {
"Conn": "server=cel60;Database=Armada_new;User ID=sa;Password=;provider=sql;sqlSyntax=SQL;",
"Conn1": "server=cel60;Database=Armada_new;User ID=sa;Password=;provider=sql;sqlSyntax=SQL;",
"Default": "server=cel60;Database=Armada_new;User ID=sa;Password=;provider=sql;sqlSyntax=SQL;"
}
}

View File

@ -0,0 +1,16 @@
# Editor configuration, see http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false
[*.{razor,cshtml}]
charset = utf-8-bom

41
Erecruitment.UI/ClientApp/.gitignore vendored Normal file
View File

@ -0,0 +1,41 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/dist-server
/tmp
/out-tsc
# dependencies
/node_modules
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# misc
/.angular/cache
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,27 @@
# Erecruitment_Angular
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.0.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

View File

@ -0,0 +1,146 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"cli": {
"analytics": "b51a5acb-37a6-45fe-b7a1-14830c13f930"
},
"version": 1,
"newProjectRoot": "projects",
"projects": {
"Erecruitment_Angular": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"progress": false,
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": ["src/assets"],
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/font-awesome/css/font-awesome.css",
"src/styles.scss"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/@popperjs/core/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"vendorChunk": true,
"extractLicenses": false,
"buildOptimizer": false,
"sourceMap": true,
"optimization": false,
"namedChunks": true
},
"configurations": {
"production": {
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
},
"defaultConfiguration": ""
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "Erecruitment_Angular:build"
},
"configurations": {
"production": {
"browserTarget": "Erecruitment_Angular:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "Erecruitment_Angular:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.scss" ],
"scripts": [
],
"assets": ["src/assets"]
}
},
"server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist-server",
"main": "src/main.ts",
"tsConfig": "src/tsconfig.server.json",
"sourceMap": true,
"optimization": false
},
"configurations": {
"dev": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true
},
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true
}
},
"defaultConfiguration": ""
}
}
},
"Erecruitment_Angular-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "Erecruitment_Angular:serve"
}
}
}
}
},
"defaultProject": "Erecruitment_Angular"
}

View File

@ -0,0 +1,9 @@
# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For IE 9-11 support, please uncomment the last line of the file and adjust as needed
> 0.5%
last 2 versions
Firefox ESR
not dead
# IE 9-11

View File

@ -0,0 +1,28 @@
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require("jasmine-spec-reporter");
exports.config = {
allScriptsTimeout: 11000,
specs: ["./src/**/*.e2e-spec.ts"],
capabilities: {
browserName: "chrome"
},
directConnect: true,
baseUrl: "http://localhost:4200/",
framework: "jasmine",
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require("ts-node").register({
project: require("path").join(__dirname, "./tsconfig.e2e.json")
});
jasmine
.getEnv()
.addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

View File

@ -0,0 +1,14 @@
import { AppPage } from './app.po';
describe('App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getMainHeading()).toEqual('Hello, world!');
});
});

View File

@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get('/');
}
getMainHeading() {
return element(by.css('app-root h1')).getText();
}
}

View File

@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

27303
Erecruitment.UI/ClientApp/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,86 @@
{
"name": "erecruitment_angular",
"version": "13.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build:ssr": "ng run Erecruitment_Angular:server:dev",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~13.0.2",
"@angular/cdk": "~13.0.2",
"@angular/common": "~13.0.2",
"@angular/compiler": "~13.0.2",
"@angular/core": "~13.0.2",
"@angular/forms": "~13.0.2",
"@angular/platform-browser": "~13.0.2",
"@angular/platform-browser-dynamic": "~13.0.2",
"@angular/router": "~13.0.2",
"@angular2-material/button-toggle": "^2.0.0-alpha.8-3",
"@auth0/angular-jwt": "^5.0.2",
"@nguniversal/module-map-ngfactory-loader": "~8.2.6",
"@popperjs/core": "^2.11.8",
"@progress/kendo-angular-common": "^2.0.0",
"@progress/kendo-angular-dateinputs": "^5.2.1",
"@progress/kendo-angular-dialog": "5.1.0",
"@progress/kendo-angular-dropdowns": "^5.3.0",
"@progress/kendo-angular-inputs": "^8.0.0",
"@progress/kendo-angular-intl": "^3.0.0",
"@progress/kendo-angular-l10n": "^3.0.0",
"@progress/kendo-angular-label": "^3.1.0",
"@progress/kendo-angular-layout": "6.1.8",
"@progress/kendo-angular-popup": "^4.0.0",
"@progress/kendo-angular-treeview": "5.4.0",
"@progress/kendo-drawing": "^1.9.3",
"@progress/kendo-licensing": "^1.2.2",
"@progress/kendo-theme-bootstrap": "4.40.1",
"@progress/kendo-theme-default": "4.40.1",
"@progress/kendo-theme-material": "4.40.1",
"@types/google-one-tap": "^1.2.2",
"@types/jquery": "^3.5.16",
"bootstrap": "^5.3.1",
"core-js": "^3.20.2",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"oidc-client": "~1.11.5",
"popper.js": "^1.16.1",
"resolve-url-loader": "^5.0.0",
"rxjs": "^6.6.3",
"tslib": "^2.0.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^13.2.4",
"@angular/cli": "~13.0.2",
"@angular/compiler-cli": "~13.0.2",
"@angular/localize": "^13.1.0",
"@types/jasmine": "~3.6.0",
"@types/jasminewd2": "~2.0.8",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"ini": "^1.3.7",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~6.4.1",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"typescript": "~4.4.3",
"url": "^0.11.0"
},
"optionalDependencies": {
"node-sass": "^5.0.0",
"protractor": "~7.0.0",
"ts-node": "~8.4.1",
"tslint": "~6.1.0"
},
"resolutions": {
"url-parse": ">=1.5.0",
"lodash": ">=4.17.21"
}
}

View File

@ -0,0 +1,26 @@
import { Injectable, EventEmitter } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../_services/auth/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
public menuEvent: EventEmitter<boolean>;
constructor(private authService: AuthService, private router: Router) {
this.menuEvent = new EventEmitter();
}
canActivate(): boolean {
if (this.authService.loggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
//public getMenuList(): any {
// return JSON.parse(localStorage.getItem('menuList'));
//}
}

View File

@ -0,0 +1,64 @@
import { EnumExtension} from '../../_models/enums';
export class ErAppliedApplicant {
id: number;
userID: number;
jobID: number;
applyDate: Date;
applicationAcknowldged: boolean;
isSelectedforInterview: boolean;
isOfferLetteraccepted: boolean;
offerletterRejectReason: string;
offerLetterIssueDate: Date;
offerletterAcceptDate: Date;
constructor() {
this.offerletterRejectReason = '';
this.applicationAcknowldged = false;
this.isSelectedforInterview = false;
this.isOfferLetteraccepted = false;
}
}
export class ErJobUpdate {
id: number;
userID: number;
jobID: number;
appliedApplicantID: number;
isAcknowledged: boolean;
acknowledgeDate: Date;
referenceID: number;
description: string;
remarks: string;
updateDate: Date;
constructor() {
}
}
export class ErApplicantDoc {
id: number;
userID: number;
appliedApplicantID: number;
originalFileName: string;
remarks: string;
createdDate: Date;
fileTobase64: string;
constructor() {
}
}

View File

@ -0,0 +1,12 @@
import {BaseObject} from '../Basic/baseObject';
export class Occupation extends BaseObject {
constructor() {
super();
this.code = '';
this.description = '';
}
id: number;
code: string;
description: string;
}

View File

@ -0,0 +1,9 @@
import {BaseObject} from '../Basic/baseObject';
export class Relation extends BaseObject {
constructor() {
super();
}
description: string;
code: string;
}

View File

@ -0,0 +1,9 @@
import {BaseObject} from '../Basic/baseObject';
export class Religion extends BaseObject {
constructor() {
super();
}
code: string;
name: string;
}

View File

@ -0,0 +1,10 @@
import {BaseObject} from '../Basic/baseObject';
export class ResultType extends BaseObject {
constructor() {
super();
}
code: string;
description: string;
cgpa: boolean;
}

View File

@ -0,0 +1,20 @@
import { EnumStatus } from '../enums';
export class BaseObject {
constructor() {
this.stepSerial = 0;
this.status = EnumStatus.Regardless;
this.createdDate = new Date();
this.id = 0;
this.createdBy = 0;
}
id: number;
stepSerial: number;
status: EnumStatus;
modifiedBy?: number;
createdDate: Date;
createdBy: number;
modifiedDate?: Date;
formControlname: string;
}

View File

@ -0,0 +1,80 @@
import { EnumEntryMode, EnumCicularColumnType } from '../enums';
export class ErCircular {
id: number;
recruitementID: number;
publishFrom: Date;
publishTo: Date;
erCircularDetails: ErCircularDetail[] = [];
}
export class ErCircularDetail{
id: number;
columnType: EnumCicularColumnType;
pAutoFocus: boolean;
description: string;
remarks: string;
erCircularID: string;
}
export class ErCircularDetailData {
Position: string;
CompanyName: string;
KeySellingPoints: string;
Vacancy: number;
JobContext: string;
JobResponsibilities: string;
EmploymentStatus: string;
Workplace: string;
EducationalRequirements: string;
ExperienceRequirements :string;
AdditionalRequirements: string;
JobLocation :string;
Salary: string;
CompensationandOtherBenefits: string;
JobSource: string;
PublishToDate: string;
multipleEdReq: string[] = [];
Id: number;
IsApplied: boolean = false;
}
export class ErCircularJobDetails {
constructor() {
this.educationalRequirements = [];
this.experienceRequirements = [];
this.additionalRequirements = [];
this.keySellingPoints = [];
this.compensationandOtherBenefits = [];
this.jobResponsibilities = [];
this.vacancy = "0";
this.salary = "0";
}
position: string;
companyName: string;
keySellingPoints: string[];
vacancy: string;
jobContext: string;
jobResponsibilities: string[];
employmentStatus: string;
workplace: string;
educationalRequirements: string[];
experienceRequirements: string[];
additionalRequirements: string[];
jobLocation: string;
salary: string;
compensationandOtherBenefits: string[];
jobSource: string;
multipleEdReq: string[];
}
export class InterviewDetails {
stepName: string;
interviewRTime: string;
IsSelected: string;
}

View File

@ -0,0 +1,15 @@
export class Discipline {
code: string;
description: string;
id: number;
disciplineLevels: DisciplineLevel[] = [];
}
class DisciplineLevel {
constructor() {
this.disciplineID = 0;
this.levelID = 0;
}
disciplineID: number;
levelID: number;
}

View File

@ -0,0 +1,12 @@
import { BaseObject } from '../../_models/Basic/baseObject';
export class EducationLevel extends BaseObject {
constructor() {
super();
}
code: string;
description: string;
educationTypeID: number;
educationType: any;
concentration: string;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,156 @@
import { SafeResourceUrl } from '@angular/platform-browser';
import { EnumEntryMode, EnumCicularColumnType, EnumTrainingCompletedFrom, EnumProfileStatus, EnumGender, EnumMaritalStatus, EnumOnBoradStatus } from '../enums';
import { Institution } from '../institutions/institution';
import { NatureOfTraining } from './nature-of-training';
import { TrainingType } from './training-type';
export class FileAttachment {
// FileAttachment- copied from branches\SanofiNew\HRM.UI\ClientApp\src\app\_models\common\uploadFile.ts
constructor() {
// this.UploaderModule = 24;
// this.UploadDate = new Date();
}
id: number;
referenceID: number;
originalFileName: string;
filePath: string;
fileTobase64: string;
previousFileTobase64: string;
serialNo: number;
fileAsByteArray: any;
fileType: number;
profilePhotoUrl: any;
}
export class ErCV {
id: number;
name: string;
firstName: string;
lastName: string;
email: string;
mobile: string;
designation: string;
presentAddress: string;
permanentAddress: string;
gender: EnumGender;
maritalStatus: EnumMaritalStatus;
sortStatus: string;
religionID: number;
erCVProfilePhoto: FileAttachment;
dateOfBirth: Date;
allExperiences: ErCVExperience[];
allEduQualifications: ErCVEducation[];
cvReferences: ErCVReference[];
cvTrainings: ErCVTraining[];
irFileAttacments: FileAttachment[];
positionID: number;
positionStatus: EnumOnBoradStatus;
candidateID: number;
}
export class ErCVEducation {
constructor() {
this.isNew = true;
this.isSave = false;
}
id: number;
degreeTitleID: number;
degreeTitle: string;
disciplineID: number;
discipline: number;
boardID: number;
board: string;
name: string;
passingYear: string;
resultID: number;
cgpa :string;
outOF: string;
isHighest :boolean;
instituteName: string;
cvID: number;
isNew: boolean;
isSave: boolean;
duration: string;
achievement: string;
}
export class ErCVExperience {
constructor() {
}
id: number;
employeer: string;
contactPerson: string;
address: string;
industry: string;
designation: string;
fromDate: Date;
toDate: Date;
telephone: string;
roleDefination: string;
cvid: number;
mobile: string;
}
export class ErCVReference {
constructor() {
}
id: number;
name: string;
occupation: string;
relation: string;
address: string;
email: string;
telephone: string;
mobile: string;
cvid: number;
}
export class ErCVTraining {
constructor() {
}
id: number;
trainingTypeID: number;
trainingType: TrainingType;
natureOfTrainingID: number;
natureOfTraining: NatureOfTraining;
trainingCompletedFrom: EnumTrainingCompletedFrom;
description: string;
countryID: number;
instituteName: string;
institutionID: number;
institution: Institution;
place: string;
achievement: string;
fees: number;
name: string;
otherCost: number;
fromDate: Date;
fromDateString: string;
toDate: Date;
toDateString: Date;
trainingMonth: number;
trainingDay: number;
trainingHour: number;
confirmationDate: Date;
profileStatus: EnumProfileStatus;
days: string;
hours: string;
}

View File

@ -0,0 +1,9 @@
import {BaseObject} from '../Basic/baseObject';
export class NatureOfTraining extends BaseObject {
constructor() {
super();
}
code: string;
name: string;
}

View File

@ -0,0 +1,11 @@
import { BaseObject } from '../Basic/baseObject';
export class TrainingType extends BaseObject {
constructor() {
super();
}
code: string;
name: string;
}

View File

@ -0,0 +1,9 @@
import { EnmInstituteType } from "../enums";
export class Institution {
id: number;
code: string;
name: string;
type: EnmInstituteType;
educationTypeID: number;
}

View File

@ -0,0 +1,183 @@
import { EnumExtension, EnumPURequestType, EnumReplacementDueTo, enumwfStatus, EnumAssetStatus, EnumAssetTranType, EnumAssetReceiverType, EnumSurveyQuestionType } from '../../_models/enums';
export class QuestionCategory {
id: number;
questionCategoryID: number;
modifiedBy?: number;
createdDate: Date;
createdBy: number;
modifiedDate?: Date;
code: string;
description: string;
constructor() {
this.code = '';
this.description = '';
}
}
export class Question {
id: number;
questionNo: string;
categoryID: number;
modifiedBy?: number;
creationDate: Date;
createdBy: number;
modifiedDate?: Date;
questionBody: string;
image: string;
isMultiple: boolean;
isPublished: boolean;
noOfOptions: number;
categoryString: string;
estimatedTime: number;
questionType: EnumSurveyQuestionType;
category: QuestionCategory;
questionAnswers: QuestionAnswer[];
questionAnswerAttachments: QuestionAnswerAttachment[];
constructor() {
this.questionNo = '';
this.isMultiple = false;
this.isPublished = false;
this.questionAnswers = [];
this.questionAnswerAttachments = [];
this.questionType = EnumSurveyQuestionType.Multiple_Choice;
}
}
export class QuestionAnswer {
id: number;
answerID: number;
questionID: number;
modifiedBy?: number;
creationDate: Date;
createdBy: number;
modifiedDate?: Date;
answerBody: string;
image: string;
myFiles: any;
isCorrect: boolean;
displayOrder: number;
weight: number;
numericAnswer: number;
isCandidateAnswer: boolean;
questionAnswerAttachments: QuestionAnswerAttachment[];
imageFile: any;
constructor() {
this.answerBody = '';
this.isCorrect = false;
this.questionAnswerAttachments = [];
this.isCandidateAnswer = false;
}
}
export class QuestionAnswerAttachment {
answerID: number;
questionID: number;
originalFileName: string;
previousFileTobase64: string;
attachmentType: number;
fileTobase64: string;
constructor() {
}
}
export class SurveyCategory {
id: number;
questionCategoryID: number;
modifiedBy?: number;
createdDate: Date;
createdBy: number;
modifiedDate?: Date;
code: string;
description: string;
constructor() {
this.code = '';
this.description = '';
}
}
export class Survey {
id: number;
title: number;
categoryID: number;
description: string;
createdDate: Date;
createdBy: number;
modifiedDate?: Date;
actualTime: number;
passMark: number;
questionCount: number;
estimatedTime: number;
marks: number;
surveyQuestions: SurveyQuestion[];
surveyQuestionList: any;
noOfQuestions: number;
categoryName: string;
constructor() {
this.estimatedTime = 0;
}
}
export class SurveyQuestion {
surveyID: number;
questionID: number;
question: Question;
}
export class SurveyResult {
surveyID: number;
employeeID: number;
questionID: number;
answerID: number;
isCorrect: boolean;
forEmployeeID: number;
candidateID: number;
weight: number;
}
export class SurveyEmployee {
surveyID: number;
employeeID: number;
candidateID: number;
startTime: Date;
currentQuestionID: number;
isDisconnected: boolean;
isPass: boolean;
erCircularID: number;
surveyMark: number;
surveyTime: number;
surveyParticipantDate: Date;
isCompleted: boolean;
}
export class Result
{
totalMark: number;
totalTime: number;
takenTime: string;
questionCount: number;
answerCount: number;
}

View File

@ -0,0 +1,28 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var baseObject_1 = require("../Basic/baseObject");
var User = /** @class */ (function (_super) {
__extends(User, _super);
function User() {
var _this = _super.call(this) || this;
_this.isNew = true;
_this.roleNames = '';
return _this;
}
return User;
}(baseObject_1.BaseObject));
exports.User = User;
//# sourceMappingURL=user.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"user.js","sourceRoot":"","sources":["user.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,kDAAiD;AAEjD;IAA0B,wBAAU;IAEhC;QAAA,YACI,iBAAO,SAGV;QAFG,KAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,KAAI,CAAC,SAAS,GAAG,EAAE,CAAC;;IACxB,CAAC;IAYL,WAAC;AAAD,CAAC,AAlBD,CAA0B,uBAAU,GAkBnC;AAlBY,oBAAI"}

View File

@ -0,0 +1,18 @@
import { EnumAuthStatus, EnumUserType } from '../enums';
import { BaseObject } from '../Basic/baseObject';
export class ErjobUser extends BaseObject {
constructor() {
super();
}
public loginID: string;
public userName: string;
public password: string;
public confirmPassword: string;
public email: string;
public passwordHints: string;
public mobile: string;
public isCVCompleted: boolean;
public jobUserID: number;
}

View File

@ -0,0 +1,100 @@
import { Injectable } from '@angular/core';
/*import { User } from '../../_models/Authentication/user';*/
import { HttpClient } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';
import { map } from 'rxjs/operators';
import { ApiService } from '../../app.api.service';
import { EnumRoleType, EnumSystemType, EnumUserType } from '../../_models/enums';
import { Router } from '@angular/router';
import { BehaviorSubject, Subject } from 'rxjs';
import { ErjobUser } from '../../_models/user/user';
@Injectable()
export class AuthService {
public userExistcheck$ = new BehaviorSubject<any>({});
baseUrl = ApiService.BASE_URL + 'Authentication/';
jwtHelper = new JwtHelperService();
decodedToken: any;
// bookmarks: Bookmark[];
constructor(private http: HttpClient,
public apiService: ApiService,
private router: Router) {
}
login(param: any) {
return this.apiService.httpPostLoginWithGoogle<any>('/Authentication/loginWithGoogle', JSON.stringify(param)).pipe(
map((response: any) => {
const user = response;
if (user) {
localStorage.setItem('token', user);
ApiService.AuthenticationToken = user;
}
})
);
}
GetLogInUserType(): any {
return this.apiService.httpGet<EnumUserType>('/Authentication/GetLogInUserType');
}
GetCurrentUser(): any {
return this.apiService.httpGet<any>('/Authentication/GetCurrentUser');
}
logout() {
localStorage.removeItem('token');
this.router.navigate(['/login']);
}
//SaveUser(oUser: User): any {
// return this.apiService.httpPost<User>('/Authentication/SaveUser', oUser);
//}
loggedIn() {
const token = localStorage.getItem('token');
ApiService.AuthenticationToken = token;
return !this.jwtHelper.isTokenExpired(token);
}
loadMenu() {
return this.http.get(this.baseUrl + 'loadMenu');
}
changePassword(userData: any) {
return this.apiService.httpPost<any>('/Authentication/changePassword', userData);
}
changePasswordbyAdmin(userData: any) {
return this.apiService.httpPost<any>('/Authentication/changePasswordbyAdmin', userData);
}
forgotPassword(data: any) {
return this.apiService.httpPost<any>('/Authentication/forgotPassword', data);
}
getVersionNumber() {
return this.apiService.httpGet<string>('/Authentication/getVersionNumber');
}
register(data: any) {
return this.apiService.httpPost<ErjobUser>('/Authentication/register', data);
}
systemLogin(param: any) {
// return this.apiService.httpPost<any>('/Authentication/login', param);
return this.apiService.httpPost<any>('/Authentication/login', param).pipe(
map((response: any) => {
const user = response;
if (user) {
localStorage.setItem('token', user);
ApiService.AuthenticationToken = user;
}
})
);
}
}

View File

@ -0,0 +1,154 @@
import { Injectable } from '@angular/core';
import { ApiService } from '../app.api.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Discipline } from '../_models/discipline/discipline';
import { EducationLevel } from '../_models/education-level/education-level';
import { EnumStatus } from '../_models/enums';
import { Institution } from '../_models/institutions/institution';
import { ResultType } from '../_models/HRBasic/result-type';
import { Religion } from '../_models/HRBasic/religion';
import { Occupation } from '../_models/HRBasic/occupation';
import { Relation } from '../_models/HRBasic/relation';
import { TrainingType } from '../_models/ercv-bank/training-type';
@Injectable({
providedIn: 'root'
})
export class BasicService {
getOccupation(id: number) {
throw new Error('Method not implemented.');
}
baseUrl = ApiService.BASE_URL + '/ERBasic';
constructor(public apiService: ApiService,
private http: HttpClient) {
}
// Department
getDepartment() {
return this.apiService.httpGet(this.apiService.base_url + '/getDepartment');
}
getAllEducationLevel(): Observable<EducationLevel[]> {
return this.apiService.httpGet<EducationLevel[]>('/ERBasic/getAllEducationLevel' + '/' + EnumStatus.Regardless);
}
// Designation
getDesignation() {
return this.apiService.httpGet(this.apiService.base_url + '/getDesignation');
}
getAllOccupation(): Observable<Occupation[]> {
const nname = this.apiService.getApiDefaultData('');
const ncode = this.apiService.getApiDefaultData('');
return this.apiService.httpGet<Occupation[]>('/ERBasic/getAllOccupation');
}
getAllRelations(): Observable<Relation[]> {
return this.apiService.httpGet<Relation[]>('/ERBasic/getAllRelations');
}
//getAllDesignation(status: EnumStatus, code?: string, name?: string): Observable<Designation[]> {
// const nname = this.apiService.getApiDefaultData(name);
// const ncode = this.apiService.getApiDefaultData(code);
// return this.apiService.httpGet<Designation[]>('/HRBasic/getAllDesignation' + '/' + status + '/' + ncode +
// '/' + nname);
//}
getDesignationByID(id: number) {
return this.apiService.httpGet('/ERBasic/getDesignationByID' + '/' + id);
}
// Grade
getGrade() {
return this.apiService.httpGet(this.apiService.base_url + '/getGrade');
}
//getAllGrade(status: EnumStatus, code?: string, name?: string): any {
// const nname = this.apiService.getApiDefaultData(name);
// const ncode = this.apiService.getApiDefaultData(code);
// return this.apiService.httpGet<Grade[]>('/HRBasic/getAllGrade' + '/' + status + '/' + ncode +
// '/' + nname);
//}
//getGradeByID(id: number) {
// return this.apiService.httpGet<Grade>('/HRBasic/getGradeByID' + '/' + id);
//}
// GradeSegment
getGradeSegment() {
return this.apiService.httpGet(this.apiService.base_url + '/getGradeSegment');
}
// Location
getLocation() {
return this.apiService.httpGet(this.apiService.base_url + '/getLocation');
}
//getAllLocation(status: EnumStatus, code?: string, name?: string): Observable<Location[]> {
// const nname = this.apiService.getApiDefaultData(name);
// const ncode = this.apiService.getApiDefaultData(code);
// return this.apiService.httpGet<Location[]>('/HRBasic/GetAllLocation' + '/' + status + '/' + ncode +
// '/' + nname);
//}
getLocationByID(id: number) {
return this.apiService.httpGet('/ERBasic/getLocationByID' + '/' + id);
}
// religion
getAllReligion(): Observable<Religion[]> {
return this.apiService.httpGet<Religion[]>('/ERBasic/getAllReligion');
}
// Term
getTerm() {
return this.apiService.httpGet(this.apiService.base_url + '/getTerm');
}
// institution
getAllInstitutions(): Observable<Institution[]> {
return this.apiService.httpGet<Institution[]>('/ERBasic/getAllInstitutions');
}
getAllResultTypesByStatus(status: EnumStatus): Observable<ResultType[]> {
return this.apiService.httpGet<ResultType[]>('/ERBasic/getAllResultTypesByStatus/' + status);
}
// Discipline
getAllDiscipline(): Observable<Discipline[]> {
return this.apiService.httpGet<Discipline[]>('/ERBasic/getAllDiscipline');
}
GetAllTrainingType(status: EnumStatus, code?: string, name?: string): any {
const nname = this.apiService.getApiDefaultData(name);
const ncode = this.apiService.getApiDefaultData(code);
return this.apiService.httpGet<TrainingType[]>('/ERBasic/GetAllTrainingType' + '/' + status + '/' + ncode +
'/' + nname);
}
GetAllInstitues(status: EnumStatus, code?: string, name?: string): any {
const nname = this.apiService.getApiDefaultData(name);
const ncode = this.apiService.getApiDefaultData(code);
return this.apiService.httpGet<TrainingType[]>('/ERBasic/GetAllInstitues' + '/' + status + '/' + ncode +
'/' + nname);
}
GetTrainingybyTypeID(traininTypeID: number): any {
return this.apiService.httpGet<TrainingType[]>('/ERBasic/GetTrainingybyTypeID/' + traininTypeID);
}
getSurvey(): Observable<any[]> {
return this.apiService.httpGet<Religion[]>('/ERBasic/getAllReligion');
}
getAllCountries(): Observable<any[]> {
return this.apiService.httpGet<any[]>('/ERBasic/getAllCountries');
}
}

View File

@ -0,0 +1,89 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from '../../app.api.service';
import { ErApplicantDoc, ErAppliedApplicant } from '../../_models/Applicant/applicant';
import { ErCircular } from '../../_models/circular_detail/CircularDetail';
import { EducationLevel } from '../../_models/education-level/education-level';
import { EnumStatus } from '../../_models/enums';
import { ErCV } from '../../_models/ercv-bank/ercv';
import { SurveyEmployee } from '../../_models/survey/survey';
@Injectable({
providedIn: 'root'
})
export class RecruitmentService {
constructor(public apiService: ApiService) {
}
getPublishItems() {
return this.apiService.httpGet<ErCircular[]>('/Recruitment/getrecruitmentpublish');
}
getByErCircularID(id:number) {
return this.apiService.httpGet<ErCircular>('/Recruitment/getByErCircularID'+'/'+id);
}
getErCirculatById(id:number) {
return this.apiService.httpGet<ErCircular>('/Recruitment/getErCirculatById'+'/'+id);
}
loginWithgoogle(param: any) {
return this.apiService.httpPostLoginWithGoogle<any>('/Authentication/loginWithGoogle', JSON.stringify(param));
}
saveCV(dtresult: ErCV) {
return this.apiService.httpPost<ErCV>('/Recruitment/saveErCV', dtresult);
}
saveErAppliedApplicant(dtresult: ErAppliedApplicant) {
return this.apiService.httpPost<ErAppliedApplicant>('/Recruitment/saveErAppliedApplicant', dtresult);
}
getJobUpdateByUserId(jobId: number) {
return this.apiService.httpGet<ErCircular>('/Recruitment/getJobUpdateByUserId' + '/' + jobId);
}
getRecruitementStepForOfferLetter(recruitmentId: number) {
return this.apiService.httpGet<boolean>('/Recruitment/getRecruitementStepForOfferLetter' + '/' + recruitmentId);
}
getApplicantDocByUserId(jobId: number) {
return this.apiService.httpGet<ErApplicantDoc>('/Recruitment/getApplicantDocByUserId' + '/' + jobId);
}
getJobApplicantByUserId(jobId: number) {
return this.apiService.httpGet<ErAppliedApplicant[]>('/Recruitment/getJobApplicantByUserId' + '/' + jobId);
}
acceptOfferLetter(jobId: number) {
return this.apiService.httpGet<any>('/Recruitment/acceptOfferLetter' + '/' + jobId);
}
rejectOfferLetter(jobId: number, remarks:string) {
return this.apiService.httpGet<any>('/Recruitment/rejectOfferLetter' + '/' + jobId + '/' + remarks);
}
getJobApplicant(jobId: number) {
return this.apiService.httpGet<ErAppliedApplicant>('/Recruitment/getJobApplicant' + '/' + jobId);
}
IsUserHaveErCV(jobId: number) {
return this.apiService.httpGet<boolean>('/Recruitment/IsUserHaveErCV' + '/' + jobId);
}
getCvInformation(userId: number) {
return this.apiService.httpGet<ErCV>('/Recruitment/getCvInformation' + '/' + userId);
}
getSurveyEmployeebyJobId(jobId: number) {
return this.apiService.httpGet<SurveyEmployee[]>('/Recruitment/getSurveyEmployeebyJobId' + '/' + jobId);
}
getAllJobApplicantByUserId() {
return this.apiService.httpGet<ErAppliedApplicant[]>('/Recruitment/getAllJobApplicantByUserId');
}
getInterViewInforBycandidateId(jobId: number) {
return this.apiService.httpGet<any>('/Recruitment/getInterViewInforBycandidateId' + '/' + jobId);
}
}

View File

@ -0,0 +1,67 @@
import { Injectable } from '@angular/core';
import { ApiService } from '../../app.api.service';
import { EnumClaimRequsitionStatus } from '../../_models/enums';
import { Question, QuestionAnswerAttachment, QuestionCategory, Result, Survey, SurveyCategory, SurveyEmployee, SurveyResult } from '../../_models/survey/survey';
@Injectable({
providedIn: 'root'
})
export class SurveyService {
constructor(public apiService: ApiService) {
}
getQuestionCategories() {
return this.apiService.httpGet<QuestionCategory[]>('/survey/getQuestionCategories');
}
saveQuestion(param: Question) {
return this.apiService.httpPost<any>('/survey/savequestion', param);
}
getByCategory(categoryId: number) {
return this.apiService.httpGet<Question[]>('/survey/GetByCategory' + '/' + categoryId);
}
getQuestionById(questionId: number) {
return this.apiService.httpGet<Question>('/survey/getQuestionById' + '/' + questionId);
}
getAllfilesQuestionById(questionId: number) {
return this.apiService.httpGet<QuestionAnswerAttachment[]>('/survey/getAllFilesById' + '/' + questionId);
}
getSurveyCategories() {
return this.apiService.httpGet<SurveyCategory[]>('/survey/getSurveyCategories');
}
saveSurvey(param: Survey) {
return this.apiService.httpPost<any>('/survey/savesurvey', param);
}
getQuestionSetCategoryId(categoryId: number) {
return this.apiService.httpGet<Survey[]>('/survey/GetQuestionsByCategory' + '/' + categoryId);
}
getSurveyById(surveyId: number) {
return this.apiService.httpGet<Survey>('/survey/getSurveyById' + '/' + surveyId);
}
getSurveyService() {
return this.apiService.httpGet<Survey[]>('/survey/getQuestionCategories');
}
getQuestionSet() {
return this.apiService.httpGet<Survey[]>('/survey/getQuestionSet');
}
getQuestionsBySurveyId(surveyId: number) {
return this.apiService.httpGet<Survey[]>('/survey/getQuestionsBySurveyId' + '/' + surveyId);
}
saveSurveyResult(param: SurveyResult) {
return this.apiService.httpPost<any>('/survey/saveSurveyResult', param);
}
saveSurveyEmployee(param: SurveyEmployee) {
return this.apiService.httpPost<any>('/survey/saveSurveyEmployee', param);
}
getResultByCandidateID(surveyId: number,jobId:number) {
return this.apiService.httpGet<Result>('/survey/getResultByCandidateID' + '/' + surveyId + '/' + jobId);
}
checkDisconncetedSurveyEmployee(jobId: number, surveyId: number) {
return this.apiService.httpGet<SurveyEmployee>('/survey/checkDisconncetedSurveyEmployee' + '/' + jobId + '/' + surveyId);
}
}

View File

@ -0,0 +1,261 @@
import { Injectable } from '@angular/core';
import { Observable, Subject, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, retry } from 'rxjs/operators';
import { DatePipe } from '@angular/common';
@Injectable({
providedIn: 'root',
})
export class ApiService {
// For Development
public static BASE_URL = 'https://localhost:44375/api';
public base_url = 'https://localhost:44375/api';
// For WeLink
/*public static BASE_URL = '/welinkventures/api';
public base_url = '/welinkventures/api';*/
// For BAT
/*public static BASE_URL = '/batDemo/api';
public base_url = '/batDemo/api';*/
// For Demo
/*public static BASE_URL = '/celDemo/api';
public base_url = '/celDemo/api';*/
// For LiFung App Test
//public base_url = '/lifungtest/api';
//public static BASE_URL = '/lifungtest/api';
// For Synovia Test
// public base_url = '/synovia/api';
// public static BASE_URL = '/synovia/api';
// For Synovia Live
// public base_url = '/synoviahr/api';
// public static BASE_URL = '/synoviahr/api';
// For BProperty Live
/*public base_url = '/api';
public static BASE_URL = '/api';*/
// For Azure
/*public static BASE_URL = '/api';
public base_url = '/api';*/
// For H&M Live
/*public base_url = '/hnm/api';
public static BASE_URL = '/hnm/api';*/
// For erecruitment
/*public base_url = '/erecruitment/api';
public static BASE_URL = '/erecruitment/api';*/
// public mobileAppDownloadLink = this.BASE_URL + 'MobileApp/Download';
public static AuthenticationToken = '';
public selectedMenuName: string = '';
constructor(public httpClient: HttpClient, public datepipe: DatePipe) {
}
createClientHeader(): { headers: HttpHeaders } {
let token = '';
if (ApiService.AuthenticationToken) {
token = `Bearer ${ApiService.AuthenticationToken}`;
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': token
})
};
return httpOptions;
}
getApiDefaultData(str: string) {
return (str === undefined || str === null || str.trim() === '') ? null : str;
}
getApiDateString(dDate: Date) {
if (dDate === undefined || dDate === null) return dDate;
var str: string = this.datepipe.transform(dDate, 'dd-MMM-yyyy');
return str;
}
getApiDefaultIntData(intData: number) {
return (intData === undefined || intData === null) ? undefined : intData;
}
public httpGet<T>(url: string, params?: any): Observable<T> {
var options: HttpHeaders;
if (!options) {
options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
options = options.append('Accept', 'application/json');
}
if (ApiService.AuthenticationToken) {
options = options.append('Authorization', `Bearer ${ApiService.AuthenticationToken}`);
}
if (params) {
const p = [];
for (const k in params) {
p.push((k + '=' + params[k]) as any);
}
url = url + '?' + (p.join('&'));
}
var endpoint: string;
return this.httpClient.get<T>(this.base_url + url, { headers: options, withCredentials: true });
// return this.http.get<T>(`${url}`, { headers: options, withCredentials: true });
}
public httpGetByKey<T>(url: string, key: any): Observable<T> {
return this.httpClient.get<T>(ApiService.BASE_URL + url + key, this.createClientHeader())
.pipe(
catchError(this.handleClientError)
);
}
public httpPost<T>(url: string, body: any): Observable<T> {
var options: HttpHeaders;
if (!options) {
options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
options = options.append('Accept', 'application/json');
}
debugger;
if (ApiService.AuthenticationToken) {
options = options.append('Authorization', `Bearer ${ApiService.AuthenticationToken}`);
}
return this.httpClient.post<T>(this.base_url + url, body, { headers: options, withCredentials: true });
//return this.httpClient.post<T>(ApiService.BASE_URL + url, body, this.createClientHeader())
// .pipe(
// catchError(this.handleClientError)
// );
}
public httpPostLoginWithGoogle<T>(url: string, body: any): Observable<T> {
var options: HttpHeaders;
if (!options) {
options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
options = options.append('Accept', 'application/json');
}
return this.httpClient.post<T>(this.base_url + url, body, { headers: options, withCredentials: true });
}
//public LoginWithGoogle(credentials: string): Observable<any> {
// const header = new HttpHeaders().set('Content-type', 'application/json');
// return this.httpClient.post(this.base_url + "/auth/loginWithGoogle", JSON.stringify(credentials), { headers: header });
//}
public httpDelete<T>(url: string, key: any): Observable<T> {
return this.httpClient.delete<T>(ApiService.BASE_URL + url + key, this.createClientHeader())
.pipe(
catchError(this.handleClientError)
);
}
public httpPostFile(url: string, body: any): Observable<Blob> {
var options: HttpHeaders;
if (!options) {
options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
options = options.append('Accept', 'application/json');
}
if (ApiService.AuthenticationToken) {
options = options.append('Authorization', `Bearer ${ApiService.AuthenticationToken}`);
}
return this.httpClient.post<Blob>(this.base_url + url, body, { headers: options, withCredentials: true })
.pipe(
catchError(this.handleClientError)
);
}
public httpPostBlob(url: string, body: any): Observable<any> {
var options: HttpHeaders;
if (!options) {
//options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
//options = options.append('Accept', 'application/json');
}
if (ApiService.AuthenticationToken) {
options = new HttpHeaders();
options = options.append('Authorization', `Bearer ${ApiService.AuthenticationToken}`);
}
return this.httpClient.post<Blob>(this.base_url + url, body, { headers: options, withCredentials: true })
.pipe(
catchError(this.handleClientError)
);
}
public httpDownloadFile(url: string, body: any): Observable<Blob> {
var options: HttpHeaders;
if (!options) {
//options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
//options = options.append('Accept', 'application/json');
}
if (ApiService.AuthenticationToken) {
options = new HttpHeaders();
options = options.append('Authorization', `Bearer ${ApiService.AuthenticationToken}`);
}
return this.httpClient.post<Blob>(this.base_url + url, body, { headers: options, withCredentials: true, responseType: 'blob' as 'json' })
.pipe(
catchError(this.handleClientError)
);
}
public httpDownloadFileNew(url: string, body: any): Observable<Blob> {
var options: HttpHeaders;
if (!options) {
options = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
options = options.append('Accept', 'application/json');
}
return this.httpClient.post<Blob>(this.base_url + url, body, { headers: options, withCredentials: true, responseType: 'blob' as 'json' });
}
public handleClientError(error: HttpErrorResponse) {
// return Observable.throw(error.message || 'An error has been occurred. Please try again or contact to system administrator');
return throwError(error.error || 'An error has been occurred. Please try again or contact to system administrator');
}
}
@Injectable()
export class PubSubService {
public subjects: Subject<any>[] = [];
publish(eventName: string) {
this.subjects[eventName] = this.subjects[eventName] || new Subject<any>();
this.subjects[eventName].next();
}
on(eventName: string): Observable<any> {
this.subjects[eventName] = this.subjects[eventName] || new Subject<any>();
return this.subjects[eventName].asObservable();
}
}
@Injectable()
export class BaseHrefService {
}

View File

@ -0,0 +1,6 @@
<body>
<app-nav-menu></app-nav-menu>
<div class="container">
<router-outlet></router-outlet>
</div>
</body>

View File

@ -0,0 +1,9 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'app';
}

View File

@ -0,0 +1,101 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { DialogModule } from '@progress/kendo-angular-dialog';
import { DateInputsModule } from "@progress/kendo-angular-dateinputs";
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { RecruitmentService } from '../app/_services/recruitment/recruitment.service';
import { DatePipe } from '@angular/common';
import { RecruitmentPublishComponent } from './recruitment-publish/recruitment-publish.component';
import { RecruitmentJobDetailsComponent } from './recruitment-job-details/recruitment-job-details.component';
/*import { AngularFontAwesomeModule } from 'angular-font-awesome';*/
import { ERCVBankComponent } from './ercv-bank/ercv-bank.component';
import { ERCVBankEducationComponent } from '../../src/app/ercv-bank/ercv-bank-education.component';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LayoutModule } from "@progress/kendo-angular-layout";
import { ERCVBankExperienceComponent } from './ercv-bank/ercv-bank-experience.component';
import { ERCVBankReferenceComponent } from './ercv-bank/ercv-bank-reference.component';
import { DatePickerModule } from '@progress/kendo-angular-dateinputs';
import { LabelModule } from "@progress/kendo-angular-label"
import { ERCVBankTrainingComponent } from './ercv-bank/ercv-bank-training.component';
import { LoginComponent } from '../app/login/login.component';
import { AuthService } from '../app/_services/auth/auth.service';
import { AuthGuard } from './_guards/auth.guard';
import { OnlineExamComponent } from './online-exam/online-exam.component';
import { SurveyService } from '../app/_services/survey/survey.service';
import { ExamResultComponent } from './exam-result/exam-result.component';
import { RejectPopupComponent } from './recruitment-job-details/reject-popup.component';
import { LoadingPanelModule } from './spinner/loading-panel.module'
//import { LoginPopupComponent } from '../app/login/login-popup.component';
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
CounterComponent,
FetchDataComponent,
RecruitmentPublishComponent,
RecruitmentJobDetailsComponent,
ERCVBankComponent,
ERCVBankEducationComponent,
ERCVBankExperienceComponent,
ERCVBankReferenceComponent,
ERCVBankTrainingComponent,
LoginComponent,
OnlineExamComponent,
ExamResultComponent,
RejectPopupComponent,
//LoginPopupComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
ReactiveFormsModule,
LayoutModule,
DatePickerModule,
LabelModule,
BrowserAnimationsModule,
DialogModule,
LoadingPanelModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
// { path: '', component: RecruitmentPublishComponent, pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: 'recruitment-publish', component: RecruitmentPublishComponent },
{ path: 'job-details/:id', component: RecruitmentJobDetailsComponent },
{ path: 'ercv-bank', component: ERCVBankComponent, canActivate: [AuthGuard] },
{ path: 'online-exam', component: OnlineExamComponent, canActivate: [AuthGuard]},
{ path: 'exam-result', component: ExamResultComponent, canActivate: [AuthGuard] },
{ path: 'reject-reason', component: RejectPopupComponent, canActivate: [AuthGuard]},
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
], { relativeLinkResolution: 'legacy' }),
DropDownsModule
],
providers: [RecruitmentService, DatePipe, AuthService, SurveyService],
bootstrap: [AppComponent]
})
export class AppModule {
constructor() {
this.overrideDate();
}
overrideDate() {
Date.prototype.toJSON = function (key) {
return this.toLocaleDateString('en-US') + ' ' + this.toLocaleTimeString('en-US');
};
}
}

View File

@ -0,0 +1,11 @@
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
@NgModule({
imports: [AppModule, ServerModule, ModuleMapLoaderModule],
bootstrap: [AppComponent]
})
export class AppServerModule { }

View File

@ -0,0 +1,7 @@
<h1>Counter</h1>
<p>This is a simple example of an Angular component.</p>
<p aria-live="polite">Current count: <strong>{{ currentCount }}</strong></p>
<button class="btn btn-primary" (click)="incrementCounter()">Increment</button>

View File

@ -0,0 +1,34 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
let fixture: ComponentFixture<CounterComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ CounterComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
});
it('should display a title', waitForAsync(() => {
const titleText = fixture.nativeElement.querySelector('h1').textContent;
expect(titleText).toEqual('Counter');
}));
it('should start with count 0, then increments by 1 when clicked', waitForAsync(() => {
const countElement = fixture.nativeElement.querySelector('strong');
expect(countElement.textContent).toEqual('0');
const incrementButton = fixture.nativeElement.querySelector('button');
incrementButton.click();
fixture.detectChanges();
expect(countElement.textContent).toEqual('1');
}));
});

View File

@ -0,0 +1,13 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-counter-component',
templateUrl: './counter.component.html'
})
export class CounterComponent {
public currentCount = 0;
public incrementCounter() {
this.currentCount++;
}
}

View File

@ -0,0 +1,134 @@
<form [formGroup]="generalForm">
<div class="card border">
<h5 class="card-header border-light" style="background-color:#DBDBDB">Academic {{indexNum}}</h5>
<div class="card-body">
<div class="row" *ngIf="isEditActive">
<div class="form-group mt-2 col-md-12">
<button class="btn btn-sm btn-primary pull-right" style="background-color:#2c3e50;border-color:black" (click)="editClick();">
<i class="fa fa-save"></i> Edit
</button>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="degreeTitle" class="label" style="margin-left:6px;">Education Level</label>
<kendo-dropdownlist class="form-control form-control-sm" id="degreeTitle"
[data]="educationLevels"
[defaultItem]="{ description: 'Select a level', id: null }"
[textField]="'description'"
[valueField]="'id'"
[valuePrimitive]="true"
[(ngModel)]="element.degreeTitleID"
(valueChange)="onChangeList($event)"
[disabled]="isEditActive"
style="width:100%;"
formControlName="degreeTitleID">
</kendo-dropdownlist>
</div>
<div class="form-group col-md-4">
<label for="degreeTitle" class="label" style="margin-left:6px;">Exam/Degree Title</label>
<input type="text" class="form-control" id="degreeTitle" formControlName="degreeTitle" [(ngModel)]="element.degreeTitle" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4" *ngIf="isFixedSubject=== false">
<label for="concentration" class="label">Concentration / Major</label>
<kendo-autocomplete class="form-control form-control-sm"
id="concentration" [data]="disciplines" [valueField]="'description'" [(ngModel)]="element.concentration" formControlName="concentration" [readonly]="isEditActive" style="width:100%">
<ng-template kendoAutoCompleteItemTemplate let-dataItem>
<span>{{ dataItem.description }}</span>
</ng-template>
</kendo-autocomplete>
<!--<input type="text" class="form-control" id="instituteName" formControlName="concentration" [(ngModel)]="element.instituteName" [readonly]="isEditActive">-->
</div>
<div class="form-group col-md-4" *ngIf="isFixedSubject=== true">
<label for="subject" class="label" style="margin-left:6px;">Subject</label>
<kendo-dropdownlist class="form-control form-control-sm" id="subject"
[data]="disciplines"
[defaultItem]="{ description: 'Select a discipline', id: null }"
[textField]="'description'"
[valueField]="'id'"
[valuePrimitive]="true"
[(ngModel)]="element.disciplineID"
[disabled]="isEditActive"
style="width:100%"
formControlName="subject">
</kendo-dropdownlist>
</div>
<div class="form-group col-md-4" *ngIf="isBoard=== true">
<label for="board" class="label" style="margin-left:6px;">Board</label>
<kendo-dropdownlist class="form-control form-control-sm" id="board"
[data]="institutions"
[defaultItem]="{name: 'Select Board', id: null }"
[textField]="'name'"
[valueField]="'id'"
[valuePrimitive]="true"
[(ngModel)]="element.boardID"
[disabled]="isEditActive"
style="width:100%;"
formControlName="board">
</kendo-dropdownlist>
</div>
<div class="form-group col-md-4">
<label for="instituteName" class="label">Institute Name</label>
<input type="text" class="form-control" id="instituteName" formControlName="instituteName" [(ngModel)]="element.instituteName" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="passingyear" class="label">Passing Year</label>
<input type="text" class="form-control" id="passingyear" formControlName="passingyear" [(ngModel)]="element.passingYear" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="result" class="label" style="margin-left:6px;">Result</label>
<kendo-dropdownlist class="form-control form-control-sm" id="result"
[data]="results"
[defaultItem]="{description: 'Select Result Type', id: null }"
[textField]="'description'"
[valueField]="'id'"
[valuePrimitive]="true"
[(ngModel)]="element.resultID"
[disabled]="isEditActive"
(valueChange)="onResultTypeChangeList($event)"
style="width:100%"
formControlName="result">
</kendo-dropdownlist>
<div *ngIf="generalForm.get('result').invalid">
</div>
</div>
<div class="form-group col-md-4">
<label for="cgpa" class="label">{{resultTypeName}}</label>
<input type="text" class="form-control" id="cgpa" formControlName="cgpa" [(ngModel)]="element.cgpa" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4" *ngIf="isCGPA===true">
<label for="outof" class="label">Out Of</label>
<input type="text" class="form-control" id="outof" formControlName="outof" [(ngModel)]="element.outOF" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="duration" class="label">Duration</label>
<input type="text" class="form-control" id="duration" formControlName="duration" [(ngModel)]="element.duration" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="achievement" class="label">Achievement</label>
<input type="text" class="form-control" id="passingyear" formControlName="achievement" [(ngModel)]="element.achievement" [readonly]="isEditActive">
</div>
</div>
<div class="row">
<div class="form-group mt-2 col-md-12">
<button class="btn btn-sm btn-primary pull-right" style="margin-left:12px;margin-right:12px;background-color:#2c3e50;border-color:black" [hidden]="!isEditable">
<i class="fa fa-times"></i> Close
</button>
<button class="btn btn-sm btn-primary pull-right" style="background-color:#2c3e50;border-color:black" (click)="educationSave();" [hidden]="!isEditable" [disabled]="!generalForm.valid">
<i class="fa fa-save"></i> Save
</button>
</div>
</div>
</div>
</div>
</form>

View File

@ -0,0 +1,278 @@
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild, ViewContainerRef } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl, FormArray } from '@angular/forms';
import { Router } from '@angular/router';
import { EducationLevel } from '../_models/education-level/education-level';
import { EnumExtension, EnumGender, EnumMaritalStatus, EnumStatus } from '../_models/enums';
import { ErCVEducation } from '../_models/ercv-bank/ercv';
import { RecruitmentService } from '../_services/recruitment/recruitment.service';
import { BasicService } from '../_services/basic.service';
import { Discipline } from '../_models/discipline/discipline';
import { Institution } from '../_models/institutions/institution';
import { ResultType } from '../_models/HRBasic/result-type';
import { Religion } from '../_models/HRBasic/religion';
import { Subject } from 'rxjs';
@Component({
selector: 'app-ercv-bank-education',
templateUrl: './ercv-bank-education.component.html',
styles: [
`
.form-group label{
font-size: 0.8em;
}
.form-control.error .k-dropdown-wrap {
border-color: red;
}
`
]
})
/* cv-bank component*/
export class ERCVBankEducationComponent implements OnInit, OnChanges {
@Output() saveHandler = new EventEmitter<ErCVEducation>();
@Output() editHandler = new EventEmitter<ErCVEducation>();
@Input() public set InputObject(InputObject:ErCVEducation) {
debugger;
if (InputObject !== undefined && InputObject !== null) {
this.payload = new ErCVEducation();
this.payload = InputObject;
this.onChangeList(this.payload.degreeTitleID);
this.onResultTypeChangeList(this.payload.resultID);
this.isEditable = false;
this.isEditActive = true;
} else {
debugger;
this.element = new ErCVEducation();
this.isEditable = true;
this.isEditActive = false;
}
}
// _val: Subject<ErCVEducation> = new Subject();
@Input() public set index(index: number) {
this.indexNum = index+1;
}
@Input() public set acaFormId(id: number) {
this.refId = id;
console.log(id);
}
indexNum: number;
refId: number = 0;
generalForm: FormGroup;
personalDetailForm: FormGroup;
isExpand: boolean = true;
genderType: any = EnumExtension.getNamesAndValues(EnumGender);
collections: ErCVEducation[] = [];
educationLevels: EducationLevel[] = [];
disciplines: Discipline[] = [];
institutions: Institution[] = [];
results: ResultType[] = [];
maritalStatusTypes: any = EnumExtension.getNamesAndValues(EnumMaritalStatus);
religions: Religion[] = [];
isEducationalDetail: boolean = true;
isFixedSubject: boolean = false;
isBoard: boolean = false;
id: number = 0;
isRequirementAdd: boolean = true;
teminals: FormArray;
element: ErCVEducation;
payload: ErCVEducation;
isEditable: boolean;
isEditActive: boolean;
resultTypeName: string="CGPA";
isEditForListClick: boolean = false
isCGPA: boolean = true;
constructor(
public recruitmentService: RecruitmentService,
public basicService: BasicService
) {
this.loadForm();
this.loadEducationLevel();
}
ngOnChanges() {
if (this.InputObject !== undefined && this.InputObject !== null) {
this.payload = new ErCVEducation();
this.payload = this.InputObject;
this.onChangeList(this.payload.degreeTitleID);
this.onResultTypeChangeList(this.payload.resultID);
this.isEditable = false;
this.isEditActive = true;
} else {
debugger;
this.element = new ErCVEducation();
this.isEditable = true;
this.isEditActive = false;
}
}
loadForm() {
this.generalForm = new FormGroup({
degreeTitleID: new FormControl('', Validators.required),
degreeTitle: new FormControl(''),
outof: new FormControl('', Validators.required),
discipline: new FormControl(''),
board: new FormControl(''),
result: new FormControl('', Validators.required),
cgpa: new FormControl('', Validators.required),
instituteName: new FormControl(),
concentration: new FormControl(),
subject: new FormControl(''),
passingyear: new FormControl('', Validators.required),
duration: new FormControl(),
achievement: new FormControl()
});
}
loadEducationLevel() {
this.basicService.getAllEducationLevel().subscribe(
(resp: any) => {
this.educationLevels = resp;
},
(err: any) => {
},
() => {
this.loadDisciplines();
}
);
}
onChangeList(event: any) {
if (this.educationLevels !== undefined) {
const temp = this.educationLevels.find(y => y.id == event);
if (temp !== undefined) {
if (temp.educationType.fixedSubject === true) {
this.isFixedSubject = true;
this.generalForm.controls['subject'].setValidators([Validators.required]);
this.generalForm.get('subject').updateValueAndValidity();
} else {
this.isFixedSubject = false;
this.generalForm.controls['subject'].clearValidators();
this.generalForm.get('subject').updateValueAndValidity();
}
if (temp.educationType.boardRequired === true) {
this.isBoard = true;
this.generalForm.controls['board'].setValidators([Validators.required]);
this.generalForm.get('board').updateValueAndValidity();
} else {
this.isBoard = false;
this.generalForm.controls['board'].clearValidators();
this.generalForm.get('board').updateValueAndValidity();
}
}
}
}
onResultTypeChangeList(event: any) {
if (this.results !== undefined) {
const temp = this.results.find(y => y.id === event);
if (temp !== undefined) {
debugger;
if (temp.cgpa === true) {
this.resultTypeName = "Cgpa";
this.isCGPA = true;
this.generalForm.controls['outof'].setValidators([Validators.required]);
this.generalForm.get('outof').updateValueAndValidity();
} else {
this.resultTypeName = "Marks(%)";
this.isCGPA = false;
this.generalForm.controls['outof'].clearValidators();
this.generalForm.get('outof').updateValueAndValidity();
}
}
}
}
loadDisciplines() {
this.basicService.getAllDiscipline().subscribe(
(resp: any) => {
this.disciplines = resp;
},
(err: any) => {
},
() => {
this.loadInstitutions();
}
);
}
loadInstitutions() {
this.basicService.getAllInstitutions().subscribe(
(resp: any) => {
this.institutions = resp;
},
(err: any) => {
},
() => {
this.loadResults();
}
);
}
loadResults() {
this.basicService.getAllResultTypesByStatus(EnumStatus.Active).subscribe(
(resp: any) => {
this.results = resp;
},
(err: any) => {
},
() => {
this.loadReligion();
}
);
}
loadReligion() {
this.basicService.getAllReligion().subscribe(
(resp: any) => {
this.religions = resp;
},
(err: any) => {
},
() => {
if (this.payload !== undefined && this.payload !== null) {
this.element = this.payload;
this.onChangeList(this.element.degreeTitleID);
this.onResultTypeChangeList(this.payload.resultID);
this.isEditable = false;
this.isEditActive = true;
}
}
);
}
ngOnInit() {
if (this.payload !== undefined && this.payload !== null) {
this.element = new ErCVEducation();
this.isEditable = true;
this.isEditActive = false;
}
}
educationSave() {
this.element.id = (this.refId === undefined || this.refId === null || this.refId===0) ? this.indexNum : this.refId;
debugger;
if (this.isEditForListClick === true) {
this.editHandler.emit(this.element);
} else {
this.saveHandler.emit(this.element);
this.element = new ErCVEducation();
}
this.isEditForListClick = false;
}
//educationEdit() {
// this.enterEdit.emit(this.element);
//}
editClick() {
this.isEditable = true;
this.isEditActive = false;
this.isEditForListClick = true;
}
}

View File

@ -0,0 +1,76 @@
<form [formGroup]="cvExperienceForm">
<div class="card border">
<h5 class="card-header border-light" style="background-color:#DBDBDB">Experience {{indexNum}}</h5>
<div class="card-body">
<div class="row" *ngIf="isEditActive">
<div class="form-group mt-2 col-md-12">
<button class="btn btn-sm btn-primary pull-right" style="background-color:#2c3e50;border-color:black" (click)="editClick();">
<i class="fa fa-save"></i> Edit
</button>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="employeer" class="label">Employeer</label>
<input type="text" class="form-control" id="employeer" formControlName="employeer" [(ngModel)]="element.employeer" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="contactPerson" class="label">Contact Person</label>
<input type="text" class="form-control" id="contactPerson" formControlName="contactPerson" [(ngModel)]="element.contactPerson" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="address" class="label">Address</label>
<textarea class="form-control input-group-sm" id="name" formControlName="address" [(ngModel)]="element.address" rows="2"
type="text"></textarea>
</div>
<div class="form-group col-md-4">
<label for="industry" class="label">Industry/Business Person</label>
<input type="text" class="form-control" id="industry" formControlName="industry" [(ngModel)]="element.industry" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="desigantion" class="label">Designation</label>
<input type="text" class="form-control" id="desigantion" formControlName="desigantion" [(ngModel)]="element.designation" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="desigantion" class="label">Modile/Phone</label>
<input type="text" class="form-control" id="mobile" formControlName="mobile" [(ngModel)]="element.mobile" [readonly]="isEditActive">
</div>
<div class="form-group col-md-4">
<label for="fromdate" class="label">From Date</label>
<kendo-datepicker id="fromDate" [(ngModel)]="element.fromDate" formControlName="fromDate" class="form-control input-group-sm" style="width:100%; margin-left:4px;" [readonly]="isEditActive">
</kendo-datepicker>
</div>
<div class="form-group col-md-4">
<label for="toDate" class="label">To Date</label>
<kendo-datepicker id="toDate" [(ngModel)]="element.toDate" formControlName="toDate" class="form-control input-group-sm" style="width:100%; margin-left:4px;" [readonly]="isEditActive">
</kendo-datepicker>
</div>
<div class="form-group col-md-4">
<label for="role" class="label">Role</label>
<textarea class="form-control input-group-sm" id="role" formControlName="role" rows="2" [(ngModel)]="element.roleDefination" [readonly]="isEditActive"
type="text"></textarea>
</div>
</div>
<div class="row">
<div class="form-group mt-2 col-md-12">
<button class="btn btn-sm btn-primary pull-right" style="margin-left:12px;background-color:#2c3e50;border-color:black" [hidden]="!isEditable">
<i class="fa fa-times"></i> Close
</button>
<button class="btn btn-sm btn-primary pull-right" style="background-color:#2c3e50;border-color:black" (click)="experienceSave();" [hidden]="!isEditable">
<i class="fa fa-save"></i> Save
</button>
<!--<button class="btn btn-sm btn-primary pull-right" (click)="educationEdit();">
<i class="fa fa-save"></i> Edit
</button>-->
</div>
</div>
</div>
</div>
</form>

View File

@ -0,0 +1,117 @@
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, ViewChild, ViewContainerRef } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl, FormArray } from '@angular/forms';
import { Router } from '@angular/router';
import { EducationLevel } from '../_models/education-level/education-level';
import { EnumExtension, EnumGender, EnumMaritalStatus, EnumStatus } from '../_models/enums';
import { ErCVEducation, ErCVExperience } from '../_models/ercv-bank/ercv';
import { RecruitmentService } from '../_services/recruitment/recruitment.service';
import { BasicService } from '../_services/basic.service';
import { Discipline } from '../_models/discipline/discipline';
import { Institution } from '../_models/institutions/institution';
import { ResultType } from '../_models/HRBasic/result-type';
import { Religion } from '../_models/HRBasic/religion';
@Component({
selector: 'app-ercv-bank-experience',
templateUrl: './ercv-bank-experience.component.html',
styles: [
`
.form-group label{
font-size: 0.8em;
}
`
]
})
/* cv-bank component*/
export class ERCVBankExperienceComponent implements OnInit {
@Output() saveExperienceHandler = new EventEmitter<ErCVExperience>();
@Output() editExperienceHandler = new EventEmitter<ErCVExperience>();
@Input() public set InputObject(InputObject: ErCVExperience) {
debugger;
if (InputObject !== undefined && InputObject !== null) {
this.payload = new ErCVExperience();
this.payload = InputObject;
this.isEditable = false;
this.isEditActive = true;
} else {
this.element = new ErCVExperience();
this.isEditable = true;
this.isEditActive = false;
}
}
@Input() public set index(index: number) {
this.indexNum = index + 1;
}
@Input() public set expFormId(id: number) {
this.refId = id;
console.log(id);
}
id: number = 0;
indexNum: number;
refId: number;
cvExperienceForm: FormGroup;
personalDetailForm: FormGroup;
genderType: any = EnumExtension.getNamesAndValues(EnumGender);
maritalStatusTypes: any = EnumExtension.getNamesAndValues(EnumMaritalStatus);
teminals: FormArray;
element: ErCVExperience;
payload: ErCVExperience;
isEditable: boolean;
isEditActive: boolean;
isEditForListClick: boolean = false;
constructor(
public recruitmentService: RecruitmentService,
public basicService: BasicService
) {
this.loadForm();
}
loadForm() {
this.cvExperienceForm = new FormGroup({
employeer: new FormControl('', Validators.required),
contactPerson: new FormControl(),
address: new FormControl(),
industry: new FormControl(),
desigantion: new FormControl('', Validators.required),
role: new FormControl(),
fromDate: new FormControl('', Validators.required),
toDate: new FormControl('', Validators.required),
mobile: new FormControl('', Validators.required)
});
}
ngOnInit() {
this.element = new ErCVExperience();
//this.element.fromDate = new Date();
//this.element.toDate = new Date();
//this.element.fromDate.setFullYear(this.element.fromDate.getFullYear() + 1);
if (this.payload !== undefined && this.payload !== null) {
this.element = this.payload;
this.isEditable = false;
this.isEditActive = true;
}
}
experienceSave() {
this.element.id = (this.refId === undefined || this.refId === null || this.refId === 0) ? this.indexNum : this.refId;
debugger;
if (this.isEditForListClick === true) {
this.editExperienceHandler.emit(this.element);
} else {
this.saveExperienceHandler.emit(this.element);
this.element = new ErCVExperience();
}
this.isEditForListClick = false;
}
editClick() {
this.isEditable = true;
this.isEditActive = false;
this.isEditForListClick = true;
}
}

Some files were not shown because too many files have changed in this diff Show More