From 3132ecc900617e4b243025aeac942fd671f3badb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Cort=C3=A9s?= Date: Thu, 12 Dec 2019 04:06:08 -0300 Subject: [PATCH] Initial Commit --- .gitignore | 356 ++++++++++ DAL/App.config | 15 + DAL/Carrera.cs | 31 + DAL/DAL.csproj | 123 ++++ DAL/Entities.Context.cs | 34 + DAL/Entities.Context.tt | 636 ++++++++++++++++++ DAL/Entities.Designer.cs | 10 + DAL/Entities.cs | 9 + DAL/Entities.edmx | 282 ++++++++ DAL/Entities.edmx.diagram | 19 + DAL/Entities.tt | 733 +++++++++++++++++++++ DAL/Participante.cs | 27 + DAL/Properties/AssemblyInfo.cs | 36 + DAL/Seminario.cs | 29 + DAL/Universidad.cs | 29 + DAL/Usuario.cs | 20 + DAL/packages.config | 4 + Universidad.sln | 58 ++ Universidad/Web.Debug.config | 23 + Universidad/Web.config | 38 ++ Universidad/base_page.master | 44 ++ Universidad/base_page.master.cs | 29 + Universidad/css/style.css | 27 + Universidad/index.aspx | 8 + Universidad/index.aspx.cs | 14 + Universidad/login.aspx | 43 ++ Universidad/login.aspx.cs | 66 ++ Universidad/packages.config | 5 + Universidad/register.aspx | 48 ++ Universidad/register.aspx.cs | 66 ++ Universidad/registrar_participante.aspx | 71 ++ Universidad/registrar_participante.aspx.cs | 124 ++++ Utils/PasswordHash.cs | 31 + Utils/Properties/AssemblyInfo.cs | 36 + Utils/Strings.cs | 17 + Utils/Utils.csproj | 49 ++ 36 files changed, 3190 insertions(+) create mode 100644 .gitignore create mode 100644 DAL/App.config create mode 100644 DAL/Carrera.cs create mode 100644 DAL/DAL.csproj create mode 100644 DAL/Entities.Context.cs create mode 100644 DAL/Entities.Context.tt create mode 100644 DAL/Entities.Designer.cs create mode 100644 DAL/Entities.cs create mode 100644 DAL/Entities.edmx create mode 100644 DAL/Entities.edmx.diagram create mode 100644 DAL/Entities.tt create mode 100644 DAL/Participante.cs create mode 100644 DAL/Properties/AssemblyInfo.cs create mode 100644 DAL/Seminario.cs create mode 100644 DAL/Universidad.cs create mode 100644 DAL/Usuario.cs create mode 100644 DAL/packages.config create mode 100644 Universidad.sln create mode 100644 Universidad/Web.Debug.config create mode 100644 Universidad/Web.config create mode 100644 Universidad/base_page.master create mode 100644 Universidad/base_page.master.cs create mode 100644 Universidad/css/style.css create mode 100644 Universidad/index.aspx create mode 100644 Universidad/index.aspx.cs create mode 100644 Universidad/login.aspx create mode 100644 Universidad/login.aspx.cs create mode 100644 Universidad/packages.config create mode 100644 Universidad/register.aspx create mode 100644 Universidad/register.aspx.cs create mode 100644 Universidad/registrar_participante.aspx create mode 100644 Universidad/registrar_participante.aspx.cs create mode 100644 Utils/PasswordHash.cs create mode 100644 Utils/Properties/AssemblyInfo.cs create mode 100644 Utils/Strings.cs create mode 100644 Utils/Utils.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b011a11 --- /dev/null +++ b/.gitignore @@ -0,0 +1,356 @@ + +# Created by https://www.gitignore.io/api/visualstudio +# Edit at https://www.gitignore.io/?templates=visualstudio + +### VisualStudio ### +## 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/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# 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/ + +# 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 + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# 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/ + +# End of https://www.gitignore.io/api/visualstudio diff --git a/DAL/App.config b/DAL/App.config new file mode 100644 index 0000000..2ed0193 --- /dev/null +++ b/DAL/App.config @@ -0,0 +1,15 @@ + + + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/DAL/Carrera.cs b/DAL/Carrera.cs new file mode 100644 index 0000000..38368ed --- /dev/null +++ b/DAL/Carrera.cs @@ -0,0 +1,31 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Collections.Generic; + + public partial class Carrera + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public Carrera() + { + this.participantes = new HashSet(); + } + + public int id { get; set; } + public string nombre { get; set; } + public int idUniversidad { get; set; } + + public virtual Universidad universidad { get; set; } + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public virtual ICollection participantes { get; set; } + } +} diff --git a/DAL/DAL.csproj b/DAL/DAL.csproj new file mode 100644 index 0000000..d834da2 --- /dev/null +++ b/DAL/DAL.csproj @@ -0,0 +1,123 @@ + + + + + + Debug + AnyCPU + {E995E818-EBAE-4AD7-86DD-F375E754BE32} + Library + Properties + DAL + DAL + v4.6.1 + 512 + true + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\EntityFramework.6.4.0\lib\net45\EntityFramework.dll + + + ..\packages\EntityFramework.6.4.0\lib\net45\EntityFramework.SqlServer.dll + + + + + + + + + + + + + + + + Entities.tt + + + True + True + Entities.Context.tt + + + True + True + Entities.tt + + + True + True + Entities.edmx + + + Entities.tt + + + + Entities.tt + + + Entities.tt + + + Entities.tt + + + + + + EntityModelCodeGenerator + Entities.Designer.cs + + + Entities.edmx + + + + + + + + + TextTemplatingFileGenerator + Entities.edmx + Entities.Context.cs + + + TextTemplatingFileGenerator + Entities.edmx + Entities.cs + + + + + + Este proyecto hace referencia a los paquetes NuGet que faltan en este equipo. Use la restauración de paquetes NuGet para descargarlos. Para obtener más información, consulte http://go.microsoft.com/fwlink/?LinkID=322105. El archivo que falta es {0}. + + + + + + \ No newline at end of file diff --git a/DAL/Entities.Context.cs b/DAL/Entities.Context.cs new file mode 100644 index 0000000..8629e95 --- /dev/null +++ b/DAL/Entities.Context.cs @@ -0,0 +1,34 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Data.Entity; + using System.Data.Entity.Infrastructure; + + public partial class Entities : DbContext + { + public Entities() + : base("name=Entities") + { + } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + throw new UnintentionalCodeFirstException(); + } + + public virtual DbSet Carreras { get; set; } + public virtual DbSet Participantes { get; set; } + public virtual DbSet Seminarios { get; set; } + public virtual DbSet Universidades { get; set; } + public virtual DbSet Usuarios { get; set; } + } +} diff --git a/DAL/Entities.Context.tt b/DAL/Entities.Context.tt new file mode 100644 index 0000000..b18345d --- /dev/null +++ b/DAL/Entities.Context.tt @@ -0,0 +1,636 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF6.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"Entities.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var loader = new EdmMetadataLoader(textTransform.Host, textTransform.Errors); +var itemCollection = loader.CreateEdmItemCollection(inputFile); +var modelNamespace = loader.GetModelNamespace(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +var container = itemCollection.OfType().FirstOrDefault(); +if (container == null) +{ + return string.Empty; +} +#> +//------------------------------------------------------------------------------ +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ + +<# + +var codeNamespace = code.VsNamespaceSuggestion(); +if (!String.IsNullOrEmpty(codeNamespace)) +{ +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<# + PushIndent(" "); +} + +#> +using System; +using System.Data.Entity; +using System.Data.Entity.Infrastructure; +<# +if (container.FunctionImports.Any()) +{ +#> +using System.Data.Entity.Core.Objects; +using System.Linq; +<# +} +#> + +<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext +{ + public <#=code.Escape(container)#>() + : base("name=<#=container.Name#>") + { +<# +if (!loader.IsLazyLoadingEnabled(container)) +{ +#> + this.Configuration.LazyLoadingEnabled = false; +<# +} + +foreach (var entitySet in container.BaseEntitySets.OfType()) +{ + // Note: the DbSet members are defined below such that the getter and + // setter always have the same accessibility as the DbSet definition + if (Accessibility.ForReadOnlyProperty(entitySet) != "public") + { +#> + <#=codeStringGenerator.DbSetInitializer(entitySet)#> +<# + } +} +#> + } + + protected override void OnModelCreating(DbModelBuilder modelBuilder) + { + throw new UnintentionalCodeFirstException(); + } + +<# + foreach (var entitySet in container.BaseEntitySets.OfType()) + { +#> + <#=codeStringGenerator.DbSet(entitySet)#> +<# + } + + foreach (var edmFunction in container.FunctionImports) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: false); + } +#> +} +<# + +if (!String.IsNullOrEmpty(codeNamespace)) +{ + PopIndent(); +#> +} +<# +} +#> +<#+ + +private void WriteFunctionImport(TypeMapper typeMapper, CodeStringGenerator codeStringGenerator, EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) +{ + if (typeMapper.IsComposable(edmFunction)) + { +#> + + [DbFunction("<#=edmFunction.NamespaceName#>", "<#=edmFunction.Name#>")] + <#=codeStringGenerator.ComposableFunctionMethod(edmFunction, modelNamespace)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ComposableCreateQuery(edmFunction, modelNamespace)#> + } +<#+ + } + else + { +#> + + <#=codeStringGenerator.FunctionMethod(edmFunction, modelNamespace, includeMergeOption)#> + { +<#+ + codeStringGenerator.WriteFunctionParameters(edmFunction, WriteFunctionParameter); +#> + <#=codeStringGenerator.ExecuteFunction(edmFunction, modelNamespace, includeMergeOption)#> + } +<#+ + if (typeMapper.GenerateMergeOptionFunction(edmFunction, includeMergeOption)) + { + WriteFunctionImport(typeMapper, codeStringGenerator, edmFunction, modelNamespace, includeMergeOption: true); + } + } +} + +public void WriteFunctionParameter(string name, string isNotNull, string notNullInit, string nullInit) +{ +#> + var <#=name#> = <#=isNotNull#> ? + <#=notNullInit#> : + <#=nullInit#>; + +<#+ +} + +public const string TemplateId = "CSharp_DbContext_Context_EF6"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navProp) + { + var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), + navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navProp), + _code.SpaceAfter(Accessibility.ForGetter(navProp)), + _code.SpaceAfter(Accessibility.ForSetter(navProp))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} virtual DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string DbSetInitializer(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} = Set<{1}>();", + _code.Escape(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public static string FixNamespaces(string typeName) + { + return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial."); + } + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + typeName = FixNamespaces(typeName); + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} +#> \ No newline at end of file diff --git a/DAL/Entities.Designer.cs b/DAL/Entities.Designer.cs new file mode 100644 index 0000000..60f5e74 --- /dev/null +++ b/DAL/Entities.Designer.cs @@ -0,0 +1,10 @@ +// La generación de código T4 está habilitada para el modelo 'C:\Users\dell\source\repos\universidad\DAL\Entities.edmx'. +// Para habilitar la generación de código heredada, cambie el valor de la propiedad del diseñador 'Estrategia de generación de código' +// por 'ObjectContext heredado'. Esta propiedad está disponible en la ventana Propiedades cuando se abre +// el modelo en el diseñador. + +// Si no se ha generado ninguna clase de contexto y de entidad, puede que haya creado un modelo vacío pero +// no haya elegido todavía la versión de Entity Framework que se va a usar. Para generar una clase de contexto y clases de entidad +// para el modelo, abra el modelo en el diseñador, haga clic con el botón secundario en la superficie del diseñador y +// seleccione 'Actualizar modelo desde base de datos...', 'Generar base de datos desde modelo...' o 'Agregar elemento de generación +// de código...'. \ No newline at end of file diff --git a/DAL/Entities.cs b/DAL/Entities.cs new file mode 100644 index 0000000..7a7d3c9 --- /dev/null +++ b/DAL/Entities.cs @@ -0,0 +1,9 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + diff --git a/DAL/Entities.edmx b/DAL/Entities.edmx new file mode 100644 index 0000000..15cc81c --- /dev/null +++ b/DAL/Entities.edmx @@ -0,0 +1,282 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DAL/Entities.edmx.diagram b/DAL/Entities.edmx.diagram new file mode 100644 index 0000000..cb58d33 --- /dev/null +++ b/DAL/Entities.edmx.diagram @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DAL/Entities.tt b/DAL/Entities.tt new file mode 100644 index 0000000..9234210 --- /dev/null +++ b/DAL/Entities.tt @@ -0,0 +1,733 @@ +<#@ template language="C#" debug="false" hostspecific="true"#> +<#@ include file="EF6.Utility.CS.ttinclude"#><#@ + output extension=".cs"#><# + +const string inputFile = @"Entities.edmx"; +var textTransform = DynamicTextTransformation.Create(this); +var code = new CodeGenerationTools(this); +var ef = new MetadataTools(this); +var typeMapper = new TypeMapper(code, ef, textTransform.Errors); +var fileManager = EntityFrameworkTemplateFileManager.Create(this); +var itemCollection = new EdmMetadataLoader(textTransform.Host, textTransform.Errors).CreateEdmItemCollection(inputFile); +var codeStringGenerator = new CodeStringGenerator(code, typeMapper, ef); + +if (!typeMapper.VerifyCaseInsensitiveTypeUniqueness(typeMapper.GetAllGlobalItems(itemCollection), inputFile)) +{ + return string.Empty; +} + +WriteHeader(codeStringGenerator, fileManager); + +foreach (var entity in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(entity.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false)#> +<#=codeStringGenerator.EntityClassOpening(entity)#> +{ +<# + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity); + var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity); + var complexProperties = typeMapper.GetComplexProperties(entity); + + if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any()) + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public <#=code.Escape(entity)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var navigationProperty in collectionNavigationProperties) + { +#> + this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>(); +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(entity); + if (simpleProperties.Any()) + { + foreach (var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var complexProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(complexProperty)#> +<# + } + } + + var navigationProperties = typeMapper.GetNavigationProperties(entity); + if (navigationProperties.Any()) + { +#> + +<# + foreach (var navigationProperty in navigationProperties) + { + if (navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many) + { +#> + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] +<# + } +#> + <#=codeStringGenerator.NavigationProperty(navigationProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var complex in typeMapper.GetItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(complex.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> +{ +<# + var complexProperties = typeMapper.GetComplexProperties(complex); + var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex); + + if (propertiesWithDefaultValues.Any() || complexProperties.Any()) + { +#> + public <#=code.Escape(complex)#>() + { +<# + foreach (var edmProperty in propertiesWithDefaultValues) + { +#> + this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>; +<# + } + + foreach (var complexProperty in complexProperties) + { +#> + this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>(); +<# + } +#> + } + +<# + } + + var simpleProperties = typeMapper.GetSimpleProperties(complex); + if (simpleProperties.Any()) + { + foreach(var edmProperty in simpleProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } + + if (complexProperties.Any()) + { +#> + +<# + foreach(var edmProperty in complexProperties) + { +#> + <#=codeStringGenerator.Property(edmProperty)#> +<# + } + } +#> +} +<# + EndNamespace(code); +} + +foreach (var enumType in typeMapper.GetEnumItemsToGenerate(itemCollection)) +{ + fileManager.StartNewFile(enumType.Name + ".cs"); + BeginNamespace(code); +#> +<#=codeStringGenerator.UsingDirectives(inHeader: false, includeCollections: false)#> +<# + if (typeMapper.EnumIsFlags(enumType)) + { +#> +[Flags] +<# + } +#> +<#=codeStringGenerator.EnumOpening(enumType)#> +{ +<# + var foundOne = false; + + foreach (MetadataItem member in typeMapper.GetEnumMembers(enumType)) + { + foundOne = true; +#> + <#=code.Escape(typeMapper.GetEnumMemberName(member))#> = <#=typeMapper.GetEnumMemberValue(member)#>, +<# + } + + if (foundOne) + { + this.GenerationEnvironment.Remove(this.GenerationEnvironment.Length - 3, 1); + } +#> +} +<# + EndNamespace(code); +} + +fileManager.Process(); + +#> +<#+ + +public void WriteHeader(CodeStringGenerator codeStringGenerator, EntityFrameworkTemplateFileManager fileManager) +{ + fileManager.StartHeader(); +#> +//------------------------------------------------------------------------------ +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine1")#> +// +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine2")#> +// <#=CodeGenerationTools.GetResourceString("Template_GeneratedCodeCommentLine3")#> +// +//------------------------------------------------------------------------------ +<#=codeStringGenerator.UsingDirectives(inHeader: true)#> +<#+ + fileManager.EndBlock(); +} + +public void BeginNamespace(CodeGenerationTools code) +{ + var codeNamespace = code.VsNamespaceSuggestion(); + if (!String.IsNullOrEmpty(codeNamespace)) + { +#> +namespace <#=code.EscapeNamespace(codeNamespace)#> +{ +<#+ + PushIndent(" "); + } +} + +public void EndNamespace(CodeGenerationTools code) +{ + if (!String.IsNullOrEmpty(code.VsNamespaceSuggestion())) + { + PopIndent(); +#> +} +<#+ + } +} + +public const string TemplateId = "CSharp_DbContext_Types_EF6"; + +public class CodeStringGenerator +{ + private readonly CodeGenerationTools _code; + private readonly TypeMapper _typeMapper; + private readonly MetadataTools _ef; + + public CodeStringGenerator(CodeGenerationTools code, TypeMapper typeMapper, MetadataTools ef) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(typeMapper, "typeMapper"); + ArgumentNotNull(ef, "ef"); + + _code = code; + _typeMapper = typeMapper; + _ef = ef; + } + + public string Property(EdmProperty edmProperty) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + Accessibility.ForProperty(edmProperty), + _typeMapper.GetTypeName(edmProperty.TypeUsage), + _code.Escape(edmProperty), + _code.SpaceAfter(Accessibility.ForGetter(edmProperty)), + _code.SpaceAfter(Accessibility.ForSetter(edmProperty))); + } + + public string NavigationProperty(NavigationProperty navProp) + { + var endType = _typeMapper.GetTypeName(navProp.ToEndMember.GetEntityType()); + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2} {{ {3}get; {4}set; }}", + AccessibilityAndVirtual(Accessibility.ForNavigationProperty(navProp)), + navProp.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType, + _code.Escape(navProp), + _code.SpaceAfter(Accessibility.ForGetter(navProp)), + _code.SpaceAfter(Accessibility.ForSetter(navProp))); + } + + public string AccessibilityAndVirtual(string accessibility) + { + return accessibility + (accessibility != "private" ? " virtual" : ""); + } + + public string EntityClassOpening(EntityType entity) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1}partial class {2}{3}", + Accessibility.ForType(entity), + _code.SpaceAfter(_code.AbstractOption(entity)), + _code.Escape(entity), + _code.StringBefore(" : ", _typeMapper.GetTypeName(entity.BaseType))); + } + + public string EnumOpening(SimpleType enumType) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} enum {1} : {2}", + Accessibility.ForType(enumType), + _code.Escape(enumType), + _code.Escape(_typeMapper.UnderlyingClrType(enumType))); + } + + public void WriteFunctionParameters(EdmFunction edmFunction, Action writeParameter) + { + var parameters = FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + foreach (var parameter in parameters.Where(p => p.NeedsLocalVariable)) + { + var isNotNull = parameter.IsNullableOfT ? parameter.FunctionParameterName + ".HasValue" : parameter.FunctionParameterName + " != null"; + var notNullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", " + parameter.FunctionParameterName + ")"; + var nullInit = "new ObjectParameter(\"" + parameter.EsqlParameterName + "\", typeof(" + TypeMapper.FixNamespaces(parameter.RawClrTypeName) + "))"; + writeParameter(parameter.LocalVariableName, isNotNull, notNullInit, nullInit); + } + } + + public string ComposableFunctionMethod(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "{0} IQueryable<{1}> {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + _code.Escape(edmFunction), + string.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray())); + } + + public string ComposableCreateQuery(EdmFunction edmFunction, string modelNamespace) + { + var parameters = _typeMapper.GetParameters(edmFunction); + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<{0}>(\"[{1}].[{2}]({3})\"{4});", + _typeMapper.GetTypeName(_typeMapper.GetReturnType(edmFunction), modelNamespace), + edmFunction.NamespaceName, + edmFunction.Name, + string.Join(", ", parameters.Select(p => "@" + p.EsqlParameterName).ToArray()), + _code.StringBefore(", ", string.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray()))); + } + + public string FunctionMethod(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var paramList = String.Join(", ", parameters.Select(p => TypeMapper.FixNamespaces(p.FunctionParameterType) + " " + p.FunctionParameterName).ToArray()); + if (includeMergeOption) + { + paramList = _code.StringAfter(paramList, ", ") + "MergeOption mergeOption"; + } + + return string.Format( + CultureInfo.InvariantCulture, + "{0} {1} {2}({3})", + AccessibilityAndVirtual(Accessibility.ForMethod(edmFunction)), + returnType == null ? "int" : "ObjectResult<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + _code.Escape(edmFunction), + paramList); + } + + public string ExecuteFunction(EdmFunction edmFunction, string modelNamespace, bool includeMergeOption) + { + var parameters = _typeMapper.GetParameters(edmFunction); + var returnType = _typeMapper.GetReturnType(edmFunction); + + var callParams = _code.StringBefore(", ", String.Join(", ", parameters.Select(p => p.ExecuteParameterName).ToArray())); + if (includeMergeOption) + { + callParams = ", mergeOption" + callParams; + } + + return string.Format( + CultureInfo.InvariantCulture, + "return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction{0}(\"{1}\"{2});", + returnType == null ? "" : "<" + _typeMapper.GetTypeName(returnType, modelNamespace) + ">", + edmFunction.Name, + callParams); + } + + public string DbSet(EntitySet entitySet) + { + return string.Format( + CultureInfo.InvariantCulture, + "{0} virtual DbSet<{1}> {2} {{ get; set; }}", + Accessibility.ForReadOnlyProperty(entitySet), + _typeMapper.GetTypeName(entitySet.ElementType), + _code.Escape(entitySet)); + } + + public string UsingDirectives(bool inHeader, bool includeCollections = true) + { + return inHeader == string.IsNullOrEmpty(_code.VsNamespaceSuggestion()) + ? string.Format( + CultureInfo.InvariantCulture, + "{0}using System;{1}" + + "{2}", + inHeader ? Environment.NewLine : "", + includeCollections ? (Environment.NewLine + "using System.Collections.Generic;") : "", + inHeader ? "" : Environment.NewLine) + : ""; + } +} + +public class TypeMapper +{ + private const string ExternalTypeNameAttributeName = @"http://schemas.microsoft.com/ado/2006/04/codegeneration:ExternalTypeName"; + + private readonly System.Collections.IList _errors; + private readonly CodeGenerationTools _code; + private readonly MetadataTools _ef; + + public TypeMapper(CodeGenerationTools code, MetadataTools ef, System.Collections.IList errors) + { + ArgumentNotNull(code, "code"); + ArgumentNotNull(ef, "ef"); + ArgumentNotNull(errors, "errors"); + + _code = code; + _ef = ef; + _errors = errors; + } + + public static string FixNamespaces(string typeName) + { + return typeName.Replace("System.Data.Spatial.", "System.Data.Entity.Spatial."); + } + + public string GetTypeName(TypeUsage typeUsage) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace: null); + } + + public string GetTypeName(EdmType edmType) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: null); + } + + public string GetTypeName(TypeUsage typeUsage, string modelNamespace) + { + return typeUsage == null ? null : GetTypeName(typeUsage.EdmType, _ef.IsNullable(typeUsage), modelNamespace); + } + + public string GetTypeName(EdmType edmType, string modelNamespace) + { + return GetTypeName(edmType, isNullable: null, modelNamespace: modelNamespace); + } + + public string GetTypeName(EdmType edmType, bool? isNullable, string modelNamespace) + { + if (edmType == null) + { + return null; + } + + var collectionType = edmType as CollectionType; + if (collectionType != null) + { + return String.Format(CultureInfo.InvariantCulture, "ICollection<{0}>", GetTypeName(collectionType.TypeUsage, modelNamespace)); + } + + var typeName = _code.Escape(edmType.MetadataProperties + .Where(p => p.Name == ExternalTypeNameAttributeName) + .Select(p => (string)p.Value) + .FirstOrDefault()) + ?? (modelNamespace != null && edmType.NamespaceName != modelNamespace ? + _code.CreateFullName(_code.EscapeNamespace(edmType.NamespaceName), _code.Escape(edmType)) : + _code.Escape(edmType)); + + if (edmType is StructuralType) + { + return typeName; + } + + if (edmType is SimpleType) + { + var clrType = UnderlyingClrType(edmType); + if (!IsEnumType(edmType)) + { + typeName = _code.Escape(clrType); + } + + typeName = FixNamespaces(typeName); + + return clrType.IsValueType && isNullable == true ? + String.Format(CultureInfo.InvariantCulture, "Nullable<{0}>", typeName) : + typeName; + } + + throw new ArgumentException("edmType"); + } + + public Type UnderlyingClrType(EdmType edmType) + { + ArgumentNotNull(edmType, "edmType"); + + var primitiveType = edmType as PrimitiveType; + if (primitiveType != null) + { + return primitiveType.ClrEquivalentType; + } + + if (IsEnumType(edmType)) + { + return GetEnumUnderlyingType(edmType).ClrEquivalentType; + } + + return typeof(object); + } + + public object GetEnumMemberValue(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var valueProperty = enumMember.GetType().GetProperty("Value"); + return valueProperty == null ? null : valueProperty.GetValue(enumMember, null); + } + + public string GetEnumMemberName(MetadataItem enumMember) + { + ArgumentNotNull(enumMember, "enumMember"); + + var nameProperty = enumMember.GetType().GetProperty("Name"); + return nameProperty == null ? null : (string)nameProperty.GetValue(enumMember, null); + } + + public System.Collections.IEnumerable GetEnumMembers(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var membersProperty = enumType.GetType().GetProperty("Members"); + return membersProperty != null + ? (System.Collections.IEnumerable)membersProperty.GetValue(enumType, null) + : Enumerable.Empty(); + } + + public bool EnumIsFlags(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + var isFlagsProperty = enumType.GetType().GetProperty("IsFlags"); + return isFlagsProperty != null && (bool)isFlagsProperty.GetValue(enumType, null); + } + + public bool IsEnumType(GlobalItem edmType) + { + ArgumentNotNull(edmType, "edmType"); + + return edmType.GetType().Name == "EnumType"; + } + + public PrimitiveType GetEnumUnderlyingType(EdmType enumType) + { + ArgumentNotNull(enumType, "enumType"); + + return (PrimitiveType)enumType.GetType().GetProperty("UnderlyingType").GetValue(enumType, null); + } + + public string CreateLiteral(object value) + { + if (value == null || value.GetType() != typeof(TimeSpan)) + { + return _code.CreateLiteral(value); + } + + return string.Format(CultureInfo.InvariantCulture, "new TimeSpan({0})", ((TimeSpan)value).Ticks); + } + + public bool VerifyCaseInsensitiveTypeUniqueness(IEnumerable types, string sourceFile) + { + ArgumentNotNull(types, "types"); + ArgumentNotNull(sourceFile, "sourceFile"); + + var hash = new HashSet(StringComparer.InvariantCultureIgnoreCase); + if (types.Any(item => !hash.Add(item))) + { + _errors.Add( + new CompilerError(sourceFile, -1, -1, "6023", + String.Format(CultureInfo.CurrentCulture, CodeGenerationTools.GetResourceString("Template_CaseInsensitiveTypeConflict")))); + return false; + } + return true; + } + + public IEnumerable GetEnumItemsToGenerate(IEnumerable itemCollection) + { + return GetItemsToGenerate(itemCollection) + .Where(e => IsEnumType(e)); + } + + public IEnumerable GetItemsToGenerate(IEnumerable itemCollection) where T: EdmType + { + return itemCollection + .OfType() + .Where(i => !i.MetadataProperties.Any(p => p.Name == ExternalTypeNameAttributeName)) + .OrderBy(i => i.Name); + } + + public IEnumerable GetAllGlobalItems(IEnumerable itemCollection) + { + return itemCollection + .Where(i => i is EntityType || i is ComplexType || i is EntityContainer || IsEnumType(i)) + .Select(g => GetGlobalItemName(g)); + } + + public string GetGlobalItemName(GlobalItem item) + { + if (item is EdmType) + { + return ((EdmType)item).Name; + } + else + { + return ((EntityContainer)item).Name; + } + } + + public IEnumerable GetSimpleProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetSimpleProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetComplexProperties(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is ComplexType && p.DeclaringType == type); + } + + public IEnumerable GetPropertiesWithDefaultValues(EntityType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetPropertiesWithDefaultValues(ComplexType type) + { + return type.Properties.Where(p => p.TypeUsage.EdmType is SimpleType && p.DeclaringType == type && p.DefaultValue != null); + } + + public IEnumerable GetNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type); + } + + public IEnumerable GetCollectionNavigationProperties(EntityType type) + { + return type.NavigationProperties.Where(np => np.DeclaringType == type && np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many); + } + + public FunctionParameter GetReturnParameter(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var returnParamsProperty = edmFunction.GetType().GetProperty("ReturnParameters"); + return returnParamsProperty == null + ? edmFunction.ReturnParameter + : ((IEnumerable)returnParamsProperty.GetValue(edmFunction, null)).FirstOrDefault(); + } + + public bool IsComposable(EdmFunction edmFunction) + { + ArgumentNotNull(edmFunction, "edmFunction"); + + var isComposableProperty = edmFunction.GetType().GetProperty("IsComposableAttribute"); + return isComposableProperty != null && (bool)isComposableProperty.GetValue(edmFunction, null); + } + + public IEnumerable GetParameters(EdmFunction edmFunction) + { + return FunctionImportParameter.Create(edmFunction.Parameters, _code, _ef); + } + + public TypeUsage GetReturnType(EdmFunction edmFunction) + { + var returnParam = GetReturnParameter(edmFunction); + return returnParam == null ? null : _ef.GetElementType(returnParam.TypeUsage); + } + + public bool GenerateMergeOptionFunction(EdmFunction edmFunction, bool includeMergeOption) + { + var returnType = GetReturnType(edmFunction); + return !includeMergeOption && returnType != null && returnType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType; + } +} + +public static void ArgumentNotNull(T arg, string name) where T : class +{ + if (arg == null) + { + throw new ArgumentNullException(name); + } +} +#> \ No newline at end of file diff --git a/DAL/Participante.cs b/DAL/Participante.cs new file mode 100644 index 0000000..9966bac --- /dev/null +++ b/DAL/Participante.cs @@ -0,0 +1,27 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Collections.Generic; + + public partial class Participante + { + public int id { get; set; } + public string nombre { get; set; } + public System.DateTime fechaInscripcion { get; set; } + public double pga { get; set; } + public int idCarrera { get; set; } + public int idSeminario { get; set; } + + public virtual Carrera carrera { get; set; } + public virtual Seminario seminario { get; set; } + } +} diff --git a/DAL/Properties/AssemblyInfo.cs b/DAL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..77a7f25 --- /dev/null +++ b/DAL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos valores de atributo para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("DAL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DAL")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde +// COM, establezca el atributo ComVisible en true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. +[assembly: Guid("e995e818-ebae-4ad7-86dd-f375e754be32")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los números de compilación y de revisión predeterminados +// mediante el carácter "*", como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DAL/Seminario.cs b/DAL/Seminario.cs new file mode 100644 index 0000000..2c7ff3d --- /dev/null +++ b/DAL/Seminario.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Collections.Generic; + + public partial class Seminario + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public Seminario() + { + this.participantes = new HashSet(); + } + + public int id { get; set; } + public string nombre { get; set; } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public virtual ICollection participantes { get; set; } + } +} diff --git a/DAL/Universidad.cs b/DAL/Universidad.cs new file mode 100644 index 0000000..ecf48cd --- /dev/null +++ b/DAL/Universidad.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Collections.Generic; + + public partial class Universidad + { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public Universidad() + { + this.carreras = new HashSet(); + } + + public int id { get; set; } + public string nombre { get; set; } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] + public virtual ICollection carreras { get; set; } + } +} diff --git a/DAL/Usuario.cs b/DAL/Usuario.cs new file mode 100644 index 0000000..e0e8c6b --- /dev/null +++ b/DAL/Usuario.cs @@ -0,0 +1,20 @@ +//------------------------------------------------------------------------------ +// +// Este código se generó a partir de una plantilla. +// +// Los cambios manuales en este archivo pueden causar un comportamiento inesperado de la aplicación. +// Los cambios manuales en este archivo se sobrescribirán si se regenera el código. +// +//------------------------------------------------------------------------------ + +namespace DAL +{ + using System; + using System.Collections.Generic; + + public partial class Usuario + { + public string nombre { get; set; } + public string password { get; set; } + } +} diff --git a/DAL/packages.config b/DAL/packages.config new file mode 100644 index 0000000..148a4a7 --- /dev/null +++ b/DAL/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Universidad.sln b/Universidad.sln new file mode 100644 index 0000000..2054185 --- /dev/null +++ b/Universidad.sln @@ -0,0 +1,58 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28307.902 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "Universidad", "Universidad\", "{81B052AD-2BE0-4DE6-AD4C-A998DA899813}" + ProjectSection(WebsiteProperties) = preProject + TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.6.1" + ProjectReferences = "{e995e818-ebae-4ad7-86dd-f375e754be32}|DAL.dll;{1f33e2d1-699b-4aca-8f42-a673d7aa5d63}|Utils.dll;" + Debug.AspNetCompiler.VirtualPath = "/localhost_60766" + Debug.AspNetCompiler.PhysicalPath = "Universidad\" + Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_60766\" + Debug.AspNetCompiler.Updateable = "true" + Debug.AspNetCompiler.ForceOverwrite = "true" + Debug.AspNetCompiler.FixedNames = "false" + Debug.AspNetCompiler.Debug = "True" + Release.AspNetCompiler.VirtualPath = "/localhost_60766" + Release.AspNetCompiler.PhysicalPath = "Universidad\" + Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_60766\" + Release.AspNetCompiler.Updateable = "true" + Release.AspNetCompiler.ForceOverwrite = "true" + Release.AspNetCompiler.FixedNames = "false" + Release.AspNetCompiler.Debug = "False" + VWDPort = "60766" + SlnRelativePath = "Universidad\" + DefaultWebSiteLanguage = "Visual C#" + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DAL", "DAL\DAL.csproj", "{E995E818-EBAE-4AD7-86DD-F375E754BE32}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "Utils\Utils.csproj", "{1F33E2D1-699B-4ACA-8F42-A673D7AA5D63}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81B052AD-2BE0-4DE6-AD4C-A998DA899813}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81B052AD-2BE0-4DE6-AD4C-A998DA899813}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81B052AD-2BE0-4DE6-AD4C-A998DA899813}.Release|Any CPU.ActiveCfg = Debug|Any CPU + {81B052AD-2BE0-4DE6-AD4C-A998DA899813}.Release|Any CPU.Build.0 = Debug|Any CPU + {E995E818-EBAE-4AD7-86DD-F375E754BE32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E995E818-EBAE-4AD7-86DD-F375E754BE32}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E995E818-EBAE-4AD7-86DD-F375E754BE32}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E995E818-EBAE-4AD7-86DD-F375E754BE32}.Release|Any CPU.Build.0 = Release|Any CPU + {1F33E2D1-699B-4ACA-8F42-A673D7AA5D63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F33E2D1-699B-4ACA-8F42-A673D7AA5D63}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F33E2D1-699B-4ACA-8F42-A673D7AA5D63}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F33E2D1-699B-4ACA-8F42-A673D7AA5D63}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {256267E8-6316-414B-8582-086DF69C97DB} + EndGlobalSection +EndGlobal diff --git a/Universidad/Web.Debug.config b/Universidad/Web.Debug.config new file mode 100644 index 0000000..8436757 --- /dev/null +++ b/Universidad/Web.Debug.config @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Universidad/Web.config b/Universidad/Web.config new file mode 100644 index 0000000..43e06f8 --- /dev/null +++ b/Universidad/Web.config @@ -0,0 +1,38 @@ + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/Universidad/base_page.master b/Universidad/base_page.master new file mode 100644 index 0000000..ba2f1a2 --- /dev/null +++ b/Universidad/base_page.master @@ -0,0 +1,44 @@ +<%@ Master Language="C#" AutoEventWireup="true" CodeFile="base_page.master.cs" Inherits="base_page" %> + + + + + + + + + + + + + +
+ +
+
+ +
+ + +
+
+
+ +
+ + + + + + diff --git a/Universidad/base_page.master.cs b/Universidad/base_page.master.cs new file mode 100644 index 0000000..a13bae4 --- /dev/null +++ b/Universidad/base_page.master.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class base_page : System.Web.UI.MasterPage +{ + protected void Page_Load(object sender, EventArgs e) + { + if(Session["username"] == null) + { + Response.Redirect("login.aspx"); + return; + } + + username_literal.Text = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Session["username"].ToString()); + time_label.InnerText = DateTime.Now.ToLongDateString(); + } + + + protected void onCerrarSesionClick(object sender, EventArgs e) + { + Session["username"] = null; + Response.Redirect("login.aspx"); + } +} diff --git a/Universidad/css/style.css b/Universidad/css/style.css new file mode 100644 index 0000000..4832a4e --- /dev/null +++ b/Universidad/css/style.css @@ -0,0 +1,27 @@ +.container { + padding-top: 6em; + padding-bottom: 6em; +} +.sidebar { + border-right: lightgray solid 1px; + margin-right: 1em; +} + +.row { + height: 100%; +} + +.card-login { + max-width: 33vw; + margin-top: 15vh; + margin-left: auto; + margin-right: auto; +} + +.invalid-message { + display: block; + width: 100%; + margin-top: 0.25rem; + font-size: 0.875em; + color: #dc3545; +} \ No newline at end of file diff --git a/Universidad/index.aspx b/Universidad/index.aspx new file mode 100644 index 0000000..12d9f77 --- /dev/null +++ b/Universidad/index.aspx @@ -0,0 +1,8 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/base_page.master" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %> + + + Index + + + + diff --git a/Universidad/index.aspx.cs b/Universidad/index.aspx.cs new file mode 100644 index 0000000..89898ee --- /dev/null +++ b/Universidad/index.aspx.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class index : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + + } +} \ No newline at end of file diff --git a/Universidad/login.aspx b/Universidad/login.aspx new file mode 100644 index 0000000..9c419ee --- /dev/null +++ b/Universidad/login.aspx @@ -0,0 +1,43 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %> + + + + + + + Login + + + + +
+ +
+ + + + + diff --git a/Universidad/login.aspx.cs b/Universidad/login.aspx.cs new file mode 100644 index 0000000..057e538 --- /dev/null +++ b/Universidad/login.aspx.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using DAL; +using Utils; + +public partial class login : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + if(Session["username"] != null) + { + Response.Redirect("/index.aspx"); + return; + } + } + + protected void onLoginClick(object sender, EventArgs e) + { + if (Page.IsValid) + { + Entities entities = new Entities(); + Usuario usuario = (from u in entities.Usuarios where u.nombre == username_box.Text select u).SingleOrDefault(); + + if (usuario == null) + { + error_message.Text = "El usuario o contraseña no son validos"; + return; + } + + if (!PasswordHash.Compare(password_box.Text, usuario.password)) + { + error_message.Text = "El usuario o contraseña no son validos"; + return; + } + + Session["username"] = usuario.nombre; + Response.Redirect("/index.aspx"); + } + } + + protected void validateUsername(object sender, ServerValidateEventArgs e) + { + if (username_box.Text.Length > 15) + { + e.IsValid = false; + username_validator.Text = "El nombre de usuario es demasiado largo, maximo de 15 caracteres"; + return; + } + e.IsValid = true; + } + + protected void validatePassword(object sender, ServerValidateEventArgs e) + { + if (password_box.Text.Length > 15) + { + e.IsValid = false; + password_validator.Text = "La contraseña es demasiado larga, maximo de 15 caracteres"; + return; + } + e.IsValid = true; + } +} \ No newline at end of file diff --git a/Universidad/packages.config b/Universidad/packages.config new file mode 100644 index 0000000..7dfbe46 --- /dev/null +++ b/Universidad/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/Universidad/register.aspx b/Universidad/register.aspx new file mode 100644 index 0000000..fa36c52 --- /dev/null +++ b/Universidad/register.aspx @@ -0,0 +1,48 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="register" %> + + + + + + + Registrar + + + + +
+ +
+ + + + + diff --git a/Universidad/register.aspx.cs b/Universidad/register.aspx.cs new file mode 100644 index 0000000..13350aa --- /dev/null +++ b/Universidad/register.aspx.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using DAL; +using Utils; + +public partial class register : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + if (Session["username"] != null) + { + Response.Redirect("/index.aspx"); + return; + } + } + + protected void onRegisterClick(object sender, EventArgs e) + { + if (Page.IsValid) + { + Entities entities = new Entities(); + Usuario usuario = new Usuario(); + usuario.nombre = username_box.Text; + usuario.password = PasswordHash.Hash(password_box.Text); + entities.Usuarios.Add(usuario); + entities.SaveChanges(); + + Response.Redirect("/login.aspx"); + } + } + + protected void validateUsername(object sender, ServerValidateEventArgs e) + { + if (username_box.Text.Trim().Length > 15) + { + e.IsValid = false; + username_validator.Text = "El nombre de usuario es demasiado largo, maximo de 15 caracteres"; + return; + } + + Entities entities = new Entities(); + if((from u in entities.Usuarios where u.nombre == username_box.Text.Trim() select u.nombre).SingleOrDefault() != null) + { + e.IsValid = false; + username_validator.Text = "El nombre de usuario ya existe"; + return; + } + + e.IsValid = true; + } + + protected void validatePassword(object sender, ServerValidateEventArgs e) + { + if (password_box.Text.Length > 15) + { + e.IsValid = false; + password_validator.Text = "La contraseña es demasiado larga, maximo de 15 caracteres"; + return; + } + e.IsValid = true; + } +} \ No newline at end of file diff --git a/Universidad/registrar_participante.aspx b/Universidad/registrar_participante.aspx new file mode 100644 index 0000000..6d58fff --- /dev/null +++ b/Universidad/registrar_participante.aspx @@ -0,0 +1,71 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/base_page.master" AutoEventWireup="true" CodeFile="registrar_participante.aspx.cs" Inherits="registrar_participante" %> + + + + + + Nuevo Participante + + + + + +

