From 2a28cee99d438a1adb1993417c1dc6cb5e97ff75 Mon Sep 17 00:00:00 2001 From: manuel Date: Fri, 30 May 2025 11:42:32 +0200 Subject: [PATCH] =?UTF-8?q?Primera=20Versi=C3=B3n=20copiada=20del=20tfs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 63 +++++++ .gitignore | 363 +++++++++++++++++++++++++++++++++++++++++ DbContextExtensions.vb | 104 ++++++++++++ ObjetExtensions.vb | 72 ++++++++ bbdd.vb | 13 ++ tsEFCore7.vbproj | 22 +++ 6 files changed, 637 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 DbContextExtensions.vb create mode 100644 ObjetExtensions.vb create mode 100644 bbdd.vb create mode 100644 tsEFCore7.vbproj diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/DbContextExtensions.vb b/DbContextExtensions.vb new file mode 100644 index 0000000..3273ae3 --- /dev/null +++ b/DbContextExtensions.vb @@ -0,0 +1,104 @@ +Imports System.Reflection +Imports System.Runtime.CompilerServices +Imports Microsoft.EntityFrameworkCore +Imports Microsoft.EntityFrameworkCore.Internal +Imports System.Linq.Dynamic.Core + + +Namespace Extensiones + Public Module DbContextExtensions + + Public Function Query(ByVal context As Microsoft.EntityFrameworkCore.DbContext, ByVal entityName As String) As IQueryable + Return context.Query(context.Model.FindEntityType(entityName).ClrType) + End Function + + + Public Function Query(ByVal context As Microsoft.EntityFrameworkCore.DbContext, ByVal entityType As Type) As IQueryable + Return CType((CType(context, IDbSetCache)).GetOrAddSet(context.GetDependencies().SetSource, entityType), IQueryable) + End Function + + + + Public Function ObtieneCampoIndice(ByVal context As Microsoft.EntityFrameworkCore.DbContext, ByVal Entidad As Object) As String + Dim entry = context.Entry(Entidad) + Dim pk = entry.Metadata.FindPrimaryKey() + Return pk.Properties.FirstOrDefault()?.Name + End Function + + + Public Function ObtieneMaximaLongitudCampo(bd As Microsoft.EntityFrameworkCore.DbContext, ByVal EspacioNombres As String, ByVal NombreTablaBase As String, ByVal NombreCampo As String) As Integer + Try + If Not NombreCampo.Contains(".") Then + Dim Tabla = bd.Model.FindEntityType(EspacioNombres & "." & NombreTablaBase) + If Tabla Is Nothing Then Throw New Exception("Tabla " & NombreTablaBase & " no encontrada") + Dim Campo = Tabla.FindProperty(NombreCampo) + If Campo Is Nothing Then + Return -1 ' Throw New Exception("No existe el campo " & NombreCampo & " en la tabla " & NombreTablaBase) + Else + Dim LongitudCampo As Integer? = Campo.GetMaxLength() + + If LongitudCampo.HasValue Then + Return LongitudCampo.Value + Else + Return -1 + End If + End If + Else + Return -1 + End If + Catch ex As Exception + Throw New Exception(ex.Message, ex) + End Try + End Function + + Public Function ExecSQL(Of T)(dbc As Microsoft.EntityFrameworkCore.DbContext, ByVal query As String) As List(Of T) + Dim Command = dbc.Database.GetDbConnection().CreateCommand() + Command.CommandText = query + Command.CommandType = Data.CommandType.Text + dbc.Database.OpenConnection() + Dim list As List(Of T) = New List(Of T)() + + Dim result = Command.ExecuteReader() + Dim obj As T = Nothing + + While result.Read() + obj = Activator.CreateInstance(Of T)() + + For Each prop As PropertyInfo In obj.[GetType]().GetProperties() + + If Not Object.Equals(result(prop.Name), DBNull.Value) Then + prop.SetValue(obj, result(prop.Name), Nothing) + End If + Next + + list.Add(obj) + End While + dbc.Database.CloseConnection() + Return list + End Function + + + Public Function CompruebaRegistroUnico(bd As Microsoft.EntityFrameworkCore.DbContext, CompruebaIndice As Boolean, EspacioNombres As String, NombreTabla As String, NombreCampo As String, Valor As Object, Entidad As Object) As Boolean + Dim Busqueda As String = NombreCampo & "==""" & CStr(Valor) & """" + If CompruebaIndice Then + Dim CampoIndice As String = bd.ObtieneCampoIndice(Entidad) + Dim ValorCampoIndice As String = CStr(bd.Entry(Entidad).[Property](CampoIndice).CurrentValue.ToString()) + Busqueda += " && " & CampoIndice & "!=" & ValorCampoIndice + End If + Dim resp As Boolean = bd.Query(EspacioNombres & "." & NombreTabla).Any(Busqueda) + Return Not resp + End Function + + + Public Function AhoraMySql(ByVal context As Microsoft.EntityFrameworkCore.DbContext) As DateTime + Dim cn = context.Database.GetDbConnection + Dim cmd = cn.CreateCommand + cmd.CommandText = "select now() as Ahora" + cn.Open() + Dim Hora As DateTime = cmd.ExecuteScalar + cn.Close() + Return Hora + End Function + + End Module +End Namespace \ No newline at end of file diff --git a/ObjetExtensions.vb b/ObjetExtensions.vb new file mode 100644 index 0000000..aa0d5d5 --- /dev/null +++ b/ObjetExtensions.vb @@ -0,0 +1,72 @@ +Imports System.Runtime.CompilerServices +Imports System.Linq.Expressions +Imports Microsoft.EntityFrameworkCore +Imports System.Data.Entity.Core.Objects +Imports System.Data.Entity.Core +Imports System.Reflection +Imports Microsoft.EntityFrameworkCore.Infrastructure +Imports Newtonsoft.Json +Imports System.Formats +'Imports System.Data.Entity.Core.Objects +'Imports System.Data.Entity.Core.Objects + +Namespace Extensiones + Public Module ObjetExtensions + + Public Function ObjetoNothingAVacio(ByVal Cadena As Object) As String + If Cadena Is Nothing Then + Return "" + Else + Return Cadena.ToString + End If + End Function + ' + 'Public Function GetDbContextFromEntity(ByVal entity As Object) As Data.Entity.DbContext + ' Dim object_context = GetObjectContextFromEntity(entity) + ' If object_context Is Nothing OrElse object_context.TransactionHandler Is Nothing Then Return Nothing + ' Return object_context.TransactionHandler.DbContext + 'End Function + 'Private Function GetObjectContextFromEntity(ByVal entity As Object) As ObjectContext + ' Dim field = entity.[GetType]().GetField("_entityWrapper") + ' If field Is Nothing Then Return Nothing + ' Dim wrapper = field.GetValue(entity) + ' Dim [property] = wrapper.[GetType]().GetProperty("Context") + ' Dim context = CType([property].GetValue(wrapper, Nothing), ObjectContext) + ' Return context + 'End Function + ' + 'Public Function ObtieneContexto(entity As Objects.DataClasses.EntityObject) As Objects.ObjectContext + ' Dim relationshipManager = DirectCast(entity, Objects.DataClasses.IEntityWithRelationships).RelationshipManager + ' Dim wrappedOwnerProperty = relationshipManager.GetType.GetProperty("WrappedOwner", Reflection.BindingFlags.Instance Or BindingFlags.NonPublic) + ' Return wrappedOwnerProperty.GetValue(relationshipManager).Context + 'End Function + + + Function GetDbContext(Of T As Class)(ByVal dbSet As DbSet(Of T)) As DbContext + Dim infrastructure = TryCast(dbSet, IInfrastructure(Of IServiceProvider)) + Dim serviceProvider = infrastructure.Instance + Dim currentDbContext = TryCast(serviceProvider.GetService(GetType(ICurrentDbContext)), ICurrentDbContext) + Return currentDbContext.Context + End Function + + Function Clonar(Of T)(ByVal self As T) As T + Dim serialized = JsonConvert.SerializeObject(self) + Return JsonConvert.DeserializeObject(Of T)(serialized) + End Function + + Sub CopiarPropiedadesDe(Of T)(ByVal Destino As T, ByVal Origen As T) + Dim props = Destino.GetType.GetProperties.Where(Function(x) x.CanWrite).ToList + For Each p In props + p.SetValue(Destino, Origen.GetType.GetProperty(p.Name).GetValue(Origen)) + Next + End Sub + + ' + 'Function ObtieneContexto(Of T As Class)(ByVal Objeto As T) As DbContext + ' Dim infrastructure = TryCast(Objeto, IInfrastructure(Of IServiceProvider)) + ' Dim serviceProvider = infrastructure.Instance + ' Dim currentDbContext = TryCast(serviceProvider.GetService(GetType(ICurrentDbContext)), ICurrentDbContext) + ' Return currentDbContext.Context + 'End Function + End Module +End Namespace \ No newline at end of file diff --git a/bbdd.vb b/bbdd.vb new file mode 100644 index 0000000..d8c1cf6 --- /dev/null +++ b/bbdd.vb @@ -0,0 +1,13 @@ +Imports Microsoft.EntityFrameworkCore + +Public Class bbdd + Public Shared Function ObtieneIPMysql(bd As DbContext) As String + Try + Dim sConexion As String = bd.Database.SqlQuery(Of String)($"select host from information_schema.processlist WHERE ID=connection_id();").ToList.First + Dim sIP As String = sConexion.Split(":")(0) + Return sIP + Catch ex As Exception + Return "** desconocida **" + End Try + End Function +End Class diff --git a/tsEFCore7.vbproj b/tsEFCore7.vbproj new file mode 100644 index 0000000..825830b --- /dev/null +++ b/tsEFCore7.vbproj @@ -0,0 +1,22 @@ + + + + SAK + SAK + SAK + SAK + + + + tsEFCore7 + net8.0 + + + + + + + + + +