mirror of
https://gitee.com/dotnetchina/OpenAuth.Net.git
synced 2025-08-23 13:06:48 +08:00
去掉Owin的一些代码
This commit is contained in:
parent
2f9b41b96d
commit
2a5cdd453f
72
Infrastructure/Helper/CookieHelper.cs
Normal file
72
Infrastructure/Helper/CookieHelper.cs
Normal file
@ -0,0 +1,72 @@
|
||||
// ***********************************************************************
|
||||
// Assembly : Infrastructure
|
||||
// Author : Administrator
|
||||
// Created : 09-22-2015
|
||||
//
|
||||
// ***********************************************************************
|
||||
// <copyright file="CookieHelper.cs" company="">
|
||||
// Copyright (c) . All rights reserved.
|
||||
// </copyright>
|
||||
// <summary>Cookie辅助</summary>
|
||||
// ***********************************************************************
|
||||
|
||||
using System;
|
||||
using System.Web;
|
||||
|
||||
namespace Infrastructure.Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// Cookie帮助类
|
||||
/// </summary>
|
||||
public class CookieHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
public static void WriteCookie(string strName, string strValue)
|
||||
{
|
||||
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
|
||||
if (cookie == null)
|
||||
{
|
||||
cookie = new HttpCookie(strName);
|
||||
}
|
||||
cookie.Value = strValue;
|
||||
HttpContext.Current.Response.AppendCookie(cookie);
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 写cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <param name="strValue">值</param>
|
||||
/// <param name="strValue">过期时间(分钟)</param>
|
||||
public static void WriteCookie(string strName, string strValue, int expires)
|
||||
{
|
||||
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
|
||||
if (cookie == null)
|
||||
{
|
||||
cookie = new HttpCookie(strName);
|
||||
}
|
||||
cookie.Value = strValue;
|
||||
cookie.Expires = DateTime.Now.AddMinutes(expires);
|
||||
HttpContext.Current.Response.AppendCookie(cookie);
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读cookie值
|
||||
/// </summary>
|
||||
/// <param name="strName">名称</param>
|
||||
/// <returns>cookie值</returns>
|
||||
public static string GetCookie(string strName)
|
||||
{
|
||||
if (HttpContext.Current.Request.Cookies[strName] != null)
|
||||
{
|
||||
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
55
Infrastructure/Infrastructure.csproj
Normal file
55
Infrastructure/Infrastructure.csproj
Normal file
@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Infrastructure</RootNamespace>
|
||||
<AssemblyName>Infrastructure</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Helper\CookieHelper.cs" />
|
||||
<Compile Include="Helper\SessionHelper.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
36
Infrastructure/Properties/AssemblyInfo.cs
Normal file
36
Infrastructure/Properties/AssemblyInfo.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 有关程序集的常规信息通过以下
|
||||
// 特性集控制。更改这些特性值可修改
|
||||
// 与程序集关联的信息。
|
||||
[assembly: AssemblyTitle("Infrastructure")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("Infrastructure")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// 将 ComVisible 设置为 false 使此程序集中的类型
|
||||
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
|
||||
// 则将该类型上的 ComVisible 特性设置为 true。
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
|
||||
[assembly: Guid("e953a7ce-9f0c-4aec-973c-de31e38e10e6")]
|
||||
|
||||
// 程序集的版本信息由下面四个值组成:
|
||||
//
|
||||
// 主版本
|
||||
// 次版本
|
||||
// 生成号
|
||||
// 修订号
|
||||
//
|
||||
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
|
||||
// 方法是按如下所示使用“*”:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
@ -22,7 +22,6 @@ namespace OpenAuth.App
|
||||
|
||||
user.CheckLogin(password);
|
||||
|
||||
LoginCacheApp.SetLogin(user);
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,25 +0,0 @@
|
||||
using System.Web;
|
||||
using OpenAuth.Domain;
|
||||
|
||||
namespace OpenAuth.App
|
||||
{
|
||||
public class LoginCacheApp
|
||||
{
|
||||
public static User GetLogin()
|
||||
{
|
||||
var session = HttpContext.Current.Session;
|
||||
return session["Login"] as User;
|
||||
}
|
||||
|
||||
public static void SetLogin(User loginresp)
|
||||
{
|
||||
var session = HttpContext.Current.Session;
|
||||
var login = session["Login"] as User;
|
||||
if (login != null && login.UserId == loginresp.UserId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
session["Login"] = loginresp;
|
||||
}
|
||||
}
|
||||
}
|
@ -41,7 +41,6 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="LoginApp.cs" />
|
||||
<Compile Include="LoginCacheApp.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
@ -1,38 +0,0 @@
|
||||
using Microsoft.AspNet.Identity;
|
||||
using Microsoft.Owin;
|
||||
using Microsoft.Owin.Security.Cookies;
|
||||
using Owin;
|
||||
|
||||
namespace OpenAuth.Mvc
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
// 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
|
||||
public void ConfigureAuth(IAppBuilder app)
|
||||
{
|
||||
// 使应用程序可以使用 Cookie 来存储已登录用户的信息
|
||||
app.UseCookieAuthentication(new CookieAuthenticationOptions
|
||||
{
|
||||
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
|
||||
LoginPath = new PathString("/Account/Login")
|
||||
});
|
||||
// Use a cookie to temporarily store information about a user logging in with a third party login provider
|
||||
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
|
||||
|
||||
// 取消注释以下行可允许使用第三方登录提供程序登录
|
||||
//app.UseMicrosoftAccountAuthentication(
|
||||
// clientId: "",
|
||||
// clientSecret: "");
|
||||
|
||||
//app.UseTwitterAuthentication(
|
||||
// consumerKey: "",
|
||||
// consumerSecret: "");
|
||||
|
||||
//app.UseFacebookAuthentication(
|
||||
// appId: "",
|
||||
// appSecret: "");
|
||||
|
||||
//app.UseGoogleAuthentication();
|
||||
}
|
||||
}
|
||||
}
|
@ -6,6 +6,7 @@ using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
using Infrastructure.Helper;
|
||||
using Newtonsoft.Json;
|
||||
using OpenAuth.App;
|
||||
using OpenAuth.Domain;
|
||||
@ -16,11 +17,13 @@ namespace OpenAuth.Mvc.Controllers
|
||||
[Authorize]
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private LoginApp _loginApp;
|
||||
private IUserRepository _userRepository;
|
||||
|
||||
public AccountController(IUserRepository repository)
|
||||
{
|
||||
_userRepository = repository;
|
||||
_loginApp = new LoginApp(_userRepository);
|
||||
}
|
||||
//
|
||||
// GET: /Account/Login
|
||||
@ -44,7 +47,7 @@ namespace OpenAuth.Mvc.Controllers
|
||||
var user = new User {Account = "admin"};
|
||||
if (user != null)
|
||||
{
|
||||
await SignInAsync(user, model.RememberMe);
|
||||
|
||||
return RedirectToLocal(returnUrl);
|
||||
}
|
||||
else
|
||||
@ -61,7 +64,7 @@ namespace OpenAuth.Mvc.Controllers
|
||||
// POST: /Account/LogOff
|
||||
public ActionResult LogOff()
|
||||
{
|
||||
AuthenticationManager.SignOut();
|
||||
SessionHelper.Clear();
|
||||
return RedirectToAction("Login", "Account");
|
||||
}
|
||||
|
||||
@ -74,36 +77,7 @@ namespace OpenAuth.Mvc.Controllers
|
||||
return JsonConvert.SerializeObject(_userRepository.LoadUsers());
|
||||
}
|
||||
|
||||
#region 帮助程序
|
||||
|
||||
private IAuthenticationManager AuthenticationManager
|
||||
{
|
||||
get
|
||||
{
|
||||
return HttpContext.GetOwinContext().Authentication;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// sign information as an asynchronous operation.
|
||||
/// </summary>
|
||||
/// <param name="user">用户</param>
|
||||
/// <param name="isPersistent">Remember me?</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task SignInAsync(User user, bool isPersistent)
|
||||
{
|
||||
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.Name, user.Account),
|
||||
new Claim(ClaimTypes.Role, "Administrator"),
|
||||
new Claim(ClaimTypes.NameIdentifier, "7c301fe4-099e-46f9-bdb8-e922d73a8031"),
|
||||
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
|
||||
"ASP.NET Identity")
|
||||
};
|
||||
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
|
||||
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
|
||||
}
|
||||
|
||||
private ActionResult RedirectToLocal(string returnUrl)
|
||||
{
|
||||
@ -117,6 +91,5 @@ namespace OpenAuth.Mvc.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
#endregion 帮助程序
|
||||
}
|
||||
}
|
35
OpenAuth.Mvc/Controllers/BaseController.cs
Normal file
35
OpenAuth.Mvc/Controllers/BaseController.cs
Normal file
@ -0,0 +1,35 @@
|
||||
// ***********************************************************************
|
||||
// Assembly : OpenAuth.Mvc
|
||||
// Author : Administrator
|
||||
// Created : 09-22-2015
|
||||
//
|
||||
// Last Modified By : Administrator
|
||||
// Last Modified On : 09-22-2015
|
||||
// ***********************************************************************
|
||||
// <copyright file="BaseController.cs" company="">
|
||||
// Copyright (c) . All rights reserved.
|
||||
// </copyright>
|
||||
// <summary>基础控制器,设置权限</summary>
|
||||
// ***********************************************************************
|
||||
|
||||
using System.Web.Mvc;
|
||||
using Infrastructure.Helper;
|
||||
using OpenAuth.Domain;
|
||||
|
||||
namespace OpenAuth.Mvc.Controllers
|
||||
{
|
||||
public class BaseController : Controller
|
||||
{
|
||||
protected override void OnActionExecuting(ActionExecutingContext filterContext)
|
||||
{
|
||||
base.OnActionExecuting(filterContext);
|
||||
|
||||
#region 当Session过期自动跳出登录画面
|
||||
if (SessionHelper.GetSessionUser<User>() == null)
|
||||
{
|
||||
Response.Redirect("~/Account/Login");
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
@ -6,7 +6,7 @@ using System.Web.Mvc;
|
||||
|
||||
namespace OpenAuth.Mvc.Controllers
|
||||
{
|
||||
public class HomeController : Controller
|
||||
public class HomeController : BaseController
|
||||
{
|
||||
public ActionResult Index()
|
||||
{
|
||||
|
@ -163,15 +163,14 @@
|
||||
<Compile Include="App_Start\BundleConfig.cs" />
|
||||
<Compile Include="App_Start\FilterConfig.cs" />
|
||||
<Compile Include="App_Start\RouteConfig.cs" />
|
||||
<Compile Include="App_Start\Startup.Auth.cs" />
|
||||
<Compile Include="Controllers\AccountController.cs" />
|
||||
<Compile Include="Controllers\BaseController.cs" />
|
||||
<Compile Include="Controllers\HomeController.cs" />
|
||||
<Compile Include="Global.asax.cs">
|
||||
<DependentUpon>Global.asax</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Models\AccountViewModels.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Startup.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="assets\avatars\avatar.png" />
|
||||
@ -272,11 +271,16 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="App_Data\" />
|
||||
<Folder Include="Views\Base\" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj">
|
||||
<Project>{5feaec9a-4f1e-4ee7-b377-9db1b0870dac}</Project>
|
||||
<Name>Infrastructure</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\OpenAuth.App\OpenAuth.App.csproj">
|
||||
<Project>{0bbf2d65-fffd-4272-b138-8ea4fb6fec48}</Project>
|
||||
<Name>OpenAuth.App</Name>
|
||||
|
@ -1,14 +0,0 @@
|
||||
using Microsoft.Owin;
|
||||
using Owin;
|
||||
|
||||
[assembly: OwinStartupAttribute(typeof(OpenAuth.Mvc.Startup))]
|
||||
namespace OpenAuth.Mvc
|
||||
{
|
||||
public partial class Startup
|
||||
{
|
||||
public void Configuration(IAppBuilder app)
|
||||
{
|
||||
ConfigureAuth(app);
|
||||
}
|
||||
}
|
||||
}
|
30
OpenAuth.Mvc/Web.Debug.config
Normal file
30
OpenAuth.Mvc/Web.Debug.config
Normal file
@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- 有关使用 Web.config 转换的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301874 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
在以下示例中, "SetAttributes" 转换将 "connectionString"
|
||||
的值更改为仅在 "Match" 定位器找到具有值 "MyDB" 的
|
||||
属性 "name" 时使用 "ReleaseSQLServer"。
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<!--
|
||||
在以下示例中,"Replace" 转换将替换 Web.config 文件的
|
||||
整个 <customErrors> 节。
|
||||
请注意,由于在 <system.web> 节点下只有一个
|
||||
customErrors 节,因此无需使用 "xdt:Locator" 属性。
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
31
OpenAuth.Mvc/Web.Release.config
Normal file
31
OpenAuth.Mvc/Web.Release.config
Normal file
@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- 有关使用 Web.config 转换的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301874 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
在以下示例中, "SetAttributes" 转换将 "connectionString"
|
||||
的值更改为仅在 "Match" 定位器找到具有值 "MyDB" 的
|
||||
属性 "name" 时使用 "ReleaseSQLServer"。
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<compilation xdt:Transform="RemoveAttributes(debug)" />
|
||||
<!--
|
||||
在以下示例中,"Replace" 转换将替换 Web.config 文件的
|
||||
整个 <customErrors> 节。
|
||||
请注意,由于在 <system.web> 节点下只有一个
|
||||
customErrors 节,因此无需使用 "xdt:Locator" 属性。
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
@ -0,0 +1,48 @@
|
||||
<#@ template hostspecific="true" language="C#" #>
|
||||
<#@ include file="EF.Utility.CS.ttinclude" #><#@
|
||||
output extension=".cs" #><#
|
||||
|
||||
var efHost = (EfTextTemplateHost)Host;
|
||||
var code = new CodeGenerationTools(this);
|
||||
#>
|
||||
using System.Data.Entity;
|
||||
using System.Data.Entity.Infrastructure;
|
||||
using OpenAuth.Domain;
|
||||
using <#= code.EscapeNamespace(efHost.MappingNamespace) #>;
|
||||
|
||||
namespace <#= code.EscapeNamespace(efHost.Namespace) #>
|
||||
{
|
||||
public partial class <#= efHost.EntityContainer.Name #> : DbContext
|
||||
{
|
||||
static <#= efHost.EntityContainer.Name #>()
|
||||
{
|
||||
Database.SetInitializer<<#= efHost.EntityContainer.Name #>>(null);
|
||||
}
|
||||
|
||||
public <#= efHost.EntityContainer.Name #>()
|
||||
: base("Name=<#= efHost.EntityContainer.Name #>")
|
||||
{
|
||||
}
|
||||
|
||||
<#
|
||||
foreach (var set in efHost.EntityContainer.BaseEntitySets.OfType<EntitySet>())
|
||||
{
|
||||
#>
|
||||
public DbSet<<#= set.ElementType.Name #>> <#= set.Name #> { get; set; }
|
||||
<#
|
||||
}
|
||||
#>
|
||||
|
||||
protected override void OnModelCreating(DbModelBuilder modelBuilder)
|
||||
{
|
||||
<#
|
||||
foreach (var set in efHost.EntityContainer.BaseEntitySets.OfType<EntitySet>())
|
||||
{
|
||||
#>
|
||||
modelBuilder.Configurations.Add(new <#= set.ElementType.Name #>Map());
|
||||
<#
|
||||
}
|
||||
#>
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,75 @@
|
||||
<#@ template hostspecific="true" language="C#" #>
|
||||
<#@ include file="EF.Utility.CS.ttinclude" #><#@
|
||||
output extension=".cs" #><#
|
||||
|
||||
var efHost = (EfTextTemplateHost)Host;
|
||||
var code = new CodeGenerationTools(this);
|
||||
#>
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace OpenAuth.Domain
|
||||
{
|
||||
public partial class <#= efHost.EntityType.Name #>
|
||||
{
|
||||
<#
|
||||
var collectionNavigations = efHost.EntityType.NavigationProperties.Where(
|
||||
np => np.DeclaringType == efHost.EntityType
|
||||
&& np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
|
||||
|
||||
// Add a ctor to initialize any collections
|
||||
if (collectionNavigations.Any())
|
||||
{
|
||||
#>
|
||||
public <#= code.Escape(efHost.EntityType) #>()
|
||||
{
|
||||
<#
|
||||
foreach (var navProperty in collectionNavigations)
|
||||
{
|
||||
#>
|
||||
this.<#= code.Escape(navProperty) #> = new List<<#= code.Escape(navProperty.ToEndMember.GetEntityType()) #>>();
|
||||
<#
|
||||
}
|
||||
#>
|
||||
}
|
||||
|
||||
<#
|
||||
}
|
||||
|
||||
foreach (var property in efHost.EntityType.Properties)
|
||||
{
|
||||
var typeUsage = code.Escape(property.TypeUsage);
|
||||
|
||||
// Fix-up spatial types for EF6
|
||||
if (efHost.EntityFrameworkVersion >= new Version(6, 0)
|
||||
&& typeUsage.StartsWith("System.Data.Spatial."))
|
||||
{
|
||||
typeUsage = typeUsage.Replace(
|
||||
"System.Data.Spatial.",
|
||||
"System.Data.Entity.Spatial.");
|
||||
}
|
||||
|
||||
|
||||
#>
|
||||
<#= Accessibility.ForProperty(property) #> <#= typeUsage #> <#= code.Escape(property) #> { get; set; }
|
||||
<#
|
||||
}
|
||||
|
||||
foreach (var navProperty in efHost.EntityType.NavigationProperties.Where(np => np.DeclaringType == efHost.EntityType))
|
||||
{
|
||||
if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
|
||||
{
|
||||
#>
|
||||
public virtual ICollection<<#= code.Escape(navProperty.ToEndMember.GetEntityType()) #>> <#= code.Escape(navProperty) #> { get; set; }
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
public virtual <#= code.Escape(navProperty.ToEndMember.GetEntityType()) #> <#= code.Escape(navProperty) #> { get; set; }
|
||||
<#
|
||||
}
|
||||
}
|
||||
#>
|
||||
}
|
||||
}
|
@ -0,0 +1,269 @@
|
||||
<#
|
||||
// Simplifying assumptions based on reverse engineer rules
|
||||
// - No complex types
|
||||
// - One entity container
|
||||
// - No inheritance
|
||||
// - Always have two navigation properties
|
||||
// - All associations expose FKs (except many:many)
|
||||
#>
|
||||
<#@ template hostspecific="true" language="C#" #>
|
||||
<#@ include file="EF.Utility.CS.ttinclude" #><#@
|
||||
output extension=".cs" #><#
|
||||
|
||||
var efHost = (EfTextTemplateHost)Host;
|
||||
var code = new CodeGenerationTools(this);
|
||||
|
||||
if (efHost.EntityFrameworkVersion >= new Version(4, 4))
|
||||
{
|
||||
#>
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
<#
|
||||
}
|
||||
#>
|
||||
using System.Data.Entity.ModelConfiguration;
|
||||
using OpenAuth.Domain;
|
||||
|
||||
namespace <#= code.EscapeNamespace(efHost.Namespace) #>
|
||||
{
|
||||
public class <#= efHost.EntityType.Name #>Map : EntityTypeConfiguration<<#= efHost.EntityType.Name #>>
|
||||
{
|
||||
public <#= efHost.EntityType.Name #>Map()
|
||||
{
|
||||
// Primary Key
|
||||
<#
|
||||
if (efHost.EntityType.KeyMembers.Count() == 1)
|
||||
{
|
||||
#>
|
||||
this.HasKey(t => t.<#= efHost.EntityType.KeyMembers.Single().Name #>);
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
this.HasKey(t => new { <#= string.Join(", ", efHost.EntityType.KeyMembers.Select(m => "t." + m.Name)) #> });
|
||||
<#
|
||||
}
|
||||
#>
|
||||
|
||||
// Properties
|
||||
<#
|
||||
foreach (var prop in efHost.EntityType.Properties)
|
||||
{
|
||||
var type = (PrimitiveType)prop.TypeUsage.EdmType;
|
||||
var isKey = efHost.EntityType.KeyMembers.Contains(prop);
|
||||
var storeProp = efHost.PropertyToColumnMappings[prop];
|
||||
var sgpFacet = storeProp.TypeUsage.Facets.SingleOrDefault(f => f.Name == "StoreGeneratedPattern");
|
||||
var storeGeneratedPattern = sgpFacet == null
|
||||
? StoreGeneratedPattern.None
|
||||
: (StoreGeneratedPattern)sgpFacet.Value;
|
||||
|
||||
var configLines = new List<string>();
|
||||
|
||||
if (type.ClrEquivalentType == typeof(int)
|
||||
|| type.ClrEquivalentType == typeof(decimal)
|
||||
|| type.ClrEquivalentType == typeof(short)
|
||||
|| type.ClrEquivalentType == typeof(long))
|
||||
{
|
||||
if (isKey && storeGeneratedPattern != StoreGeneratedPattern.Identity)
|
||||
{
|
||||
configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)");
|
||||
}
|
||||
else if ((!isKey || efHost.EntityType.KeyMembers.Count > 1) && storeGeneratedPattern == StoreGeneratedPattern.Identity)
|
||||
{
|
||||
configLines.Add(".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)");
|
||||
}
|
||||
}
|
||||
|
||||
if (type.ClrEquivalentType == typeof(string)
|
||||
|| type.ClrEquivalentType == typeof(byte[]))
|
||||
{
|
||||
if (!prop.Nullable)
|
||||
{
|
||||
configLines.Add(".IsRequired()");
|
||||
}
|
||||
|
||||
var unicodeFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "IsUnicode");
|
||||
if(unicodeFacet != null && !(bool)unicodeFacet.Value)
|
||||
{
|
||||
configLines.Add(".IsUnicode(false)");
|
||||
}
|
||||
|
||||
var fixedLengthFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "FixedLength");
|
||||
if (fixedLengthFacet != null && (bool)fixedLengthFacet.Value)
|
||||
{
|
||||
configLines.Add(".IsFixedLength()");
|
||||
}
|
||||
|
||||
var maxLengthFacet = (Facet)prop.TypeUsage.Facets.SingleOrDefault(f => f.Name == "MaxLength");
|
||||
if (maxLengthFacet != null && !maxLengthFacet.IsUnbounded)
|
||||
{
|
||||
configLines.Add(string.Format(".HasMaxLength({0})", maxLengthFacet.Value));
|
||||
|
||||
if (storeGeneratedPattern == StoreGeneratedPattern.Computed
|
||||
&& type.ClrEquivalentType == typeof(byte[])
|
||||
&& (int)maxLengthFacet.Value == 8)
|
||||
{
|
||||
configLines.Add(".IsRowVersion()");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(configLines.Any())
|
||||
{
|
||||
#>
|
||||
this.Property(t => t.<#= prop.Name #>)
|
||||
<#= string.Join("\r\n ", configLines) #>;
|
||||
|
||||
<#
|
||||
}
|
||||
}
|
||||
|
||||
var tableSet = efHost.TableSet;
|
||||
var tableName = (string)tableSet.MetadataProperties["Table"].Value
|
||||
?? tableSet.Name;
|
||||
var schemaName = (string)tableSet.MetadataProperties["Schema"].Value;
|
||||
#>
|
||||
// Table & Column Mappings
|
||||
<#
|
||||
if (schemaName == "dbo" || string.IsNullOrWhiteSpace(schemaName))
|
||||
{
|
||||
#>
|
||||
this.ToTable("<#= tableName #>");
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
this.ToTable("<#= tableName #>", "<#= schemaName #>");
|
||||
<#
|
||||
}
|
||||
|
||||
foreach (var property in efHost.EntityType.Properties)
|
||||
{
|
||||
#>
|
||||
this.Property(t => t.<#= property.Name #>).HasColumnName("<#= efHost.PropertyToColumnMappings[property].Name #>");
|
||||
<#
|
||||
}
|
||||
|
||||
// Find m:m relationshipsto configure
|
||||
var manyManyRelationships = efHost.EntityType.NavigationProperties
|
||||
.Where(np => np.DeclaringType == efHost.EntityType
|
||||
&& np.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
|
||||
&& np.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many
|
||||
&& np.RelationshipType.RelationshipEndMembers.First() == np.FromEndMember); // <- ensures we only configure from one end
|
||||
|
||||
// Find FK relationships that this entity is the dependent of
|
||||
var fkRelationships = efHost.EntityType.NavigationProperties
|
||||
.Where(np => np.DeclaringType == efHost.EntityType
|
||||
&& ((AssociationType)np.RelationshipType).IsForeignKey
|
||||
&& ((AssociationType)np.RelationshipType).ReferentialConstraints.Single().ToRole == np.FromEndMember);
|
||||
|
||||
if(manyManyRelationships.Any() || fkRelationships.Any())
|
||||
{
|
||||
#>
|
||||
|
||||
// Relationships
|
||||
<#
|
||||
foreach (var navProperty in manyManyRelationships)
|
||||
{
|
||||
var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single();
|
||||
var association = (AssociationType)navProperty.RelationshipType;
|
||||
var mapping = efHost.ManyToManyMappings[association];
|
||||
var item1 = mapping.Item1;
|
||||
var mappingTableName = (string)mapping.Item1.MetadataProperties["Table"].Value
|
||||
?? item1.Name;
|
||||
var mappingSchemaName = (string)item1.MetadataProperties["Schema"].Value;
|
||||
|
||||
// Need to ensure that FKs are decalred in the same order as the PK properties on each principal type
|
||||
var leftType = (EntityType)navProperty.DeclaringType;
|
||||
var leftKeyMappings = mapping.Item2[navProperty.FromEndMember];
|
||||
var leftColumns = string.Join(", ", leftType.KeyMembers.Select(m => "\"" + leftKeyMappings[m] + "\""));
|
||||
var rightType = (EntityType)otherNavProperty.DeclaringType;
|
||||
var rightKeyMappings = mapping.Item2[otherNavProperty.FromEndMember];
|
||||
var rightColumns = string.Join(", ", rightType.KeyMembers.Select(m => "\"" + rightKeyMappings[m] + "\""));
|
||||
#>
|
||||
this.HasMany(t => t.<#= code.Escape(navProperty) #>)
|
||||
.WithMany(t => t.<#= code.Escape(otherNavProperty) #>)
|
||||
.Map(m =>
|
||||
{
|
||||
<#
|
||||
if (mappingSchemaName == "dbo" || string.IsNullOrWhiteSpace(mappingSchemaName))
|
||||
{
|
||||
#>
|
||||
m.ToTable("<#= mappingTableName #>");
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
m.ToTable("<#= mappingTableName #>", "<#= mappingSchemaName #>");
|
||||
<#
|
||||
}
|
||||
#>
|
||||
m.MapLeftKey(<#= leftColumns #>);
|
||||
m.MapRightKey(<#= rightColumns #>);
|
||||
});
|
||||
|
||||
<#
|
||||
}
|
||||
|
||||
foreach (var navProperty in fkRelationships)
|
||||
{
|
||||
var otherNavProperty = navProperty.ToEndMember.GetEntityType().NavigationProperties.Where(n => n.RelationshipType == navProperty.RelationshipType && n != navProperty).Single();
|
||||
var association = (AssociationType)navProperty.RelationshipType;
|
||||
|
||||
if (navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
|
||||
{
|
||||
#>
|
||||
this.HasRequired(t => t.<#= code.Escape(navProperty) #>)
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
this.HasOptional(t => t.<#= code.Escape(navProperty) #>)
|
||||
<#
|
||||
}
|
||||
|
||||
if(navProperty.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
|
||||
{
|
||||
#>
|
||||
.WithMany(t => t.<#= code.Escape(otherNavProperty) #>)
|
||||
<#
|
||||
if(association.ReferentialConstraints.Single().ToProperties.Count == 1)
|
||||
{
|
||||
#>
|
||||
.HasForeignKey(d => d.<#= association.ReferentialConstraints.Single().ToProperties.Single().Name #>);
|
||||
<#
|
||||
}
|
||||
else
|
||||
{
|
||||
#>
|
||||
.HasForeignKey(d => new { <#= string.Join(", ", association.ReferentialConstraints.Single().ToProperties.Select(p => "d." + p.Name)) #> });
|
||||
<#
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// NOTE: We can assume that this is a required:optional relationship
|
||||
// as EDMGen will never create an optional:optional relationship
|
||||
// because everything is one:many except PK-PK relationships which must be required
|
||||
#>
|
||||
.WithOptional(t => t.<#= code.Escape(otherNavProperty) #>);
|
||||
<#
|
||||
}
|
||||
}
|
||||
#>
|
||||
|
||||
<#
|
||||
}
|
||||
#>
|
||||
}
|
||||
}
|
||||
}
|
@ -17,12 +17,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAuth.Domain", "OpenAuth
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAuth.UnitTest", "OpenAuth.UnitTest\OpenAuth.UnitTest.csproj", "{2E6B5B73-7757-43F0-8AC8-3030F7C191B8}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4 Repository(仓储)", "4 Repository(仓储)", "{7A38939E-FC9B-44A9-BD3D-E0CE438624E6}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4 功能适配层", "4 功能适配层", "{7A38939E-FC9B-44A9-BD3D-E0CE438624E6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAuth.Repository", "OpenAuth.Repository\OpenAuth.Repository.csproj", "{E8DF8DEA-E2CF-4BDB-8F4F-3F8205B0E03A}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenAuth.Mvc", "OpenAuth.Mvc\OpenAuth.Mvc.csproj", "{2A9D9687-1822-41CF-B7DF-819BFC0F8FE9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure", "Infrastructure\Infrastructure.csproj", "{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -49,6 +51,10 @@ Global
|
||||
{2A9D9687-1822-41CF-B7DF-819BFC0F8FE9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2A9D9687-1822-41CF-B7DF-819BFC0F8FE9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2A9D9687-1822-41CF-B7DF-819BFC0F8FE9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -59,6 +65,7 @@ Global
|
||||
{6108DA8E-92A1-4ABE-B9F5-26D64D55CA2C} = {7618C0B1-D556-40C2-B2DD-CCECDC4E46B6}
|
||||
{2E6B5B73-7757-43F0-8AC8-3030F7C191B8} = {C59DF46D-7815-462B-9FFF-750B2120B75B}
|
||||
{E8DF8DEA-E2CF-4BDB-8F4F-3F8205B0E03A} = {7A38939E-FC9B-44A9-BD3D-E0CE438624E6}
|
||||
{5FEAEC9A-4F1E-4EE7-B377-9DB1B0870DAC} = {7A38939E-FC9B-44A9-BD3D-E0CE438624E6}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
EnterpriseLibraryConfigurationToolBinariesPath = packages\Unity.2.1.505.2\lib\NET35
|
||||
|
Loading…
Reference in New Issue
Block a user