Nuevo Participante

+
+ + + + +
+
+ + + +
+
+ + + +
+
+ + + + +
+ + +
+ + + + +
+
+ + + +
+
+ + + + +
+ +
+ + + + diff --git a/Universidad/registrar_participante.aspx.cs b/Universidad/registrar_participante.aspx.cs new file mode 100644 index 0000000..8e8f268 --- /dev/null +++ b/Universidad/registrar_participante.aspx.cs @@ -0,0 +1,124 @@ +using DAL; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +public partial class registrar_participante : System.Web.UI.Page +{ + protected void Page_Load(object sender, EventArgs e) + { + if (!IsPostBack) + { + FillUniversidades(); + FillSeminarios(); + inscripcion_box.Text = DateTime.Today.ToString("yyyy-MM-dd"); + } + } + + private void FillUniversidades() + { + Entities entities = new Entities(); + var universidades = from u in entities.Universidades select u; + universidad_select.DataSource = universidades.ToList(); + universidad_select.DataTextField = "nombre"; + universidad_select.DataValueField = "id"; + universidad_select.DataBind(); + universidad_select.Items.Insert(0, "Seleccione una Universidad"); + } + + private void FillSeminarios() + { + Entities entities = new Entities(); + var seminarios = from s in entities.Seminarios select s; + seminario_select.DataSource = seminarios.ToList(); + seminario_select.DataTextField = "nombre"; + seminario_select.DataValueField = "id"; + seminario_select.DataBind(); + seminario_select.Items.Insert(0, "Seleccione un Seminario"); + } + + protected void IndexChangedUniversidad(object sender, EventArgs e) + { + if (universidad_select.SelectedIndex > 0) + { + var id = int.Parse(universidad_select.SelectedValue); + Entities entities = new Entities(); + var carreras = from c in entities.Carreras where c.idUniversidad == id select c; + carrera_select.DataSource = carreras.ToList(); + carrera_select.DataTextField = "nombre"; + carrera_select.DataValueField = "id"; + carrera_select.DataBind(); + carrera_select.Items.Insert(0, "Seleccione una Carrera"); + } + } + + protected void OnRegistrarClick(object sender, EventArgs e) + { + if(Page.IsValid) + { + Entities entities = new Entities(); + Participante participante = new Participante(); + participante.nombre = nombre_box.Text; + participante.fechaInscripcion = DateTime.Parse(inscripcion_box.Text); + participante.pga = double.Parse(pga_box.Text); + participante.idCarrera = int.Parse(carrera_select.SelectedValue); + participante.idSeminario = int.Parse(seminario_select.SelectedValue); + entities.Participantes.Add(participante); + entities.SaveChanges(); + + Response.Redirect("/index.aspx"); + } + } + + protected void ValidateNombre(object source, ServerValidateEventArgs args) + { + if (nombre_box.Text.Trim().Length > 80) + { + args.IsValid = false; + nombre_validator.Text = "El nombre es muy largo, maximo de 80 caracteres"; + return; + } + + args.IsValid = true; + } + + protected void ValidateUniversidad(object source, ServerValidateEventArgs args) + { + if (universidad_select.SelectedIndex == 0) + { + args.IsValid = false; + universidad_validator.Text = "Porfavor seleccionar una universidad"; + return; + } + + args.IsValid = true; + } + + protected void ValidateCarrera(object source, ServerValidateEventArgs args) + { + if (carrera_select.SelectedIndex == 0) + { + args.IsValid = false; + carrera_validator.Text = "Porfavor seleccionar una carrera"; + return; + } + + args.IsValid = true; + } + + protected void ValidateSeminario(object source, ServerValidateEventArgs args) + { + if (seminario_select.SelectedIndex == 0) + { + args.IsValid = false; + seminario_validator.Text = "Porfavor seleccionar un seminario"; + return; + } + + args.IsValid = true; + } + +} \ No newline at end of file diff --git a/Utils/PasswordHash.cs b/Utils/PasswordHash.cs new file mode 100644 index 0000000..07c2d3f --- /dev/null +++ b/Utils/PasswordHash.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace Utils +{ + public class PasswordHash + { + // No es perfecto, pero me tengo un limite de 15 caracteres en la base de datos + // y realmente no queria guardar contraseñas en texto plano + public static string Hash(string password) + { + using (SHA1Managed sha1 = new SHA1Managed()) + { + var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password)); + return Convert.ToBase64String(hash).Truncate(15); + } + } + + public static bool Compare(string password, string hashed) + { + if (password == null) return false; + if (hashed == null) return false; + + return Hash(password).Equals(hashed); + } + } +} diff --git a/Utils/Properties/AssemblyInfo.cs b/Utils/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c2f1f9a --- /dev/null +++ b/Utils/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// La información general de un ensamblado se controla mediante el siguiente +// conjunto de atributos. Cambie estos valores de atributo para modificar la información +// asociada con un ensamblado. +[assembly: AssemblyTitle("Utils")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Utils")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles +// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde +// COM, establezca el atributo ComVisible en true en este tipo. +[assembly: ComVisible(false)] + +// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. +[assembly: Guid("1f33e2d1-699b-4aca-8f42-a673d7aa5d63")] + +// La información de versión de un ensamblado consta de los cuatro valores siguientes: +// +// Versión principal +// Versión secundaria +// Número de compilación +// Revisión +// +// Puede especificar todos los valores o usar los números de compilación y de revisión predeterminados +// mediante el carácter "*", como se muestra a continuación: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Utils/Strings.cs b/Utils/Strings.cs new file mode 100644 index 0000000..ad7f1ae --- /dev/null +++ b/Utils/Strings.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Utils +{ + public static class Strings + { + public static string Truncate(this string value, int maxLength) + { + if (string.IsNullOrEmpty(value)) return value; + return value.Length <= maxLength ? value : value.Substring(0, maxLength); + } + } +} diff --git a/Utils/Utils.csproj b/Utils/Utils.csproj new file mode 100644 index 0000000..8951d88 --- /dev/null +++ b/Utils/Utils.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {1F33E2D1-699B-4ACA-8F42-A673D7AA5D63} + Library + Properties + Utils + Utils + v4.6.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file