初始化项目

This commit is contained in:
2025-11-20 13:11:05 +08:00
commit d5edc62c08
2412 changed files with 2201918 additions and 0 deletions

View File

@@ -0,0 +1,191 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{56438F1C-BA3A-4272-964E-C6739AE0B4EC}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AUTS.Services</RootNamespace>
<AssemblyName>AUTS.Services</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<TargetFrameworkProfile />
</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="BouncyCastle.Crypto, Version=1.9.0.0, Culture=neutral, PublicKeyToken=0e99375e54769942, processorArchitecture=MSIL">
<HintPath>..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="Google.Protobuf, Version=3.21.9.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
<HintPath>..\packages\Google.Protobuf.3.21.9\lib\net45\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="K4os.Compression.LZ4, Version=1.3.5.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Compression.LZ4.1.3.5\lib\net462\K4os.Compression.LZ4.dll</HintPath>
</Reference>
<Reference Include="K4os.Compression.LZ4.Streams, Version=1.3.5.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Compression.LZ4.Streams.1.3.5\lib\net462\K4os.Compression.LZ4.Streams.dll</HintPath>
</Reference>
<Reference Include="K4os.Hash.xxHash, Version=1.0.8.0, Culture=neutral, PublicKeyToken=32cd54395057cec3, processorArchitecture=MSIL">
<HintPath>..\packages\K4os.Hash.xxHash.1.0.8\lib\net462\K4os.Hash.xxHash.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
</Reference>
<Reference Include="MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.6.9.12\lib\net45\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="MySql.Data.Entity.EF6, Version=6.9.11.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.Entity.6.9.11\lib\net45\MySql.Data.Entity.EF6.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.11.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SqlSugar, Version=5.1.2.7, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\SqlSugar.5.1.2.7\lib\SqlSugar.dll</HintPath>
</Reference>
<Reference Include="StackExchange.Redis, Version=1.2.6.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\StackExchange.Redis.1.2.6\lib\net46\StackExchange.Redis.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Pipelines, Version=5.0.0.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.Pipelines.5.0.2\lib\net461\System.IO.Pipelines.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.4\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Cache\BaseCacheHelp.cs" />
<Compile Include="Cache\CacheHelp.cs" />
<Compile Include="DBUtility\CommandInfo.cs" />
<Compile Include="DBUtility\Common\DALHelper.cs" />
<Compile Include="DBUtility\Common\DbHelperMySQL.cs" />
<Compile Include="DBUtility\Custom\DALHelperCustom.cs" />
<Compile Include="DBUtility\Custom\DbHelperMySqlCustom.cs" />
<Compile Include="Enums\CacheTimeType.cs" />
<Compile Include="Enums\LoginInfoType.cs" />
<Compile Include="Enums\OperationLevel.cs" />
<Compile Include="Enums\OrderStatus.cs" />
<Compile Include="Enums\Root.cs" />
<Compile Include="Enums\ShortStringVersion.cs" />
<Compile Include="Enums\SnType.cs" />
<Compile Include="Enums\StationType.cs" />
<Compile Include="Extensions\CacheExtensions.cs" />
<Compile Include="Extensions\CookieExtensions.cs" />
<Compile Include="Extensions\CustomException.cs" />
<Compile Include="Extensions\EnumerableExtensions.cs" />
<Compile Include="Extensions\LinqExtensions.cs" />
<Compile Include="Extensions\ModelExtensions.cs" />
<Compile Include="Extensions\SafeInputExtensions.cs" />
<Compile Include="Extensions\StringExtensions.cs" />
<Compile Include="Extensions\TimeExtensions.cs" />
<Compile Include="Manager\AutsChart.cs" />
<Compile Include="Manager\Capacity.cs" />
<Compile Include="Manager\ChartsDatas.cs" />
<Compile Include="Manager\Logs.cs" />
<Compile Include="Manager\Orders.cs" />
<Compile Include="Manager\PPlans.cs" />
<Compile Include="Manager\SqlConnect.cs" />
<Compile Include="Manager\TestLogs.cs" />
<Compile Include="Manager\UserOperationLog.cs" />
<Compile Include="Manager\Users.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Tool\DateTimeDiff.cs" />
<Compile Include="Tool\ModelHelper.cs" />
<Compile Include="Tool\System\ComputerHelp.cs" />
<Compile Include="Tool\System\ConfigHelper.cs" />
<Compile Include="Tool\System\EnumHelper.cs" />
<Compile Include="Tool\System\IPHelper.cs" />
<Compile Include="Tool\RedisHelper.cs" />
<Compile Include="Tool\System\StringHelp.cs" />
<Compile Include="UDP\DevManageHelp.cs" />
<Compile Include="UDP\UDPHelp.cs" />
<Compile Include="UserLoginHelper.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AUTS.Domain.ViewModels\AUTS.Domain.ViewModels.csproj">
<Project>{be790400-c1ee-4d97-b3f1-604f6831e5e7}</Project>
<Name>AUTS.Domain.ViewModels</Name>
</ProjectReference>
<ProjectReference Include="..\AUTS.Domain\AUTS.Domain.csproj">
<Project>{709aa98f-388f-44dd-b64b-ad44e695c34c}</Project>
<Name>AUTS.Domain</Name>
</ProjectReference>
<ProjectReference Include="..\AUTS.Log4Net\AUTS.Log4Net.csproj">
<Project>{5500f9dd-89d9-40f3-b62f-90c6b633d55a}</Project>
<Name>AUTS.Log4Net</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

51
AUTS.Services/App.config Normal file
View File

@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.11.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.9.12.0" newVersion="6.9.12.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Google.Protobuf" publicKeyToken="a7d26565bac4d604" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.21.9.0" newVersion="3.21.9.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="K4os.Compression.LZ4.Streams" publicKeyToken="2186fa9121ef231d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.3.5.0" newVersion="1.3.5.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup><system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data></configuration>

View File

@@ -0,0 +1,271 @@
using AUTS.Services.Enums;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Cache
{
public class BaseCacheHelp : BaseCacheHelpRedis
{
}
#region -MVC
/// <summary>
/// 缓存管理-MVC内核
/// </summary>
public abstract class BaseCacheHelpMVC
{
/// <summary>
/// 获取设置-string
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="setAcrion">委托方法</param>
/// <param name="key">缓存key</param>
/// <param name="cacheTimeType">超时设置</param>
/// <param name="cacheTime">超时设置</param>
/// <returns>返回泛型实例</returns>
public static T GetCache<T>(string key, Func<T> setAcrion, CacheTimeType? cacheTimeType = null, int? cacheTime = null)
{
if (CacheExtensions.CheckCache(key))
{
return CacheExtensions.GetCache<T>(key);
}
else
{
T model = setAcrion();
if (model != null)
{
if (cacheTimeType != null && cacheTime != null)
{
CacheExtensions.SetCache(key, model, (CacheTimeType)cacheTimeType, (int)cacheTime);
}
}
return model;
}
}
/// <summary>
/// 设置参数 string
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="setAcrion">委托方法</param>
/// <param name="key">缓存key</param>
/// <param name="cacheTimeType">超时设置</param>
/// <param name="cacheTime">超时设置</param>
public static void SetCache<T>(string key, Func<T> setAcrion, CacheTimeType? cacheTimeType = null, int? cacheTime = null)
{
T model = setAcrion();
if (model != null)
{
if (cacheTimeType != null && cacheTime != null)
{
CacheExtensions.SetCache(key, model, (CacheTimeType)cacheTimeType, (int)cacheTime);
}
}
}
/// <summary>
/// 获取 string 失败返回 null
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <returns>返回泛型实例</returns>
public static T GetVaue<T>(string key)
{
if (CacheExtensions.CheckCache(key))
{
return CacheExtensions.GetCache<T>(key);
}
else
{
return default(T);
}
}
/// <summary>
/// 清除缓存
/// </summary>
/// <param name="key">缓存key</param>
public static void ClearCache(string key)
{
if (CacheExtensions.CheckCache(key))
{
CacheExtensions.ClearCache(key);
}
}
#region
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="key"></param>
/// <param name="action"></param>
/// <returns></returns>
public static T GetCacheHelp<T>(string key, Func<T> action)
{
if (CacheExtensions.CheckCache(key))
{
return CacheExtensions.GetCache<T>(key);
}
else
{
var model = action();
CacheExtensions.SetCache(key, model);
return model;
}
}
#endregion
}
#endregion
#region -Redis Redis-string
/// <summary>
/// 缓存管理-Redis内核 基于Redis-string
/// </summary>
public abstract class BaseCacheHelpRedis
{
/// <summary>
/// 获取设置-string
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="setAcrion">委托方法</param>
/// <param name="key">缓存key</param>
/// <param name="expiry">超时设置</param>
/// <returns>返回泛型实例</returns>
public static T GetCache<T>(string key, Func<T> setAcrion, TimeSpan? expiry = default(TimeSpan?))
{
if (RedisHelper.CheckKey(key))
{
return RedisHelper.StringGet<T>(key);
}
else
{
T model = setAcrion();
if (model != null)
{
RedisHelper.StringSet(key, model, expiry);
}
return model;
}
}
/// <summary>
/// 设置参数 string
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="setAcrion">委托方法</param>
/// <param name="key">缓存key</param>
/// <param name="expiry">超时设置</param>
public static void SetCache<T>(string key, Func<T> setAcrion, TimeSpan? expiry = default(TimeSpan?))
{
T model = setAcrion();
if (model != null)
{
RedisHelper.StringSet(key, model, expiry);
}
}
/// <summary>
/// 获取 string 失败返回 null
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <returns>返回泛型实例</returns>
public static T GetVaue<T>(string key)
{
if (RedisHelper.CheckKey(key))
{
return RedisHelper.StringGet<T>(key);
}
else
{
return default(T);
}
}
/// <summary>
/// 清除缓存
/// </summary>
/// <param name="key">缓存key</param>
public static void ClearCache(string key)
{
if (RedisHelper.CheckKey(key))
{
RedisHelper.RemoveKey(key);
}
}
/// <summary>
/// 获取哈希缓存,没有则添加
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <param name="sid">键</param>
/// <param name="setAcrion">委托方法</param>
/// <returns></returns>
public static T GetHashCache<T>(string key, string sid, Func<T> setAcrion)
{
if (RedisHelper.HashExists(key, sid))
{
return RedisHelper.HashGet<T>(key, sid);
}
else
{
T model = setAcrion();
if (model != null)
{
RedisHelper.HashSet(key, sid, model);
}
return model;
}
}
/// <summary>
/// 写入哈希缓存
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <param name="sid">键</param>
/// <param name="model">实体</param>
public static void SetHashCache<T>(string key, string sid, T model)
{
RedisHelper.HashSet(key, sid, model);
}
/// <summary>
/// 写入哈希缓存
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <param name="dic">字典</param>
public static void SetHashCache<T>(string key, Dictionary<string, T> dic)
{
RedisHelper.HashSet(key, dic);
}
/// <summary>
/// 获取哈希缓存字典
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="key">缓存key</param>
/// <returns></returns>
public static Dictionary<string, T> GetHashAllCache<T>(string key)
{
return RedisHelper.HashGetAll<T>(key);
}
public static bool CheckKey(string key)
{
return RedisHelper.CheckKey(key);
}
}
#endregion
}

View File

@@ -0,0 +1,995 @@
using AUTS.Domain.Entities;
using AUTS.Services.Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AUTS.Domain.Application;
using MySql.Data.MySqlClient;
using AUTS.Services.Manager;
namespace AUTS.Services.Cache
{
/// <summary>
/// 缓存
/// </summary>
public static class CacheHelp
{
#region
private static readonly string sysDBListKey = "sysManage_DBList";//库列表
private static readonly string sysCompanyListKey = "sysManage_CompanyList";//客户列表
private static readonly string sysUserAuthListKey = "sysManage_UserAuthList";//用户权限列表
private static readonly string sysDBCofinStrListKey = "sysManage_DBCofinStrList";//库连接串列表
private static readonly string sysCurrencyListKey = "sysManage_CurrencyList";//库连接串列表
private static readonly string sysSearchKeyKey = "sysManage_SearchKeyList";//库搜索关键词列表
private static readonly string sysUserOperationKey = "UserOperation_";//用户当前选择库
private static readonly string sysDBOrderStatusListKey = "sysManage_OrderStatusList";//客户库订单状态列表
private static readonly string sysDBOUserListKey = "sysUserList";//客户库订单状态列表
private static readonly string sysDBSnListKey = "sysSNlist";//订单表
#endregion
#region
private static readonly string userDBCustomerListKey = "_CustomerList";//客户库客户列表
private static readonly string userDBProjectListKey = "_ProjectList";//客户库产品列表
private static readonly string userDBPLineListKey = "_PLineList";//客户库产线列表
private static readonly string userDBOrderListKey = "_OrderList";//客户库订单列表
private static readonly string userDBStationListKey = "_StationList";//客户库工作站列表
private static readonly string userDBOrderInternalListKey = "_OrderInternalList";//客户库内部订单列表
private static readonly string userDBSnRulesListKey = "_SnRulesList";//客户库内部订单列表
private static readonly string userDBSnProjectTypeKey = "_ProjectType";//客户库产品类型列表
private static readonly string userDBSnRepairTypesKey = "_RepairTypes";//维修类型列表
private static readonly string userDBSnRepairReasonKey = "_SnRepairReason";//维修原因列表
private static readonly string userDBSnRepairResultsKey = "_RepairResults";//维修结果列表
#endregion
#region Hash缓存前缀
private static readonly string sysServiceListKey = "sysManage_Hash_ServiceList";//Hash缓存前缀
#endregion
#region
#region
#region
/// <summary>
/// 获取写入数据库列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static List<TBL_UTS_Manage_DBList> GetSysDBList()
{
return BaseCacheHelp.GetCache(sysDBListKey, () =>
{
var list = new List<TBL_UTS_Manage_DBList>();
using (var db = new Uts_ManageEntities())
{
//取所有
list = db.TBL_UTS_Manage_DBList.ToList();
}
return list;
});
}
#endregion
#region
/// <summary>
/// 清除数据库列表缓存
/// </summary>
public static void ClearSysDBList()
{
BaseCacheHelp.ClearCache(sysDBListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入厂家列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static List<TBL_UTS_Manage_Company> GetCompanyList()
{
return BaseCacheHelp.GetCache(sysCompanyListKey, () =>
{
var list = new List<TBL_UTS_Manage_Company>();
using (var db = new Uts_ManageEntities())
{
//取所有
list = db.TBL_UTS_Manage_Company.ToList();
}
return list;
});
}
#endregion
#region
/// <summary>
/// 清除写入厂家列表缓存
/// </summary>
public static void ClearCompanyList()
{
BaseCacheHelp.ClearCache(sysCompanyListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入用户权限列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static List<TBL_UTS_Manage_UserAuth_Operation> GetUserAuthList()
{
return BaseCacheHelp.GetCache(sysUserAuthListKey, () =>
{
var list = new List<TBL_UTS_Manage_UserAuth_Operation>();
using (var db = new Uts_ManageEntities())
{
//取所有
list = db.TBL_UTS_Manage_UserAuth_Operation.ToList();
}
return list;
});
}
#endregion
#region
/// <summary>
/// 清除用户权限列表缓存
/// </summary>
public static void ClearUserAuthList()
{
BaseCacheHelp.ClearCache(sysUserAuthListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入厂家列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static List<Domain.Application.DBCofinStrModel> GetDBCofinStrList()
{
return BaseCacheHelp.GetCache(sysDBCofinStrListKey, () =>
{
//取所有
var dbList = GetSysDBList();
var dbServer = Tool.ConfigHelper.GetConfigString("DBServer");//数据库服务器
string dbPort = Tool.ConfigHelper.GetConfigString("DBPort");//服务器端口
var dbCofinStrlist = new List<Domain.Application.DBCofinStrModel>();
foreach (var item in dbList)
{
MySql.Data.MySqlClient.MySqlConnectionStringBuilder one = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder
{
Server = dbServer,
Database = item.DatabaseName,//数据库名
UserID = item.DatabaseUser,//用户名
Password = item.DatabasePassword,//密码
Port = UInt16.Parse(dbPort),
Pooling = true
};
var cofinStr = one.ConnectionString;
dbCofinStrlist.Add(new Domain.Application.DBCofinStrModel
{
ID = item.ID,
CofinStr = cofinStr,
});
}
return dbCofinStrlist;
});
}
#endregion
#region
/// <summary>
/// 清除数据库连接串列表缓存
/// </summary>
public static void ClearSysDBListDBCofinStrList()
{
BaseCacheHelp.ClearCache(sysDBCofinStrListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入厂家列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static List<TBL_UTS_Manage_SearchKey> GetSearchKeyList()
{
return BaseCacheHelp.GetCache(sysSearchKeyKey, () =>
{
var list = new List<TBL_UTS_Manage_SearchKey>();
using (var db = new Uts_ManageEntities())
{
//取所有
list = db.TBL_UTS_Manage_SearchKey.ToList();
}
return list;
});
}
#endregion
#region
/// <summary>
/// 清除写入厂家列表缓存
/// </summary>
public static void ClearSearchKeyList()
{
BaseCacheHelp.ClearCache(sysSearchKeyKey);
}
#endregion
#endregion
/// <summary>
/// 币种列表
/// </summary>
/// <returns></returns>
public static List<Domain.Sys_Currency> GetSysCurrencyList()
{
return BaseCacheHelp.GetCache(sysCurrencyListKey, () =>
{
var dbCofinStrlist = new List<Domain.Sys_Currency>();
dbCofinStrlist.Add(new Domain.Sys_Currency
{
CurrencyName = "人民币",
Currency = "CNY",
CurrencySymbol = "¥",
});
dbCofinStrlist.Add(new Domain.Sys_Currency
{
CurrencyName = "美元",
Currency = "USD",
CurrencySymbol = "$",
});
dbCofinStrlist.Add(new Domain.Sys_Currency
{
CurrencyName = "欧元",
Currency = "EUR",
CurrencySymbol = "€",
});
dbCofinStrlist.Add(new Domain.Sys_Currency
{
CurrencyName = "日元",
Currency = "JPY",
CurrencySymbol = "¥",
});
dbCofinStrlist.Add(new Domain.Sys_Currency
{
CurrencyName = "新台币",
Currency = "TWD",
CurrencySymbol = "NT",
});
return dbCofinStrlist;
});
}
/// <summary>
/// 用户当前选择库
/// </summary>
/// <param name="userName"></param>
/// <param name="dbID"></param>
/// <returns></returns>
public static int GetUserOperation(string userName, int dbID = 0)
{
if (dbID == 0)
{
return BaseCacheHelp.GetCache(sysUserOperationKey + userName, () =>
{
return dbID;
});
}
else
{
BaseCacheHelp.SetCache(sysUserOperationKey + userName, () =>
{
return dbID;
});
return dbID;
}
}
#endregion
public static DataTable GetTodayData(string key,DataTable data = null)
{
return BaseCacheHelp.GetCache(key, () =>
{
return data;
});
}
#region
#region
#region
/// <summary>
/// 获取写入客户库厂家列表
/// </summary>
/// <returns></returns>
public static List<TBL_Customer> GetUserDBCustomerList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBCustomerListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_Customer>("TBL_Customer").GetList();
return list;
});
}
return null;
}
#endregion
#region
/// <summary>
/// 清除客户库厂家列表缓存
/// </summary>
public static void ClearUserDBCustomerList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBCustomerListKey);
}
}
#endregion
#endregion
#region
public static List<TBL_RepairTypes> GetUserDBSnRepairTypesList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBSnRepairTypesKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_RepairTypes>("TBL_RepairTypes").GetList();
return list;
});
}
return null;
}
#endregion
#region
public static List<TBL_RepairReason> GetUserDBRepairReasonList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBSnRepairReasonKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_RepairReason>("TBL_RepairReason").GetList();
return list;
});
}
return null;
}
#endregion
#region
public static List<TBL_RepairResults> GetUserDBRepairResultsList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBSnRepairResultsKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_RepairResults>("TBL_RepairResults").GetList();
return list;
});
}
return null;
}
#endregion
#region
#region
/// <summary>
/// 获取写入客户库产品列表
/// </summary>
/// <returns></returns>
public static List<TBL_Project> GetUserDBProjectList()
{
var onDB = Manager.Users.GerOnUserCustomer();
string strwhere = string.Empty;
int userid = Manager.Users.Umodel.ID;
int dbid = GetUserOperation(Users.Umodel.UserName);//后期修改回来
if (SqlConnect.ProjectData(userid, dbid).ToString() != "")
{
string[] str = SqlConnect.ProjectData(userid, dbid).ToString().Split(',');
foreach (var item in str)
{
strwhere += "ID= " + item + " or ";
}
strwhere = strwhere.Substring(0, strwhere.Length - 3);
}
if (onDB != null)
{
if (strwhere != "")
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBProjectListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_Project>("TBL_Project").GetList(strwhere);
return list;
});
}
else
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBProjectListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_Project>("TBL_Project").GetList();
return list;
});
}
}
return null;
}
#endregion
public static List<TBL_SnList> GetUserDBPSnlist()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + sysDBSnListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_SnList>("TBL_SnList").GetList();
return list;
});
}
return null;
}
#region
/// <summary>
/// 清除客户库产品列表缓存
/// </summary>
public static void ClearUserDBProjectList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBProjectListKey);
}
}
public static void ClearUserDBProjectList(string DbName)
{
BaseCacheHelp.ClearCache(DbName + userDBProjectListKey);
}
#endregion
#endregion
#region 线
#region 线
/// <summary>
/// 获取写入客户产线列表
/// </summary>
/// <returns></returns>
public static List<TBL_ProductionLine> GetUserDBPLineList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBPLineListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_ProductionLine>("TBL_ProductionLine").GetList();
return list;
});
}
return null;
}
#endregion
#region 线
/// <summary>
/// 清除客户库产线列表缓存
/// </summary>
public static void ClearUserDBPLineList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBPLineListKey);
}
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入订单列表
/// </summary>
/// <returns></returns>
public static List<TBL_ProductTypes> GetUserDBProjectTypeList(string dbName = null)
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache((dbName ?? onDB.DatabaseName) + userDBSnProjectTypeKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_ProductTypes>("TBL_ProductTypes").GetList();
return list;
});
}
return null;
}
#endregion
#region
/// <summary>
/// 清除客户库订单列表缓存
/// </summary>
public static void ClearUserDBProjectTypeList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBSnProjectTypeKey);
}
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入客户订单列表
/// </summary>
/// <returns></returns>
public static List<TBL_Orders> GetUserDBOrderList(string dbName = null)
{
string strwhere = string.Empty;
int userid = Manager.Users.Umodel.ID;
int dbid = GetUserOperation(Users.Umodel.UserName);
if (SqlConnect.ProjectData(userid, dbid).ToString() != "")
{
string[] str = SqlConnect.ProjectData(userid, dbid).ToString().Split(',');
foreach (var item in str)
{
strwhere += "ProductID= " + item + " or ";
}
strwhere = strwhere.Substring(0, strwhere.Length - 3);
}
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
if (strwhere != "")
{
return BaseCacheHelp.GetCache((dbName ?? onDB.DatabaseName) + userDBOrderListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_Orders>("TBL_Orders").GetList(strwhere);
if (list == null)
return new List<TBL_Orders>();
return list;
});
}
else
{
return BaseCacheHelp.GetCache((dbName ?? onDB.DatabaseName) + userDBOrderListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_Orders>("TBL_Orders").GetList();
if (list == null)
return new List<TBL_Orders>();
return list;
});
}
}
return null;
}
#endregion
public static List<TBL_UTS_Manage_User> GeiUserList()
{
return BaseCacheHelp.GetCache(sysDBOUserListKey, () =>
{
var list = new List<TBL_UTS_Manage_User>();
using (var db = new Uts_ManageEntities())
{
list = db.TBL_UTS_Manage_User.ToList();
}
return list;
});
}
#region
/// <summary>
/// 清除客户库订单列表缓存
/// </summary>
public static void ClearUserDBOrderList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBOrderListKey);
}
}
#endregion
public static void ClearProductTypes()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBSnProjectTypeKey);
}
}
#endregion
#region
#region
/// <summary>
/// 获取写入客户库订单状态列表
/// </summary>
/// <returns></returns>
public static List<TBL_UTS_Manage_OrderStatus> GetUserDBOrderStatusLis()
{
return BaseCacheHelp.GetCache(sysDBOrderStatusListKey, () =>
{
//取所有
var list = new DBUtility.Common.DALHelper<TBL_UTS_Manage_OrderStatus>("TBL_UTS_Manage_OrderStatus").GetList();
return list;
});
}
#endregion
#region
/// <summary>
/// 清除客户库订单状态列表缓存
/// </summary>
public static void ClearUserDBOrderStatusLis()
{
BaseCacheHelp.ClearCache(sysDBOrderStatusListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入客户工作站列表
/// </summary>
/// <returns></returns>
public static List<TBL_StationList> GetUserDBStationList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBStationListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_StationList>("TBL_StationList").GetList();
if (list != null)
list = list.Where(e => e.IsValid == 1).OrderBy(x => x.ArtworkOrder).ToList();
return list;
});
}
return null;
}
public static List<TBL_StationList> GetUserDBStationList(System.Web.HttpContext context)
{
var onDB = Manager.Users.GerOnUserCustomer(context);
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBStationListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_StationList>("TBL_StationList").GetList().Where(e => e.IsValid == 1).ToList();
return list;
});
}
return null;
}
#endregion
#region
/// <summary>
/// 清除客户库工作站列表缓存
/// </summary>
public static void ClearUserDBStationList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBStationListKey);
}
}
public static void ClearUserDBStationList(string DbName)
{
BaseCacheHelp.ClearCache(DbName + userDBStationListKey);
}
public static void ClearUserDBOrderList(string DbName)
{
BaseCacheHelp.ClearCache(DbName + userDBOrderListKey);
}
public static void ClearUserDBOrderIList(string DbName)
{
BaseCacheHelp.ClearCache(DbName + userDBOrderInternalListKey);
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入客户订单列表
/// </summary>
/// <returns></returns>
public static List<TBL_OrderInternal> GetUserDBOrderInternalList()
{
string strwhere = string.Empty;
int userid = Manager.Users.Umodel.ID;
int dbid = GetUserOperation(Users.Umodel.UserName);
if (SqlConnect.ProjectData(userid, dbid).ToString() != "")
{
string[] str = SqlConnect.ProjectData(userid, dbid).ToString().Split(',');
foreach (var item in str)
{
strwhere += "ProductID= " + item + " or ";
}
strwhere = strwhere.Substring(0, strwhere.Length - 3);
}
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
if(strwhere != "")
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBOrderInternalListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_OrderInternal>("TBL_OrderInternal").GetList(strwhere);
if (list == null)
return new List<TBL_OrderInternal>();
return list;
});
}
else
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBOrderInternalListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_OrderInternal>("TBL_OrderInternal").GetList();
if (list == null)
return new List<TBL_OrderInternal>();
return list;
});
}
}
return null;
}
#endregion
#region
/// <summary>
/// 清除客户库内部单列表缓存
/// </summary>
public static void ClearUserDBOrderInternalList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBOrderInternalListKey);
}
}
#endregion
#endregion
#region
#region
/// <summary>
/// 获取写入条码规则列表
/// </summary>
/// <returns></returns>
public static List<TBL_SnRules> GetUserDBSnRulesList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
return BaseCacheHelp.GetCache(onDB.DatabaseName + userDBSnRulesListKey, () =>
{
//取所有
var list = new DBUtility.Custom.DALHelperCustom<TBL_SnRules>("TBL_SnRules").GetList();
return list;
});
}
return null;
}
#endregion
#region
/// <summary>
/// 清除客户库条码规则列表缓存
/// </summary>
public static void ClearUserDBSnRulesList()
{
var onDB = Manager.Users.GerOnUserCustomer();
if (onDB != null)
{
BaseCacheHelp.ClearCache(onDB.DatabaseName + userDBSnRulesListKey);
}
}
#endregion
#endregion
#endregion
#region Hash缓存
#region Hash列表(UDP通讯)
#region Hash列表
/// <summary>
/// 获取写入服务Hash列表
/// </summary>
/// <returns>返回数据库列表</returns>
public static TBL_UTS_Manage_DataServiceList GetHashService(int sid)
{
return BaseCacheHelp.GetHashCache(sysServiceListKey, sid.ToString(), () =>
{
var mdoel = new TBL_UTS_Manage_DataServiceList();
using (var db = new Uts_ManageEntities())
{
//取所有
mdoel = db.TBL_UTS_Manage_DataServiceList.SingleOrDefault(x => x.ID == sid);
}
return mdoel;
});
}
#endregion
#region Hash
/// <summary>
/// 写入服务Hash
/// </summary>
/// <param name="model"></param>
public static void SetHashService(TBL_UTS_Manage_DataServiceList model)
{
BaseCacheHelp.SetHashCache(sysServiceListKey, model.ID.ToString(), model);
}
#endregion
#region Hash列表
public static List<TBL_UTS_Manage_DataServiceList> GetHashServiceList()
{
if (BaseCacheHelp.CheckKey(sysServiceListKey))
{
return BaseCacheHelp.GetHashAllCache<TBL_UTS_Manage_DataServiceList>(sysServiceListKey).Values.OrderBy(x => x.ID).ToList();
}
else
{
var list = new List<TBL_UTS_Manage_DataServiceList>();
using (var db = new Uts_ManageEntities())
{
//取所有
list = db.TBL_UTS_Manage_DataServiceList.OrderBy(x => x.ID).ToList();
Dictionary<string, TBL_UTS_Manage_DataServiceList> dic = list.ToDictionary(key => key.ID.ToString(), value => value);
BaseCacheHelp.SetHashCache(sysServiceListKey, dic);
}
return list;
}
}
#endregion
#endregion
#endregion
}
}

View File

@@ -0,0 +1,75 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.DBUtility
{
public enum EffentNextType
{
/// <summary>
/// 对其他语句无任何影响
/// </summary>
None,
/// <summary>
/// 当前语句必须为"select count(1) from .."格式,如果存在则继续执行,不存在回滚事务
/// </summary>
WhenHaveContine,
/// <summary>
/// 当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务
/// </summary>
WhenNoHaveContine,
/// <summary>
/// 当前语句影响到的行数必须大于0否则回滚事务
/// </summary>
ExcuteEffectRows,
/// <summary>
/// 引发事件-当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务
/// </summary>
SolicitationEvent
}
public class CommandInfo
{
public object ShareObject = null;
public object OriginalData = null;
event EventHandler _solicitationEvent;
public event EventHandler SolicitationEvent
{
add
{
_solicitationEvent += value;
}
remove
{
_solicitationEvent -= value;
}
}
public void OnSolicitationEvent()
{
if (_solicitationEvent != null)
{
_solicitationEvent(this, new EventArgs());
}
}
public string CommandText;
public System.Data.Common.DbParameter[] Parameters;
public EffentNextType EffentNextType = EffentNextType.None;
public CommandInfo()
{
}
public CommandInfo(string sqlText, MySqlParameter[] para)
{
this.CommandText = sqlText;
this.Parameters = para;
}
public CommandInfo(string sqlText, MySqlParameter[] para, EffentNextType type)
{
this.CommandText = sqlText;
this.Parameters = para;
this.EffentNextType = type;
}
}
}

View File

@@ -0,0 +1,324 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.DBUtility.Common
{
public class DALHelper<TEntity> where TEntity : class, new()
{
private string databasetablename; //数据库表名前缀
//private DbConfigsInfo confInfi;
public DALHelper()
{
databasetablename = "TBL_UTS_Manage";
}
public DALHelper(string _databaseprefix)
{
databasetablename = _databaseprefix;
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
return DbHelperMySQL.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId(TEntity entity, string strField)
{
return DbHelperMySQL.GetMaxID(strField, databasetablename);
}
public bool Add(TEntity entity)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into " + databasetablename + "(");
PropertyInfo[] propertys = entity.GetType().GetProperties();// 获得此模型的公共属性
List<MySqlParameter> parameters = new List<MySqlParameter>();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append(pi.Name + ",");
strSql.Append(" values (");
}
strSql.Append(" ) values (");
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append(pi.Name + "@,");
parameters.Add(new MySqlParameter("@" + pi.Name, pi.GetValue(entity)));
}
strSql.Append(");select @@IDENTITY");
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters.ToArray());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 修改一个实体数据
/// </summary>
/// <param name="entity"></param>
/// <param name="strField"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public bool Update(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + databasetablename + " set ");
PropertyInfo[] propertys = entity.GetType().GetProperties();// 获得此模型的公共属性
List<MySqlParameter> parameters = new List<MySqlParameter>();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append(pi.Name + "=@" + pi.Name + ",");
parameters.Add(new MySqlParameter("@" + pi.Name, pi.GetValue(entity)));
}
strSql.Append(" where " + strField + "=@strValue");
parameters.Add(new MySqlParameter("@strValue", keyValue));
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters.ToArray());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 修改一列数据
/// </summary>
public int UpdateField(TEntity entity, string strField, object strValue, string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + databasetablename);
strSql.Append(" set " + strField + "=@strValue");
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
MySqlParameter[] parameters = {
new MySqlParameter("@strValue",strValue)
};
return DbHelperMySQL.ExecuteSql(strSql.ToString());
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
int rows = DbHelperMySQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
public TEntity GetModel(TEntity entity, string strField, string keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
strSql.Append(" LIMIT 0,1;");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
DataSet ds = DbHelperMySQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(entity, ds.Tables[0]);
}
else
{
return null;
}
}
public List<TEntity> GetList(string strWhere = null)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from " + databasetablename);
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
//strSql.Append(" LIMIT 0,1;");
TEntity entity = new TEntity();
DataSet ds = DbHelperMySQL.Query(strSql.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModels(entity, ds.Tables[0]);
}
else
{
return null;
}
}
/// <summary>
/// 将DataTable转换得到一个对象实体
/// </summary>
/// <param name="model"></param>
/// <param name="dt"></param>
/// <returns></returns>
public TEntity DataRowToModel(TEntity model, DataTable dt)
{
if (dt.Rows.Count > 0)
{
TEntity t = new TEntity();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dt.Rows[0][pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Single":
pi.SetValue(t, float.Parse(value.ToString()), null);
break;
case "System.Double":
pi.SetValue(t, double.Parse(value.ToString()), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
case "System.DateTime":
pi.SetValue(t, DateTime.Parse(value.ToString()), null);
break;
case "System.Boolean":
pi.SetValue(t, bool.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
return t;
}
else
{
return null;
}
}
/// <summary>
/// 将DataTable转换得到一个对象实体集合
/// </summary>
/// <param name="model"></param>
/// <param name="dt"></param>
/// <returns></returns>
public List<TEntity> DataRowToModels(TEntity model, DataTable dt)
{
List<TEntity> ts = new List<TEntity>();// 定义集合
foreach (DataRow dr in dt.Rows)
{
TEntity t = new TEntity();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Single":
pi.SetValue(t, float.Parse(value.ToString()), null);
break;
case "System.Double":
pi.SetValue(t, double.Parse(value.ToString()), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
case "System.DateTime":
pi.SetValue(t, DateTime.Parse(value.ToString()), null);
break;
case "System.Boolean":
pi.SetValue(t, bool.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
ts.Add(t);
}
return ts;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,524 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.DBUtility.Custom
{
public class DALHelperCustom<TEntity> where TEntity : class, new()
{
private string databasetablename; //数据库表名前缀
//private DbConfigsInfo confInfi;
public DALHelperCustom()
{
databasetablename = "TBL_UTS_Manage";
}
public DALHelperCustom(string _databaseprefix)
{
databasetablename = _databaseprefix;
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
return DbHelperMySqlCustom.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 得到最大ID
/// </summary>
public int GetMaxId(TEntity entity, string strField)
{
return DbHelperMySqlCustom.GetMaxID(strField, databasetablename);
}
/// <summary>
/// 添加一条数据
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Add(TEntity entity)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into " + databasetablename + "(");
PropertyInfo[] propertys = entity.GetType().GetProperties();// 获得此模型的公共属性
List<MySqlParameter> parameters = new List<MySqlParameter>();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite || pi.GetValue(entity)==null) continue;
strSql.Append(pi.Name + ",");
}
strSql.Remove(strSql.Length - 1, 1);//移除最后一个逗号
strSql.Append(" ) values (");
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite || pi.GetValue(entity) == null) continue;
strSql.Append("@" + pi.Name + ",");
parameters.Add(new MySqlParameter("@" + pi.Name, pi.GetValue(entity)));
}
strSql.Remove(strSql.Length - 1, 1);//移除最后一个逗号
strSql.Append(");select @@IDENTITY");
int rows = DbHelperMySqlCustom.ExecuteSql(strSql.ToString(), parameters.ToArray());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 修改一列数据
/// </summary>
/// <param name="entity"></param>
/// <param name="strField"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public bool Update(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + databasetablename + " set ");
PropertyInfo[] propertys = entity.GetType().GetProperties();// 获得此模型的公共属性
List<MySqlParameter> parameters = new List<MySqlParameter>();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append(pi.Name + "=@" + pi.Name + ",");
parameters.Add(new MySqlParameter("@" + pi.Name, pi.GetValue(entity)));
}
strSql.Remove(strSql.Length - 1, 1);//移除最后一个逗号
strSql.Append(" where " + strField + "=@strValue");
System.Type keyType = keyValue.GetType();
switch (keyType.Name)
{
case "Int32":
MySqlParameter strValue = new MySqlParameter("@strValue", MySqlDbType.Int32)
{
Value = keyValue
};
parameters.Add(strValue);
break;
default:
parameters.Add(new MySqlParameter("@strValue", keyValue));
break;
}
int rows = DbHelperMySqlCustom.ExecuteSql(strSql.ToString(), parameters.ToArray());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 修改一列数据
/// </summary>
public int UpdateField(TEntity entity, string strField, object strValue, string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + databasetablename);
strSql.Append(" set " + strField + "=@strValue");
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
MySqlParameter[] parameters = {
new MySqlParameter("@strValue",strValue)
};
return DbHelperMySqlCustom.ExecuteSql(strSql.ToString(), parameters);
}
/// <summary>
/// 修改一列数据
/// </summary>
public int UpdateFieldTia(TEntity entity, string strField, string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update " + databasetablename);
strSql.Append(" set " + strField);
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
return DbHelperMySqlCustom.ExecuteSql(strSql.ToString());
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
int rows = DbHelperMySqlCustom.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
/// <param name="uid"></param>
/// <returns></returns>
public TEntity GetModel(TEntity entity, string strField, object keyValue)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from " + databasetablename);
strSql.Append(" where " + strField + "=@keyValue ");
strSql.Append(" LIMIT 0,1;");
MySqlParameter[] parameters = {
new MySqlParameter("@keyValue",keyValue)
};
DataSet ds = DbHelperMySqlCustom.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(entity, ds.Tables[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到数据列表
/// </summary>
/// <param name="strWhere"></param>
/// <returns></returns>
public List<TEntity> GetList(string strWhere = null)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from " + databasetablename);
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
//strSql.Append(" LIMIT 0,1;");
//strSql.Append(";");
TEntity entity = new TEntity();
DataSet ds = DbHelperMySqlCustom.Query(strSql.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModels(entity, ds.Tables[0]);
}
else
{
return new List<TEntity>();
}
}
/// <summary>
/// 重载,得到数据列表
/// </summary>
/// <param name="columnName"></param>
/// <param name="strWhere"></param>
/// <returns></returns>
public List<TEntity> GetList(string columnName, string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select " + columnName + " from " + databasetablename);
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(" where " + strWhere);
}
//strSql.Append(" LIMIT 0,1;");
strSql.Append(";");
TEntity entity = new TEntity();
DataSet ds = DbHelperMySqlCustom.Query(strSql.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModels(entity, ds.Tables[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到数据列表
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public List<TEntity> SqlQueryGetList(string strSql)
{
//StringBuilder strSql = new StringBuilder();
//strSql.Append("select " + columnName + " from " + databasetablename);
//if (!string.IsNullOrEmpty(strWhere))
//{
// strSql.Append(" where " + strWhere);
//}
//strSql.Append(" LIMIT 0,1;");
//strSql.Append(";");
TEntity entity = new TEntity();
DataSet ds = DbHelperMySqlCustom.Query(strSql);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModels(entity, ds.Tables[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到数据列表
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public List<TEntity> SqlQueryGetListdb(string strSql)
{
//StringBuilder strSql = new StringBuilder();
//strSql.Append("select " + columnName + " from " + databasetablename);
//if (!string.IsNullOrEmpty(strWhere))
//{
// strSql.Append(" where " + strWhere);
//}
//strSql.Append(" LIMIT 0,1;");
//strSql.Append(";");
TEntity entity = new TEntity();
DataSet ds = DbHelperMySqlCustom.dbQuery(strSql);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModels(entity, ds.Tables[0]);
}
else
{
return null;
}
}
/// <summary>
/// 将DataTable转换得到一个对象实体
/// </summary>
/// <param name="model"></param>
/// <param name="dt"></param>
/// <returns></returns>
public TEntity DataRowToModel(TEntity model, DataTable dt)
{
if (dt.Rows.Count > 0)
{
TEntity t = new TEntity();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dt.Rows[0][pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Single":
pi.SetValue(t, float.Parse(value.ToString()), null);
break;
case "System.Double":
pi.SetValue(t, double.Parse(value.ToString()), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
case "System.DateTime":
pi.SetValue(t, DateTime.Parse(value.ToString()), null);
break;
case "System.Boolean":
pi.SetValue(t, bool.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
return t;
}
else
{
return null;
}
}
/// <summary>
/// 将DataTable转换得到一个对象实体集合
/// </summary>
/// <param name="model"></param>
/// <param name="dt"></param>
/// <returns></returns>
public List<TEntity> DataRowToModels(TEntity model, DataTable dt)
{
List<TEntity> ts = new List<TEntity>();// 定义集合
foreach (DataRow dr in dt.Rows)
{
TEntity t = new TEntity();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Single":
pi.SetValue(t, float.Parse(value.ToString()), null);
break;
case "System.Double":
pi.SetValue(t, double.Parse(value.ToString()), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
case "System.DateTime":
pi.SetValue(t, DateTime.Parse(value.ToString()), null);
break;
case "System.Boolean":
pi.SetValue(t, bool.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
ts.Add(t);
}
return ts;
}
/// <summary>
/// 将DataTable转换得到一个对象实体集合
/// </summary>
/// <param name="model"></param>
/// <param name="dt"></param>
/// <returns></returns>
public List<TEntity> DataRowToModels(DataTable dt)
{
List<TEntity> ts = new List<TEntity>();// 定义集合
foreach (DataRow dr in dt.Rows)
{
try
{
TEntity t = new TEntity();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Single":
pi.SetValue(t, float.Parse(value.ToString()), null);
break;
case "System.Double":
pi.SetValue(t, double.Parse(value.ToString()), null);
break;
case "System.Int32":
if (value.ToString().Trim().Length <= 0)
{
value = "0";
}
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
case "System.DateTime":
pi.SetValue(t, DateTime.Parse(value.ToString()), null);
break;
case "System.Boolean":
pi.SetValue(t, bool.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
ts.Add(t);
}
catch (Exception ex)
{
continue;
throw;
}
}
return ts;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
/// <summary>
/// 缓存的时间类别
/// </summary>
public enum CacheTimeType
{
/// <summary>
/// 按照分钟模式
/// </summary>
ByMinutes,
/// <summary>
/// 按照小时模式
/// </summary>
ByHours,
/// <summary>
/// 按照天模式
/// </summary>
ByDays,
/// <summary>
/// 按照年模式
/// </summary>
ByYears
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
public enum LoginInfoType
{
/*
* 添加账户类型的时候枚举值为2的倍数
*
*/
/// <summary>
/// 管理人员
/// </summary>
[Description("管理人员")]
Manager = 2,
/// <summary>
/// 用户
/// </summary>
[Description("用户")]
User = 4,
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
/// <summary>
/// 操作权限级别
/// </summary>
public enum OperationLevel
{
/// <summary>
/// 只读
/// </summary>
[Description("只读")]
ReadOnly = 10,
/// <summary>
/// 读写
/// </summary>
[Description("读写")]
ReadWrite = 20,
/// <summary>
/// 完整
/// </summary>
[Description("完整")]
Full = 30,
}
}

View File

@@ -0,0 +1,72 @@
using System.ComponentModel;
namespace AUTS.Services.Enums
{
/// <summary>
/// 此类变量英文不正确
/// </summary>
public enum OrderStatus
{
/// <summary>
/// 已转MO
/// </summary>
[Description("已转MO")]
PlaceOrder = 1,
/// <summary>
/// 已分配条码
/// </summary>
[Description("已分配条码")]
NoScheduling = 2,
/// <summary>
/// 已排产
/// </summary>
[Description("已排产")]
MOrder = 3,
/// <summary>
/// 生产中
/// </summary>
[Description("生产中")]
SnRules = 4,
/// <summary>
/// 完成生产
/// </summary>
[Description("完成生产")]
ProductionPlan = 5,
/// <summary>
/// 已结单
/// </summary>
[Description("已结单")]
InProduction = 6,
/// <summary>
/// 未确认
/// </summary>
[Description("PO已录入")]
unconfirmed=99,
///// <summary>
///// 已完成
///// </summary>
//[Description("已完成")]
//Completed = 7,
/// <summary>
/// 取消
/// </summary>
[Description("取消")]
Cancel = -1,
/// <summary>
/// 暂停中
/// </summary>
[Description("暂停中")]
Suspend = -2,
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
public class Root
{
public List<DataItem> data { get; set; }
}
public class DataItem
{
/// <summary>
///
/// </summary>
public string ExtendedLocation { get; set; }
/// <summary>
///
/// </summary>
public string OriginQuery { get; set; }
/// <summary>
///
/// </summary>
public string appinfo { get; set; }
/// <summary>
///
/// </summary>
public int disp_type { get; set; }
/// <summary>
///
/// </summary>
public string fetchkey { get; set; }
/// <summary>
/// 本地局域网
/// </summary>
public string location { get; set; }
/// <summary>
///
/// </summary>
public string origip { get; set; }
/// <summary>
///
/// </summary>
public string origipquery { get; set; }
/// <summary>
///
/// </summary>
public string resourceid { get; set; }
/// <summary>
///
/// </summary>
public int role_id { get; set; }
/// <summary>
///
/// </summary>
public int shareImage { get; set; }
/// <summary>
///
/// </summary>
public int showLikeShare { get; set; }
/// <summary>
///
/// </summary>
public string showlamp { get; set; }
/// <summary>
/// IP地址查询
/// </summary>
public string titlecont { get; set; }
/// <summary>
///
/// </summary>
public string tplt { get; set; }
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
/// <summary>
/// 短字符串版本
/// </summary>
public enum ShortStringVersion
{
/// <summary>
/// 版本1
/// </summary>
[MaxLength(6)]
[Description("版本1")]
Version_1 = 5,
/// <summary>
/// 版本2
/// </summary>
[MaxLength(8)]
[Description("版本2")]
Version_2 = 4,
/// <summary>
/// 版本3
/// </summary>
[Description("版本3")]
[MaxLength(10)]
Version_3 = 3,
/// <summary>
/// 版本4
/// </summary>
[MaxLength(15)]
[Description("版本4")]
Version_4 = 2,
/// <summary>
/// 版本5
/// </summary>
[Description("版本5")]
[MaxLength(30)]
Version_5 = 1
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
public enum SnType
{
/// <summary>
/// 无序
/// </summary>
[Description("无序")]
Unordered = 0,
/// <summary>
/// 十六进制
/// </summary>
[Description("自动生成")]
Hexadecimal = 1,
/// <summary>
/// 直接录入
/// </summary>
[Description("直接录入")]
Entering = 2,
/// <summary>
/// Excel导入
/// </summary>
[Description("Excel导入")]
Excel = 3,
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Enums
{
public enum StationType
{
/// <summary>
/// 测试
/// </summary>
[Description("Test")]
Test = 100,
/// <summary>
/// 测试2
/// </summary>
[Description("Test2")]
Test2 = 120,
/// <summary>
/// 组装
/// </summary>
[Description("Assem")]
Assem = 200,
/// <summary>
/// 质量保证
/// </summary>
[Description("QA")]
QA = 300,
}
}

View File

@@ -0,0 +1,149 @@
using AUTS.Services.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace AUTS.Services.Extensions
{
/// <summary>
/// 缓存扩展
/// </summary>
public static class CacheExtensions
{
public static MvcHtmlString Cache(this HtmlHelper htmlHelper, string cacheName, Func<object> func, CacheTimeType cacheTimeType, int cacheTime)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, func().ToString(), cacheTimeType, cacheTime);
}
return MvcHtmlString.Create(CacheExtensions.GetCache<string>(cacheName));
}
/// <summary>
/// 检查缓存名是否存在如果存在则返回True
/// </summary>
/// <param name="cacheName">缓存的枚举类</param>
public static bool CheckCache(string cacheName)
{
return HttpRuntime.Cache[cacheName.ToString()] != null;
}
/// <summary>
/// 获取缓存,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static T GetCache<T>(string cacheName)
{
return (T)((object)HttpRuntime.Cache[cacheName]);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc, CacheTimeType cacheTimeType, int times)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc(), cacheTimeType, times);
}
return CacheExtensions.GetCache<T>(cacheName);
}
public static T GetCacheWithSet<T>(string cacheName, Func<T> valueFunc)
{
if (!CacheExtensions.CheckCache(cacheName))
{
CacheExtensions.SetCache(cacheName, valueFunc());
}
return CacheExtensions.GetCache<T>(cacheName);
}
/// <summary>
/// 获取缓存集合,未做校验,每次取缓存的时候需要判断缓存是否存在
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheName"></param>
/// <param name="varName"></param>
/// <returns></returns>
public static List<T> GetCacheList<T>(string cacheName)
{
return (List<T>)HttpRuntime.Cache[cacheName];
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
/// <param name="cacheTimeType"></param>
/// <param name="cacheTime"></param>
public static void SetCache(string cacheName, object value, CacheTimeType cacheTimeType, int cacheTime)
{
switch (cacheTimeType)
{
case CacheTimeType.ByMinutes:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddMinutes((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByHours:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddHours((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByDays:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddDays((double)cacheTime), TimeSpan.Zero);
return;
case CacheTimeType.ByYears:
HttpRuntime.Cache.Insert(cacheName, value, null, DateTime.Now.AddYears(cacheTime), TimeSpan.Zero);
return;
default:
return;
}
}
public static void SetCache(string cacheName, object value)
{
HttpRuntime.Cache.Insert(cacheName, value);
}
public static List<string> GetAllCache()
{
List<string> list = new List<string>();
IDictionaryEnumerator enumerator = HttpRuntime.Cache.GetEnumerator();
while (enumerator.MoveNext())
{
list.Add(enumerator.Key.ToString());
}
return list;
}
/// <summary>
/// 清除指定缓存
/// </summary>
/// <param name="cacheName"></param>
public static void ClearCache(string cacheName)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache.Remove(cacheName);
}
}
/// <summary>
/// 重置缓存
/// </summary>
/// <param name="cacheName"></param>
/// <param name="value"></param>
public static void RestCache(string cacheName, object value)
{
if (CacheExtensions.CheckCache(cacheName))
{
HttpRuntime.Cache[cacheName] = value;
return;
}
CacheExtensions.SetCache(cacheName, value);
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace AUTS.Services.Extensions
{
/// <summary>
/// cookie扩展
/// </summary>
public static class CookieExtensions
{
/// <summary>
/// 写cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <param name="strValue">值</param>
public static void WriteCookie(string strName, string strValue)
{
HttpCookie httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <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 httpCookie = HttpContext.Current.Request.Cookies[strName];
if (httpCookie == null)
{
httpCookie = new HttpCookie(strName);
}
httpCookie.Value = strValue;
httpCookie.Expires = DateTime.Now.AddMinutes((double)expires);
HttpContext.Current.Response.AppendCookie(httpCookie);
}
/// <summary>
/// 读cookie值
/// </summary>
/// <param name="strName">名称</param>
/// <returns>cookie值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
/// <summary>
/// 检查Cookie,如果存在则为true
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
public static bool CheckCookie(string strName)
{
return HttpContext.Current.Request.Cookies[strName] != null;
}
/// <summary>
/// 删除Cookie
/// </summary>
/// <param name="strName"></param>
public static void RemoveCookie(string strName)
{
HttpContext.Current.Request.Cookies.Remove(strName);
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Extensions
{
/// <summary>
/// 异常扩展
/// </summary>
public class CustomException : ApplicationException
{
//记录异常的类型
private CustomExceptionType exceptionType;
public CustomException(CustomExceptionType type) : base()
{
this.exceptionType = type;
}
public CustomException(CustomExceptionType type, string message) : base(message)
{
this.exceptionType = type;
}
public CustomException(string message) : base(message)
{
this.exceptionType = CustomExceptionType.InputValidation;
}
//序列化
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
//重写message方法,以让它显示相应异常提示信息
public override string Message
{
get
{
//根据异常类型从message.xml中读取相应异常提示信息
return base.Message;
//return string.Format(XmlMessageManager.GetXmlMessage((int)exceptionType), base.Message);
}
}
}
public enum CustomExceptionType
{
InputValidation = 1,
hint = 2,
Warning = 3,
Unknown = 8
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Extensions
{
/// <summary>
/// 枚举扩展
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// 对枚举器的每个元素执行指定的操作
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">枚举器</param>
/// <param name="action">要对枚举器的每个元素执行的委托</param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source.IsNullOrEmpty<T>() || action == null)
{
return;
}
foreach (T obj in source)
{
action(obj);
}
}
/// <summary>
/// 指示指定的枚举器是null还是没有任何元素
/// </summary>
/// <typeparam name="T">枚举器类型参数</typeparam>
/// <param name="source">要测试的枚举器</param>
/// <returns>true:枚举器是null或者没有任何元素 false:枚举器不为null并且包含至少一个元素</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
return source == null || !source.Any<T>();
}
/// <summary>
/// 得到枚举中文备注
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetEnumDesc(this System.Enum enumValue)
{
string value = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length == 0) //当描述属性没有时,直接返回名称
return value;
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
public static string GetEnumDesc(this Type enumType, object val)
{
string enumvalue = Enum.GetName(enumType, val);
if (string.IsNullOrEmpty(enumvalue))
{
return "";
}
FieldInfo finfo = enumType.GetField(enumvalue);
object[] enumAttr = finfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (enumAttr.Length > 0)
{
DescriptionAttribute desc = (DescriptionAttribute)enumAttr[0];
if (desc != null)
{
return desc.Description;
}
}
return enumvalue;
}
/// <summary>
/// 获取所有的枚举描述和值
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static List<EnumDto> GetEnumListItem(this Type type)
{
List<EnumDto> list = new List<EnumDto>();
// 循环枚举获取所有的Fields
foreach (var field in type.GetFields())
{
// 如果是枚举类型
if (field.FieldType.IsEnum)
{
object tmp = field.GetValue(null);
Enum enumValue = (Enum)tmp;
int intValue = Convert.ToInt32(enumValue);
string showName = enumValue.GetEnumDesc(); // 获取描述和排序
list.Add(new EnumDto { Value = intValue, Description = showName });
}
}
//返回
return list;
}
public class EnumDto
{
/// <summary>
/// 枚举code
/// </summary>
public string Code { get; set; }
/// <summary>
/// 值
/// </summary>
public int Value { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
}
}
}

View File

@@ -0,0 +1,469 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Reflection;
namespace System.Linq
{
public static class LinqExtensions
{
/// <summary>通过页面控件动态构建查询</summary>
public static IQueryable<TSource> WhereDynamic<TSource>(this IQueryable<TSource> source,
NameValueCollection nameValues) where TSource : class
{
if (nameValues.Count > 0)
{
//构建 c=>Body中的c
ParameterExpression param = Expression.Parameter(typeof(TSource), "c");
//构建c=>Body中的Body
var body = GetExpressoinBody(param, nameValues);
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, param);
//传到Where中当做参数类型为Expression<Func<T,bool>>
return source.Where(expression);
}
}
return source;
}
/// <summary>构建body</summary>
private static Expression GetExpressoinBody(ParameterExpression param, NameValueCollection nameValues)
{
var list = new List<Expression>();
if (nameValues.Count > 0)
{
var plist = param.Type.GetRuntimeProperties().ToDictionary(z => z.Name);//可以加缓存改善性能
foreach (var item in nameValues.AllKeys)
if (item.EndsWith(">") || item.EndsWith(">="))//可能大小查询
{
bool isEqual = item.EndsWith(">=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('>') : item.TrimEnd('>');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
//list.Add(Expression.GreaterThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(dValue, rType), isEqual));
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault();
//list.Add(Expression.GreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterGreaterThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (item.EndsWith("<") || item.EndsWith("<="))//可能大小查询
{
bool isEqual = item.EndsWith("<=");
string key = isEqual ? item.TrimEnd('=').TrimEnd('<') : item.TrimEnd('<');
if (!plist.ContainsKey(key) || nameValues[item].Length <= 0) continue;
var rType = plist[key].GetMethod.ReturnType;
if (rType == typeof(string)) continue;
var e1 = Expression.Property(param, key);
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
{
if (rType == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (plist[key].GetMethod.ReturnType.GenericTypeArguments.Count() > 0 && TryParser(nameValues[item], plist[key].GetMethod.ReturnType.GenericTypeArguments[0], out dValue))
{
if (plist[key].GetMethod.ReturnType.GenericTypeArguments[0] == typeof(DateTime)) dValue = ((DateTime)dValue).AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(dValue, rType)));
list.Add(AddGreaterLessThan(e1, Expression.Constant(dValue, rType), isEqual));
}
else if (rType == typeof(DateTime?))
{
DateTime enddate = nameValues[item].ToDateTime().GetValueOrDefault().AddDays(1);
//list.Add(Expression.LessThan(e1, Expression.Constant(enddate, typeof(DateTime?))));
list.Add(AddGreaterLessThan(e1, Expression.Constant(enddate, typeof(DateTime?)), isEqual));
}
}
else if (plist.ContainsKey(item) && nameValues[item].Length > 0)
{
var e1 = Expression.Property(param, item);
var rType = plist[item].GetMethod.ReturnType;
if (rType == typeof(string))//可能是like查询
{
var value = nameValues[item].Trim('%');
var e2 = Expression.Constant(value, rType);
if (nameValues[item].StartsWith("%") && nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (nameValues[item].StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (nameValues[item].EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
else if (nameValues[item].IndexOf(",") > 0)//可能是in查询
{
if (rType == typeof(short))
{
var searchList = TryParser<short>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(int))
{
var searchList = TryParser<int>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
else if (rType == typeof(long))
{
var searchList = TryParser<long>(nameValues[item]);
if (searchList.Any())
list.Add(Expression.Call(Expression.Constant(searchList, rType), "Contains", null, new Expression[] { e1 }));
}
}
else
{
object dValue;
if (TryParser(nameValues[item], rType, out dValue))
list.Add(Expression.Equal(e1, Expression.Constant(dValue, rType)));
}
}
}
return list.Count > 0 ? list.Aggregate(Expression.AndAlso) : null;
}
private static List<T> TryParser<T>(string value)
{
string[] searchArray = value.Split(',');
List<T> dList = new List<T>();
foreach (var l in searchArray)
{
try
{
T dValue = (T)Convert.ChangeType(l, typeof(T));
dList.Add(dValue);
}
catch { }
}
return dList;
}
private static bool TryParser(string value, Type outType, out object dValue)
{
try
{
dValue = Convert.ChangeType(value, outType);
return true;
}
catch
{
dValue = null;
return false;
}
}
//大于
private static Expression AddGreaterGreaterThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.GreaterThanOrEqual(exleft, exright);
}
else
{
return Expression.GreaterThan(exleft, exright);
}
}
//大于
private static Expression AddGreaterLessThan(Expression exleft, Expression exright, bool Equal)
{
if (Equal)
{
return Expression.LessThanOrEqual(exleft, exright);
}
else
{
return Expression.LessThan(exleft, exright);
}
}
/// <summary>
/// 从 System.Collections.Generic.IQueryable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IQueryable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 从 System.Collections.Generic.IEnumerable`1 创建一个 System.Collections.Generic.List`1。并在集合末尾添加一个默认值为空的TSource实例
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">要从其创建 System.Collections.Generic.List`1 的 System.Collections.Generic.IEnumerable`1。</param>
/// <returns>一个包含输入序列中元素的 System.Collections.Generic.List`1。</returns>
public static List<TSource> ToListAndAddEmpty<TSource>(this IEnumerable<TSource> source) where TSource : class
{
List<TSource> list = source.ToList();
TSource addmodel = Activator.CreateInstance<TSource>();
list.Add(addmodel);
return list;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiled">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource>(this IQueryable<TSource> source, string keyword, params string[] keyfiled)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keyfiled)
{
string[] paramKs = item.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 外键表动态模糊查询
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要模糊查找的值序列。</param>
/// <typeparam name="TKey">由 keySelector 表示的函数返回的键类型。</typeparam>
/// <param name="keyword">查询关键字(动态模糊在首或尾部添加%)</param>
/// <param name="keyfiledn">查询字段</param>
/// <param name="keySelector">查询字段Lamvda表达式(支持多表导航查询)</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> LikeQueryable<TSource, TKey>(this IQueryable<TSource> source, string keyword, string keyfiled, params Expression<Func<TSource, TKey>>[] keySelector)
{
try
{
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
Expression body = null;
var list = new List<Expression>();
foreach (var item in keySelector)
{
string[] paramKs = item.Body.ToString().Split('.');
var e1 = Expression.Property(paramT, paramKs[1]);//c.user
for (int i = 2; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
e1 = Expression.Property(e1, keyfiled);//c.user.ID
if (e1.Type == typeof(string))
{
var value = keyword.Trim('%');
var e2 = Expression.Constant(value, typeof(string));
if (keyword.StartsWith("%") && keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "Contains", null, new Expression[] { e2 }));
else if (keyword.StartsWith("%"))
list.Add(Expression.Call(e1, "EndsWith", null, new Expression[] { e2 }));
else if (keyword.EndsWith("%"))
list.Add(Expression.Call(e1, "StartsWith", null, new Expression[] { e2 }));
else
list.Add(Expression.Equal(e1, e2));
}
}
body = list.Count > 0 ? list.Aggregate(Expression.OrElse) : null;
//构建c=>Body中的Body
if (body != null)
{
//将二者拼为c=>Body
var expression = Expression.Lambda<Func<TSource, bool>>(body, paramT);
//传到Where中当做参数类型为Expression<Func<T,bool>>
source = source.Where(expression);
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IQueryable<TSource> OrderByQueryable<TSource>(this IQueryable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source, expression);
break;
case 2:
source = Queryable.OrderByDescending(source, expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
/// <summary>
/// 动态排序
/// </summary>
/// <typeparam name="TSource">source 中的元素的类型。</typeparam>
/// <param name="source">一个要排序查找的值序列。</param>
/// <param name="keyfiled">排序字段</param>
/// <param name="type">排序类型0不排序1升序2降序</param>
/// <returns>一个 System.Linq.IOrderedQueryable`1根据键对其元素模糊查找。</returns>
public static IEnumerable<TSource> OrderByQueryable<TSource>(this IEnumerable<TSource> source, string keyfiled, int type)
{
try
{
if (type == 0) return source;//不排序
var paramT = Expression.Parameter(typeof(TSource), "c");//c=>
string[] paramKs = keyfiled.Split('.');
var e1 = Expression.Property(paramT, paramKs[0]);//c.user
for (int i = 1; i < paramKs.Count(); i++)
{
e1 = Expression.Property(e1, paramKs[i]);//c.user.ID
}
dynamic expression = Expression.Lambda(e1, paramT);
switch (type)
{
case 1:
source = Queryable.OrderBy(source.AsQueryable(), expression);
break;
case 2:
source = Queryable.OrderByDescending(source.AsQueryable(), expression);
break;
default:
break;
}
}
catch
{
}
return source;
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Extensions
{
/// <summary>
/// 对象扩展
/// </summary>
public static class ModelExtensions
{
/// <summary>
/// 创建一个新的类型的对象,并将现有对象的属性值赋给新对象相同名称的属性
/// </summary>
/// <typeparam name="T">新对象的类型</typeparam>
/// <param name="source">现有对象</param>
/// <returns>新的对象</returns>
public static T ToModel<T>(this object source) where T : new()
{
if (source == null)
{
return default(T);
}
return Activator.CreateInstance<T>().UpdateFrom(source, new string[0]);
}
/// <summary>
/// 将源对象的属性值赋给目标对象相同名称的属性
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">源对象</param>
/// <param name="copyPropertyName">需要复制的属性名,为空时表示复制全部</param>
/// <returns>目标类型</returns>
public static T UpdateFrom<T>(this T target, object source, params string[] copyPropertyName)
{
if (target == null)
{
return default(T);
}
if (source == null)
{
return target;
}
Type typeFromHandle = typeof(T);
foreach (PropertyInfo obj in source.GetType().GetProperties())
{
//PropertyDescriptor propertyDescriptor = (PropertyDescriptor)obj;
if (copyPropertyName == null || copyPropertyName.Length == 0 || copyPropertyName.Contains(obj.Name))
{
PropertyInfo property = typeFromHandle.GetProperty(obj.Name, BindingFlags.Instance | BindingFlags.Public);
if (property != null && property.CanWrite)
{
property.SetValue(target, obj.GetValue(source, null), null);
}
}
}
return target;
}
}
}

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
/// <summary>
/// 字符串转换扩展
/// </summary>
public static class SafeInputExtensions
{
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ToShort(this object str)
{
short result = 0;
if (str != null)
{
short.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成Int类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int ToInt(this object str)
{
int result = 0;
if (str != null)
{
int.TryParse(str.ToString(), out result);
}
return result;
}
/// <summary>
/// 将字符串转换成decimal类型如果出错则返回0
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static double ToDouble(this object str)
{
double result = 0.0;
if (str != null)
{
double.TryParse(str.ToString(), out result);
}
return result;
}
public static decimal ToDecimal(this object str)
{
decimal result = 0m;
if (str != null)
{
decimal.TryParse(str.ToString(), out result);
}
return result;
}
public static string ToNone(this object str, string extStr)
{
if (str != null && !string.IsNullOrEmpty(str.ToString()))
{
return str + " " + extStr;
}
return "";
}
/// <summary>
/// 将字符串转换成真假
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ToBool(this object str)
{
return str != null && str.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// 将字符串转换成GUID出错则为Guid.NewGuid()
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Guid ToGuid(this object str)
{
Guid result = Guid.NewGuid();
if (str != null)
{
Guid.TryParse(str.ToString(), out result);
}
return result;
}
public static DateTime ToDateTime(this object str)
{
DateTime now = DateTime.Now;
if (str != null)
{
DateTime.TryParse(str.ToString(), out now);
}
return now;
}
public static string ToDateTimeRandom()
{
return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999).ToString();
}
public static string ToDateString()
{
return DateTime.Now.ToString("yyyyMMdd");
}
public static string ToBr(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>");
}
return str;
}
}
}

View File

@@ -0,0 +1,402 @@
using AUTS.Services.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing.Imaging;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AUTS.Services.Extensions
{
/// <summary>
/// 字符串扩展函数工具类
/// </summary>
public static class StringExtensions
{
/// <summary>
/// 将\r\n替换成BR
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToSafeBR(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>");
}
return str;
}
/// <summary>
/// 得到父部门的ID
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetDepartmentFatherID(this string str)
{
if (!string.IsNullOrEmpty(str) && str.Length > 2)
{
str = str.Substring(0, str.Length - 3);
}
return str;
}
/// <summary>
/// 截取字符串,超过部分用...代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <returns></returns>
public static string Substr(this string source, int len)
{
return source.Substr(len, "...");
}
/// <summary>
/// 截取字符串,超过部分用自定义代替
/// </summary>
/// <param name="source"></param>
/// <param name="len"></param>
/// <param name="att"></param>
/// <returns></returns>
public static string Substr(this string source, int len, string att)
{
if (string.IsNullOrEmpty(source))
{
return string.Empty;
}
att = (att ?? string.Empty);
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
else if (regex2.IsMatch(source))
{
if (source.Length <= len * 2)
{
return source;
}
return source.Substring(0, len * 2) + att;
}
else
{
if (source.Length <= len)
{
return source;
}
return source.Substring(0, len) + att;
}
}
public static string InputStr(this string source)
{
if (!string.IsNullOrEmpty(source))
{
Regex regex = new Regex("[\\u4e00-\\u9fa5]");
Regex regex2 = new Regex("^[A-Za-z0-9]+$");
if (regex.IsMatch(source))
{
if (source.Length < 3)
{
return string.Format("{0}**", source[0]);
}
if (source.Length == 3)
{
return string.Format("{0}*{1}", source[0], source[source.Length - 1]);
}
if (source.Length > 3)
{
return string.Format("{0}**{1}", source[0], source[source.Length - 1]);
}
}
else
{
if (!regex2.IsMatch(source))
{
return string.Format("{0}**", source.Substring(0, 2));
}
if (source.Length < 6)
{
return string.Format("{0}**", source.Substring(0, 2));
}
return string.Format("{0}****{1}", source.Substring(0, 2), source.Substring(source.Length - 3, 2));
}
}
return string.Empty;
}
/// <summary>
/// 移除掉所有的Html代码
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string RemoveHtml(this string strHtml)
{
Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase);
strHtml = regex.Replace(strHtml, "");
strHtml = strHtml.Replace("&nbsp;", "");
return strHtml;
}
/// <summary>
/// 生成0-9随机数
/// </summary>
/// <param name="VcodeNum">生成长度</param>
/// <returns></returns>
public static string RndNum(int VcodeNum)
{
StringBuilder stringBuilder = new StringBuilder(VcodeNum);
Random random = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
int num = random.Next(9);
stringBuilder.AppendFormat("{0}", num);
}
return stringBuilder.ToString();
}
/// <summary>
/// 返回星号的加密
/// </summary>
/// <param name="items"></param>
/// <param name="mask"></param>
/// <returns></returns>
public static string MaskStar(Dictionary<string, string> items, bool mask)
{
StringBuilder stringBuilder = new StringBuilder();
if (mask)
{
foreach (KeyValuePair<string, string> keyValuePair in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair.Key,
"').attr('name', '",
keyValuePair.Key,
"mask');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', true);");
stringBuilder.Append("$('.maskstar').val('***');");
}
else
{
foreach (KeyValuePair<string, string> keyValuePair2 in items)
{
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').attr('name', '",
keyValuePair2.Key,
"');"
}));
stringBuilder.Append(string.Concat(new string[]
{
"$('#",
keyValuePair2.Key,
"').val('",
keyValuePair2.Value,
"');"
}));
}
stringBuilder.Append("$('.maskstar').attr('disabled', false);");
}
return stringBuilder.ToString();
}
/// <summary>
/// 给自动填充使用
/// </summary>
/// <param name="str1"></param>
/// <param name="str2"></param>
/// <returns></returns>
public static string ToAutoComplate(this string str1, string str2)
{
if (!string.IsNullOrEmpty(str1) && !string.IsNullOrEmpty(str2))
{
return str1 + "," + str2;
}
return "";
}
/// <summary>
/// 返回红色字体
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToRedColor(this int value)
{
if (value != 0)
{
return "<font color='red'>" + value.ToString() + "</font>";
}
return value.ToString();
}
/// <summary>
/// 返回安全的字符串类型如果为NULL则返回空
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToSafeString(this object value)
{
if (value == null)
{
return "";
}
return value.ToString();
}
/// <summary>
/// 将中文转换成Unicode编码主要用在URL传递中文
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GB2Unicode(this string str)
{
string text = "";
Encoding encoding = Encoding.GetEncoding("GB2312");
Encoding unicode = Encoding.Unicode;
byte[] bytes = encoding.GetBytes(str);
for (int i = 0; i < bytes.Length; i++)
{
string str2 = "%" + bytes[i].ToString("x");
text += str2;
}
return text;
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToMD5(this string str)
{
MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
StringBuilder stringBuilder = new StringBuilder();
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
return stringBuilder.ToString().ToUpper();
}
/// <summary>
/// 字节码长度转可读字符串 00000000 bytes 0.0GB
/// </summary>
/// <param name="KSize"></param>
/// <returns></returns>
public static string ByteSizeToString(this long KSize)
{
if (KSize > 0L)
{
string[] array = new string[]
{
"B",
"KB",
"MB",
"GB",
"TB"
};
double num = 0.0;
int num2 = array.Length - 1;
while (num2 >= 0 && (num = Math.Round((double)KSize / Math.Pow(1024.0, (double)num2), 2)) < 1.0)
{
num2--;
}
return string.Format("{0}{1}", num, array[num2]);
}
return string.Empty;
}
/// <summary>
/// 将图片的字节码数组转成 base64 字符串
/// </summary>
/// <param name="img"></param>
/// <param name="format"></param>
/// <returns></returns>
public static string GetImgBase64String(this byte[] img, ImageFormat format)
{
return string.Format("data:image/{0};base64,{1}", format.ToString(), Convert.ToBase64String(img));
}
/// <summary>
/// 将字符串转换成为大写的MD5
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string GetMD5Code(this string str)
{
StringBuilder stringBuilder = new StringBuilder();
using (MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider())
{
byte[] array = md5CryptoServiceProvider.ComputeHash(Encoding.Default.GetBytes(str));
foreach (byte b in array)
{
stringBuilder.Append(b.ToString("x2"));
}
}
return stringBuilder.ToString();
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <param name="version">制码版本</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str, ShortStringVersion version)
{
string text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = text.Length;
string md5Code = str.GetMD5Code();
string[] array = new string[4];
FieldInfo field = typeof(ShortStringVersion).GetField(version.ToString());
MaxLengthAttribute maxLengthAttribute = ((MaxLengthAttribute[])field.GetCustomAttributes(typeof(MaxLengthAttribute), false))[0];
int num = 0;
while (num < 4 && text.Length > 0)
{
int i = 1073741823 & Convert.ToInt32("0x" + md5Code.Substring(num * 8, 8), 16);
string text2 = string.Empty;
int index = 61 & i;
while (i > 0)
{
text2 += text[index];
i >>= (int)version;
index = (61 & i);
}
while (text2.Length < maxLengthAttribute.Length)
{
text2 += text[num];
}
array[num] = text2;
num++;
}
return array;
}
/// <summary>
/// 转码成短字符串
/// </summary>
/// <param name="str">源字符串</param>
/// <returns>短码数组</returns>
public static string[] EncodeShortString(this string str)
{
return str.EncodeShortString(ShortStringVersion.Version_1);
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
public static class TimeExtensions
{
public static DateTime? ToDateTime(this string timeStamp)
{
long ticks = 0L;
if (long.TryParse(timeStamp, out ticks))
{
DateTime dateTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan value = new TimeSpan(ticks);
return new DateTime?(dateTime.Add(value));
}
DateTime now = DateTime.Now;
if (DateTime.TryParse(timeStamp, out now))
{
return new DateTime?(now);
}
return null;
}
}
}

View File

@@ -0,0 +1,565 @@
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.DBUtility.Custom;
using AUTS.Services.Enums;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace AUTS.Services.Manager
{
public partial class AutsChart
{
private static string TestLogTbName = "TBL_{0}_{1}_TestLog";//测试记录表名
/// <summary>
/// 图表-未完成订单生产进度统计
/// </summary>
/// <param name="reqModel">查询条件实体</param>
/// <param name="cacheUserProject">机型缓存</param>
/// <param name="cacheUserOrder">订单缓存</param>
/// <param name="cacheUserCustomer">客户缓存</param>
/// <param name="cacheUserStationList">工作站缓存</param>
/// <returns></returns>
public static ReturnResult<object> GetOrderStats(RequestOrderStats reqModel, List<TBL_Project> cacheUserProject, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var project = cacheUserProject.SingleOrDefault(x => x.ID == reqModel.ProjectID);
if (!reqModel.IsOrder)//如果不是按照订单
{
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
if (reqModel.StartDate == null)
{
result.Message = "请输入起始时间";
return result;
}
}
var orderNotList = cacheUserOrder.Where(x => x.OrderStatus == (int)OrderStatus.InProduction);//取出该机型未完成订单
var minTime = reqModel.StartDate ?? DateTime.Now;//起始时间
if (project != null)
{
orderNotList = orderNotList.Where(x => x.ProductID == project.ID);
}
if (!reqModel.IsOrder)
{
orderNotList = orderNotList.Where(x => x.CreateTime <= minTime && x.DeliveryTime >= minTime);//取出未完成订单
//minTime = orderNotList.Min(m => m.CreateTime);//订单最早日期
}
else
{
if (reqModel.StartDate == null && orderNotList.Count() > 0)
{
minTime = orderNotList.Min(m => m.CreateTime);//订单最早日期
}
}
if (orderNotList.Count() == 0)
{
result.Status = 200;
return result;
}
var maxTime = reqModel.EndDate ?? DateTime.Now;//最晚日期
minTime = Convert.ToDateTime(minTime.ToString("yyyy/MM/dd"));//订单最早日期
maxTime = Convert.ToDateTime(maxTime.ToString("yyyy/MM/dd"));//订单最晚日期
TimeSpan ts = maxTime - minTime;
int differenceInDays = ts.Days + 1;
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("ID", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("单号", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("机型", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("客户", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数量", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("已完成", Type.GetType("System.String"));//新列
for (var i = 0; i < differenceInDays; i++)
{
tblDatas.Columns.Add(minTime.AddDays(i).ToString("yy/MM/dd"), Type.GetType("System.String"));//新列
}
var dbTableName = "";
var sumTotal = 0;
var dalHelperCustom = new DALHelperCustom<VM_PlannedSpeed>();
var thisDataList = new List<VM_PlannedSpeed>();
string connectionString = Users.GerOnUserCofin();//当前库连接串
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter();
var strSql = "";
foreach (var item in orderNotList)
{
strSql = "";
dataSet.Clear();
sumTotal = 0;
DataRow newRow = tblDatas.NewRow();//新行
newRow["ID"] = item.ID;
newRow["单号"] = item.OrderNo;
newRow["机型"] = cacheUserProject.Single(x => x.ID == item.ProductID).ProjectName;
newRow["客户"] = cacheUserCustomer.Single(x => x.ID == item.CompanyID).CustomerAbbr;
newRow["数量"] = item.OrderCount;
var endTestStation = cacheUserStationList.Where(x => x.ProjectID == item.ProductID && (x.StationType == StationType.Test.GetEnumDesc() || x.StationType == StationType.Test2.GetEnumDesc())).OrderByDescending(o => o.ArtworkOrder).FirstOrDefault();//最大测试站
dbTableName = string.Format(TestLogTbName, item.ProductID, endTestStation.ID);//最大测试站表名
//strSql = "select StartTime,DATE_FORMAT(StartTime,'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where OrderID=" + item.OrderID + " AND TestResult=1 GROUP BY DAYS;";//查询语句
strSql = "select {0} StartTime,DATE_FORMAT({0},'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where TestResult=1";//查询语句
if (reqModel.StartDate != null)
{
strSql += " AND (DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') >='" + minTime.ToString("yyyy-MM-dd 00:00:00") + "')";
//strSql += (string.Format(" AND (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') >='{0}')", minTime.ToString("yyyy-MM-dd 00:00:00")));
}
if (reqModel.EndDate != null && reqModel.StartDate != null)
{
strSql += " AND (DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') <='" + maxTime.ToString("yyyy-MM-dd 23:59:59") + "')";
//strSql += (string.Format(" AND (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') <='{0}')", maxTime.ToString("yyyy-MM-dd 23:59:59")));
}
if (reqModel.IsOrder)
{
strSql += " AND OrderID=" + item.ID;
}
strSql += " GROUP BY DAYS;";
if (endTestStation.StationType == StationType.Test2.GetEnumDesc())
{
strSql = string.Format(strSql, "DateTime_2nd");
}
else
{
strSql = string.Format(strSql, "StartTime");
}
command = new MySqlDataAdapter(strSql, connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]);
foreach (var itemData in thisDataList)
{
newRow[itemData.StartTime.ToString("yy/MM/dd")] = itemData.Total;
sumTotal += itemData.Total;
}
}
newRow["已完成"] = sumTotal;
tblDatas.Rows.Add(newRow);
}
}
var rows = ModelHelper.TableToRow(tblDatas);
result.Data = rows;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
/// <summary>
/// 图表-该订单各站生产进度统计
/// </summary>
/// <param name="reqModel">查询条件实体</param>
/// <param name="cacheUserProject">机型缓存</param>
/// <param name="cacheUserOrder">订单缓存</param>
/// <param name="cacheUserCustomer">客户缓存</param>
/// <param name="cacheUserStationList">工作站缓存</param>
/// <param name="connectionString">数据库连接串</param>
/// <returns></returns>
public static ReturnResult<object> GetOrdersPlannedSpeedDetails(RequestOrdersPlanned reqModel, List<TBL_Project> cacheUserProject, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList, string connectionString)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var id = reqModel.id;
var order = cacheUserOrder.Single(x => x.ID == id);//取出订单
var stationList = cacheUserStationList.Where(x => x.StationType != StationType.QA.GetEnumDesc() && x.ProjectID == order.ProductID);//不为该机型QA的测试站
var minTime = reqModel.StartDate ?? order.CreateTime;//订单最早日期
var maxTime = reqModel.EndDate ?? DateTime.Now;//订单最晚日期
minTime = Convert.ToDateTime(minTime.ToString("yyyy/MM/dd"));//订单最早日期
maxTime = Convert.ToDateTime(maxTime.ToString("yyyy/MM/dd"));//订单最晚日期
TimeSpan ts = maxTime - minTime;
int differenceInDays = ts.Days + 1;
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("测试站", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数量", Type.GetType("System.String"));//新列
for (var i = 0; i < differenceInDays; i++)
{
tblDatas.Columns.Add(minTime.AddDays(i).ToString("yy/MM/dd"), Type.GetType("System.String"));//新列
}
var dbTableName = "";
var strSql = "";
var sumTotal = 0;
var dalHelperCustom = new DALHelperCustom<VM_PlannedSpeed>();
//string connectionString = Users.GerOnUserCofin();//当前库连接串
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
MySqlDataAdapter command = new MySqlDataAdapter();
connection.Open();
//测试站列表
foreach (var itemStation in stationList)
{
strSql = "";
sumTotal = 0;
dataSet.Clear();
DataRow newRow = tblDatas.NewRow();//新行
newRow["测试站"] = itemStation.StationName;
newRow["数量"] = "当日";
DataRow newRow2 = tblDatas.NewRow();//新行
newRow2["测试站"] = itemStation.StationName;
newRow2["数量"] = "累计";
dbTableName = string.Format(TestLogTbName, itemStation.ProjectID, itemStation.ID);//测试站表名
//strSql = "select StartTime,DATE_FORMAT(StartTime,'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where OrderID=" + id + " AND TestResult=1 GROUP BY DAYS;";//查询语句
strSql = "select {0},DATE_FORMAT({0},'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where TestResult=1";//查询语句
if (reqModel.IsOrder)
{
strSql += " AND OrderID=" + id;
}
if (reqModel.StartDate != null)
{
strSql += " AND (DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') >='" + minTime.ToString("yyyy-MM-dd 00:00:00") + "')";
}
if (reqModel.EndDate != null && reqModel.StartDate != null)
{
strSql += " AND (DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') <='" + maxTime.ToString("yyyy-MM-dd 23:59:59") + "')";
}
strSql += " GROUP BY DAYS;";
if (itemStation.StationType == StationType.Test2.GetEnumDesc())
{
strSql = string.Format(strSql, "DateTime_2nd");
}
else
{
strSql = string.Format(strSql, "StartTime");
}
command = new MySqlDataAdapter(strSql, connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
var thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]).OrderBy(x => x.StartTime);
foreach (var itemData in thisDataList)
{
newRow[itemData.StartTime.ToString("yy/MM/dd")] = itemData.Total;
sumTotal += itemData.Total;
newRow2[itemData.StartTime.ToString("yy/MM/dd")] = sumTotal;
}
}
tblDatas.Rows.Add(newRow);
tblDatas.Rows.Add(newRow2);
}
}
var rows = ModelHelper.TableToRow(tblDatas);
result.Data = rows;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
/// <summary>
/// 生产实时统计
/// </summary>
/// <param name="reqModel"></param>
/// <param name="cacheUserProject"></param>
/// <param name="cacheUserOrder"></param>
/// <param name="cacheUserCustomer"></param>
/// <param name="cacheUserStationList"></param>
/// <param name="connectionString"></param>
/// <returns></returns>
public static ReturnResult<object> GetOrdersStatsDetails(RequestOrdersRealTime reqModel, List<TBL_Project> cacheUserProject, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList, string connectionString)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
//var vModelList = new VM_OrderPlannedSpeed();
var id = reqModel.Order;
var order = cacheUserOrder.SingleOrDefault(x => x.ID == id);//取出订单
if (order == null)
{
result.Message = "无订单或无效订单";
return result;
}
var project = cacheUserProject.Single(x => x.ID == order.ProductID);//取出订单
var customer = cacheUserCustomer.Single(x => x.ID == order.CompanyID);//取出订单
var stationList = cacheUserStationList.Where(x => x.StationType != StationType.QA.GetEnumDesc() && x.ProjectID == order.ProductID).OrderBy(o => o.ArtworkOrder);//不为该机型QA的测试站
//vModelList.ProjectName = project.ProjectName;
//vModelList.OrderNo = order.OrderNo;
//vModelList.CustomerAbbr = customer.CustomerAbbr;
//vModelList.OrderCount = order.OrderCount;
//vModelList.CreateTime = order.CreateTime.ToString("yyyy/MM/dd");
//vModelList.DeliveryTime = order.DeliveryTime.ToString("yyyy/MM/dd");
////测试站列表
//foreach (var itemStation in stationList)
//{
// vModelList.StationDes += itemStation.StationName + "-" + itemStation.StationDesc + "&nbsp;";
//}
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("DataType", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("日期", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数据类型", Type.GetType("System.String"));//新列
//foreach (var station in stationList)
//{
// tblDatas.Columns.Add(station.StationName, Type.GetType("System.String"));//新列
//}
var strSql = "";//查询语句
var dbTableName = "";//测试记录表名
var timeStr = "";//日期
var totalDic = new Dictionary<string, TbTotalDic>();//计算字典
var ppNum = 0;
var actualNum = 0;
var thisRow = 1;
var rowKey = 0;
var pPlan = new TBL_ProductionPlan();
var testLog = new OrderTestLogData();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
MySqlDataAdapter command = new MySqlDataAdapter();
connection.Open();
strSql = "SELECT * FROM `TBL_ProductionPlan` WHERE OrderID=" + order.ID + ";";
command = new MySqlDataAdapter(strSql, connection);
command.Fill(dataSet, "ds");
var dalHelperPP = new DALHelperCustom<TBL_ProductionPlan>();
var dalHelperPSpeed = new DALHelperCustom<OrderTestLogData>();
var pSpeed = new List<OrderTestLogData>();
var ppList = dalHelperPP.DataRowToModels(dataSet.Tables[0]);//计划列表
var ppListGroup = ppList.GroupBy(g => g.ProductionTime).OrderBy(x => x.Key);//计划列表按时间分组
if (ppListGroup.Count() > 0)
{
foreach (var dateTime in ppListGroup)
{
timeStr = dateTime.Key.ToString("yyyy/MM/dd");
DataRow planRow = tblDatas.NewRow();//新行 计划行
planRow["DataType"] = "plan";
planRow["日期"] = timeStr;
planRow["数据类型"] = "计划";
tblDatas.Rows.Add(planRow);
DataRow planTotalRow = tblDatas.NewRow();//新行 累计计划行
planTotalRow["DataType"] = "plantotal";
planTotalRow["日期"] = timeStr;
planTotalRow["数据类型"] = "累计计划";
tblDatas.Rows.Add(planTotalRow);
DataRow testNumRow = tblDatas.NewRow();//新行 累计计划行
testNumRow["DataType"] = "test";
testNumRow["日期"] = timeStr;
testNumRow["数据类型"] = "当日";
tblDatas.Rows.Add(testNumRow);
DataRow testNumTotalRow = tblDatas.NewRow();//新行 累计计划行
testNumTotalRow["DataType"] = "testtotal";
testNumTotalRow["日期"] = timeStr;
testNumTotalRow["数据类型"] = "累计当日";
tblDatas.Rows.Add(testNumTotalRow);
}
var minTime = ppList.Min(m => m.ProductionTime);//订单最早日期
var maxTime = ppList.Max(m => m.ProductionTime);//订单最晚日期
var timeWhere = " AND(DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') >= '" + minTime.ToString("yyyy-MM-dd 00:00:00") + "') AND (DATE_FORMAT({0}, '%Y-%m-%d %H:%i:%s') <='" + maxTime.ToString("yyyy-MM-dd 23:59:59") + "')";
//测试站列表
foreach (var itemStation in stationList)
{
tblDatas.Columns.Add(itemStation.StationName, Type.GetType("System.String"));//新列
totalDic.Add(itemStation.StationName, new TbTotalDic());
dataSet.Clear();
dbTableName = string.Format(TestLogTbName, order.ProductID, itemStation.ID);//测试站表名
strSql = "select {0} StartTime,DATE_FORMAT({0},'%Y/%m/%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where TestResult=1";//查询语句
strSql += timeWhere;
if (itemStation.StationType == StationType.Test2.GetEnumDesc())
{
strSql = string.Format(strSql, "DateTime_2nd");
}
else
{
strSql = string.Format(strSql, "StartTime");
}
strSql += " GROUP BY DAYS;";
command = new MySqlDataAdapter(strSql, connection);
command.Fill(dataSet, "ds");
pSpeed = dalHelperPSpeed.DataRowToModels(dataSet.Tables[0]);//测试记录数据
thisRow = 1;
foreach (var dateTime in ppListGroup)
{
rowKey = (thisRow * 4);
pPlan = null;
testLog = null;
if (dateTime.ToList().Count > 0)
{
pPlan = dateTime.ToList().SingleOrDefault(x => x.StationID == itemStation.ID);
}
testLog = pSpeed.SingleOrDefault(x => x.DAYS == timeStr);
timeStr = dateTime.Key.ToString("yyyy/MM/dd");
ppNum = pPlan == null ? 0 : pPlan.ObjectiveYield;
totalDic[itemStation.StationName].PlanTotal += ppNum;
if (ppNum > 0)
{
tblDatas.Rows[(rowKey - 4)][itemStation.StationName] = ppNum;//计划
tblDatas.Rows[(rowKey - 3)][itemStation.StationName] = totalDic[itemStation.StationName].PlanTotal;//累计计划
}
actualNum = testLog == null ? 0 : testLog.Total;
totalDic[itemStation.StationName].ActualTotal += actualNum;
if (actualNum > 0)
{
tblDatas.Rows[(rowKey - 2)][itemStation.StationName] = actualNum;//当日
tblDatas.Rows[(rowKey - 1)][itemStation.StationName] = totalDic[itemStation.StationName].ActualTotal;//累计
}
thisRow += 1;
}
}
}
}
var rows = ModelHelper.TableToRow(tblDatas);
//vModelList.Rows = ModelHelper.TableToRow(tblDatas);
result.Data = rows;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
/// <summary>
/// 更新生产进度
/// </summary>
public static void UpdateOrderProductionSchedule()
{
//取所有库
var dbList = Cache.CacheHelp.GetSysDBList();
if (dbList != null && dbList.Count > 0)
{
IEnumerable<TBL_Orders> orderList = null;//
//var orderList = new List<TBL_Orders>();
foreach (var item in dbList)
{
orderList = Cache.CacheHelp.GetUserDBOrderList(item.DatabaseName).Where(x => x.OrderStatus == (int)OrderStatus.ProductionPlan && x.OrderStatus == (int)OrderStatus.InProduction);
}
}
}
}
}

View File

@@ -0,0 +1,977 @@
using AUTS.Domain;
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.Cache;
using AUTS.Services.DBUtility.Custom;
using AUTS.Services.Enums;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public partial class Capacity
{
private static string TestLogTbName = "TBL_{0}_{1}_TestLog";//测试记录表名
/// <summary>
/// 获取当前机型最大ID
/// </summary>
/// <param name="ProjectID"></param>
/// <param name="context"></param>
/// <returns></returns>
public static int GerOnProjectMaxID(int ProjectID, List<TBL_StationList> cacheUserStation, System.Web.HttpContext context)
{
var stationID = cacheUserStation.Where(x => x.ProjectID == ProjectID).Min(m => m.ID);
var dbTableName = string.Format(TestLogTbName, ProjectID, stationID);
string strsql = "select max(ID) from " + dbTableName;
string connectionString = Users.GerOnUserCofin(context);
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(strsql, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return 0;
}
else
{
return int.Parse(obj.ToString());
}
}
catch (MySqlException e)
{
connection.Close();
throw e;
}
}
}
//return DBUtility.Custom.DbHelperMySqlCustom.GetMaxID("ID", dbTableName);
}
public static ReturnResult<object> GetTestLogList(RequestTestLogSearch reqModel, List<TBL_Project> cacheUserProject, List<TBL_StationList> cacheUserStation)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var project = cacheUserProject.SingleOrDefault(x => x.ID == reqModel.ProjectID);
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
if (reqModel.KeyWhere != "number" && reqModel.KeyWhere != "testLogID")
{
result.Message = "无效查询类型";
return result;
}
if (String.IsNullOrEmpty(reqModel.KeyWord))
{
result.Message = "请输入查询关键词";
return result;
}
#region
var strWhereList = new List<string>();//条件语句列表
string dbTableName;//查询表名字段
StringBuilder strSqlSB = new StringBuilder();
var rdata = new ResponseDataquerySearch();
var thisDataList = new List<DataQuerySearch>();
var dataList = new List<DataQuerySearch>();
#endregion
#region
//工作站
var stationList = cacheUserStation.Where(x => x.ProjectID == reqModel.ProjectID).OrderBy(o => o.ArtworkOrder).Select(s => new TBL_Station { StationID = s.ID, StationName = s.StationName, StationType = s.StationType, ArtworkOrder = s.ArtworkOrder }).ToList();//当前选择的工艺站
#endregion
var maxAssemblySn = "";//最大编号组合
var assemPrList = stationList.Where(x => x.StationType == StationType.Assem.GetEnumDesc()).OrderByDescending(x => x.ArtworkOrder).ToList();//所有组装站
string connectionString = Users.GerOnUserCofin();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
try
{
var strSql = "";
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter();
if (reqModel.KeyWhere == "testLogID")
{
var forIDdbTableName = string.Format(TestLogTbName, reqModel.ProjectID, stationList.Min(m => m.StationID));
strSql = "SELECT DUT_SN FROM `" + forIDdbTableName + "` WHERE ID=" + reqModel.KeyWord.ToInt();
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
maxAssemblySn = dataSet.Tables[0].Rows[0]["DUT_SN"].ToString();
}
else
{
result.Message = "该序号暂无数据";
return result;
}
}
else if (reqModel.KeyWhere == "number")
{
maxAssemblySn = reqModel.KeyWord;
}
//从组合站中取出最大的序号集
foreach (var item in assemPrList)
{
dataSet.Clear();
dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, item.StationID);
strSql = "select AssemblySn from " + dbTableName + " Where locate('," + maxAssemblySn + ",',CONCAT(',',AssemblySn,','))";
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
maxAssemblySn = dataSet.Tables[0].Rows[0]["AssemblySn"].ToString();
break;
}
}
var dalHelperCustom = new DALHelperCustom<DataQuerySearch>();
foreach (var item in stationList)
{
dataSet.Clear();
thisDataList = null;
strSqlSB.Remove(0, strSqlSB.Length);//移除stringBuilder中的内容
dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, item.StationID);
strSqlSB.Append("SELECT ID,StartTime,TestResult,DUT_SN FROM " + dbTableName);
strSqlSB.Append(" WHERE locate(CONCAT(',',DUT_SN,','),'," + maxAssemblySn + ",')");
command = new MySqlDataAdapter(strSqlSB.ToString(), connection);
command.Fill(dataSet, "ds");
//if (dataSet.Tables[0].Rows.Count == 0)
//{
// break;
//}
thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]);
foreach (var data in thisDataList)
{
dataList.Add(new DataQuerySearch
{
ID = data.ID,
StartTime = data.StartTime == null ? "" : data.StartTime,
TestResult = data.TestResult,
StationName = item.StationName,
StationID = item.StationID,
ProjectID = reqModel.ProjectID,
DUT_SN = data.DUT_SN,
});
}
}
}
catch (MySqlException ex)
{
result.Message = ex.Message;
}
}
rdata.ProductNumbers = maxAssemblySn;
rdata.DataQuerySearchList = dataList;
result.Data = rdata;
result.Status = 200;
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
/// <summary>
/// 测试记录详情
/// </summary>
/// <param name="projectID"></param>
/// <param name="stationID"></param>
/// <param name="id"></param>
/// <returns></returns>
public static ReturnResult<object> GetTestLogDetails(int projectID, int stationID, int id)
{
ReturnResult<object> result = new ReturnResult<object>();
string connectionString = Users.GerOnUserCofin();
using (MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString))
{
System.Data.DataSet dataSet = new System.Data.DataSet();
try
{
connection.Open();
MySql.Data.MySqlClient.MySqlDataAdapter command = new MySql.Data.MySqlClient.MySqlDataAdapter();
var forIDdbTableName = string.Format(TestLogTbName, projectID, stationID);
var strSql = "SELECT * FROM `" + forIDdbTableName + "` WHERE ID=" + id;
command = new MySql.Data.MySqlClient.MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow Row in dataSet.Tables[0].Rows)//循环行
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(dataSet.Tables[0].Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);
}
result.Data = rows;
result.Status = 200;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
//throw new Exception(ex.Message);
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
}
return result;
}
public static ReturnResult<object> GetTestLogDateList(RequestTestLogDateSearch reqModel, List<TBL_Project> cacheUserProject, List<TBL_StationList> cacheUserStation)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
if (reqModel.StartDate == null && reqModel.EndDate == null)
{
result.Message = "请选择日期";
return result;
}
var project = cacheUserProject.SingleOrDefault(x => x.ID == reqModel.ProjectID);
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
//第一站工作站
var station = cacheUserStation.Where(x => x.ProjectID == reqModel.ProjectID).OrderBy(o => o.ArtworkOrder).FirstOrDefault();//当前选择的工艺站
if (station == null)
{
result.Message = "当前机型无测试站";
return result;
}
var vModel = new ResponseEveryDate();
var dataList = new List<DataQuerySearch>();
var listCount = 0;
var page = reqModel.page;
var pagesize = reqModel.pagesize;
var dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, station.ID);//查询表名
var startDataTime = (reqModel.StartDate ?? DateTime.Now).ToString("yyyy-MM-dd 00:00:00");//开始时间
var endDataTime = (reqModel.EndDate ?? DateTime.Now).AddDays(1).ToString("yyyy-MM-dd 00:00:00");//结束时间
var strWhereStr = "";
if (reqModel.StartDate != null)
{
if (reqModel.EndDate != null)
{
strWhereStr += string.Format(" (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') >='{0}')", startDataTime);
strWhereStr += string.Format(" AND (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') <'{0}')", endDataTime);
}
else
{
strWhereStr += (string.Format("TO_DAYS('{0}')=TO_DAYS(StartTime)", startDataTime));
}
}
else
{
strWhereStr += (string.Format("TO_DAYS('{0}')=TO_DAYS(StartTime)", endDataTime));
}
string connectionString = Users.GerOnUserCofin();
var dalHelperCustom = new DALHelperCustom<DataQuerySearch>();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = "select count(*) from `" + dbTableName + "` WHERE " + strWhereStr + ";";
var obj = cmd.ExecuteScalar();
if (!(Object.Equals(obj, null)) && !(Object.Equals(obj, System.DBNull.Value)))
{
listCount = int.Parse(obj.ToString());
}
}
MySqlDataAdapter command = new MySqlDataAdapter();
var sqlStr = "SELECT ID,StartTime,TestResult,DUT_SN FROM " + dbTableName + " WHERE " + strWhereStr + " order by ID desc LIMIT " + (page - 1) * pagesize + "," + pagesize + ";";
command = new MySqlDataAdapter(sqlStr, connection);
command.Fill(dataSet, "ds");
var thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]);
foreach (var data in thisDataList)
{
dataList.Add(new DataQuerySearch
{
ID = data.ID,
StartTime = data.StartTime == null ? "" : data.StartTime,
TestResult = data.TestResult,
StationName = station.StationName,
StationID = station.ID,
ProjectID = reqModel.ProjectID,
DUT_SN = data.DUT_SN,
});
}
}
vModel.DataList = dataList;
vModel.TotalCount = listCount;
result.Data = vModel;
result.Status = 200;
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
/// <summary>
/// 抽检
/// </summary>
/// <param name="reqModel"></param>
/// <param name="cacheUserProject"></param>
/// <param name="cacheUserStation"></param>
/// <returns></returns>
public static ReturnResult<object> QualityAssuranceAjax(RequestQAAjaxSearch reqModel, List<TBL_Project> cacheUserProject, List<TBL_StationList> cacheUserStation)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
#region
var project = cacheUserProject.SingleOrDefault(x => x.ID == reqModel.ProjectID);
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
var qaStation = cacheUserStation.FirstOrDefault(x => x.ProjectID == reqModel.ProjectID && x.StationType == StationType.QA.GetEnumDesc());
if (qaStation == null)
{
result.Message = "该机型暂无QA站";
return result;
}
if (string.IsNullOrEmpty(reqModel.Number))
{
result.Message = "请输入条码号";
return result;
}
#endregion
string dbTableName;
var checkResult = true;
var strCheckProcList = new List<string>();//条件语句列表
var rdata = new ResponseQAAjaxSearch();
var qaResultVM = new QAResultVM();
var dataList = new List<QADataSearch>();
#region
//QA之外的站
var stationList = cacheUserStation.Where(x => x.ProjectID == reqModel.ProjectID && x.StationType != StationType.QA.GetEnumDesc()).OrderBy(o => o.ArtworkOrder).Select(s => new TBL_Station { StationID = s.ID, StationName = s.StationName, StationType = s.StationType }).ToList();
var maxAssemblySn = reqModel.Number.Trim();//最大组合编号
var assemPrList = stationList.Where(x => x.StationType == StationType.Assem.GetEnumDesc()).OrderByDescending(x => x.ArtworkOrder).ToList();//组装站列表
#endregion
#region
string connectionString = Users.GerOnUserCofin();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
try
{
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter();
var strSql = "";
foreach (var assemPr in assemPrList)
{
dataSet.Reset();
//dataSet.Clear();
dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, assemPr.StationID);
strSql = "select AssemblySn from " + dbTableName + " Where locate('," + reqModel.Number.Trim() + ",',CONCAT(',',AssemblySn,','));";
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
maxAssemblySn = dataSet.Tables[0].Rows[0]["AssemblySn"].ToString();
break;
}
}
StringBuilder strSqlSB = new StringBuilder();
var dalHelperCustom = new DALHelperCustom<QADataSearch>();
var thisDataList = new List<QADataSearch>();
foreach (var item in stationList)
{
dataSet.Reset();
//dataSet.Clear();
thisDataList = null;
strSqlSB.Remove(0, strSqlSB.Length);//移除
dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, item.StationID);
if (item.StationType == StationType.Test2.GetEnumDesc())
{
strSqlSB.Append("SELECT DateTime_2nd as StartTime,TestResult,DUT_SN FROM " + dbTableName);
strSqlSB.Append(" WHERE locate(CONCAT(',',DUT_SN,','),'," + maxAssemblySn + ",')");
strSqlSB.Append(" ORDER BY StartTime DESC LIMIT 1;");
}
else
{
strSqlSB.Append("SELECT StartTime,TestResult,DUT_SN FROM " + dbTableName);
strSqlSB.Append(" WHERE locate(CONCAT(',',DUT_SN,','),'," + maxAssemblySn + ",')");
strSqlSB.Append(" ORDER BY StartTime DESC LIMIT 1;");
}
command = new MySqlDataAdapter(strSqlSB.ToString(), connection);
command.Fill(dataSet, "ds");
thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]);
if (thisDataList.Where(x => !x.TestResult).Count() > 0 || thisDataList.Where(x => x.TestResult).Count() == 0)
{
checkResult = false;
}
foreach (var data in thisDataList)
{
dataList.Add(new QADataSearch
{
StationID = item.StationID,
StartTime = data.StartTime == null ? "" : data.StartTime,
TestResult = data.TestResult,
StationName = item.StationName,
});
strCheckProcList.Add(item.StationName + ":" + data.TestResult + " - " + data.StartTime);
}
}
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
}
#endregion
qaResultVM.ProductNumbers = maxAssemblySn;
qaResultVM.TestResult = checkResult;
qaResultVM.CheckProc = string.Join("<br>", strCheckProcList.ToArray());
qaResultVM.ProjectID = reqModel.ProjectID;
qaResultVM.QAStationID = qaStation.ID;
rdata.qaResultVM = qaResultVM;
rdata.QADataSearchList = dataList;
result.Data = rdata;
result.Status = 200;
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
public static ReturnResult<object> QualityAssuranceSubmit(RequestQASubmit reqModel, int uesrID)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var total = 0;
var totalToday = 0;
int rows = 0;
var data = new ResponseQASubmit();
var entity = new TBL_QA_TestLog
{
UserID = uesrID,
StartTime = DateTime.Now,
DUT_SN = reqModel.NumberSubmit,
TestResult = reqModel.QA_TestResultSubmit,
QA_FlowLog = reqModel.QA_CheckProcSubmit
};
if (reqModel.QA_TestResultSubmit)
{
entity.QA_CheckResult = "OK";
}
else
{
entity.QA_CheckResult = "NG";
}
if (!string.IsNullOrEmpty(reqModel.QARemarks))
{
entity.QA_CheckResult += ":" + reqModel.QARemarks;
}
var dbTableName = string.Format(TestLogTbName, reqModel.QA_ProjectID, reqModel.QA_QAStationID);
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into " + dbTableName + "(");
PropertyInfo[] propertys = entity.GetType().GetProperties();// 获得此模型的公共属性
List<MySqlParameter> parameters = new List<MySqlParameter>();
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append(pi.Name + ",");
}
strSql.Remove(strSql.Length - 1, 1);//移除最后一个逗号
strSql.Append(" ) values (");
foreach (PropertyInfo pi in propertys)
{
if (!pi.CanWrite) continue;
strSql.Append("@" + pi.Name + ",");
parameters.Add(new MySqlParameter("@" + pi.Name, pi.GetValue(entity)));
}
strSql.Remove(strSql.Length - 1, 1);//移除最后一个逗号
strSql.Append(");select @@IDENTITY");
string connectionString = Services.Manager.Users.GerOnUserCofin();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
try
{
if (connection.State != ConnectionState.Open)
connection.Open();
cmd.Connection = connection;
cmd.CommandText = strSql.ToString();
cmd.CommandType = CommandType.Text;//cmdType;
if (parameters.ToArray() != null)
{
foreach (MySqlParameter parameter in parameters.ToArray())
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "select COUNT(*) FROM " + dbTableName;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
}
else
{
total = int.Parse(obj.ToString());
}
cmd.CommandText = "select COUNT(*) FROM " + dbTableName + " WHERE TO_DAYS('" + DateTime.Now.ToString("yyyy-MM-dd 00:00:00") + "')=TO_DAYS(StartTime)";
obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
}
else
{
totalToday = int.Parse(obj.ToString());
}
}
catch (MySqlException e)
{
result.Message = e.Message;
}
}
}
data.Total = total;
data.TotalToday = totalToday;
result.Data = data;
if (rows > 0)
{
result.Status = 200;
}
//var isSuccess = false;
//isSuccess = new DALHelperCustom<TBL_QA_TestLog>(dbTableName).Add(entity);
//if (isSuccess)
//{
// result.Status = 200;
//}
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
/// <summary>
/// 抽检记录查询
/// </summary>
/// <param name="reqModel"></param>
/// <param name="cacheUserProject"></param>
/// <param name="cacheUserStation"></param>
/// <returns></returns>
public static ReturnResult<object> QALogSearch(RequestQALogSearch reqModel, List<TBL_Project> cacheUserProject, List<TBL_StationList> cacheUserStation)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var project = cacheUserProject.SingleOrDefault(x => x.ID == reqModel.ProjectID);
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
//取QA站ID
var qaStation = cacheUserStation.FirstOrDefault(x => x.ProjectID == reqModel.ProjectID && x.StationType == StationType.QA.GetEnumDesc());
if (qaStation == null)
{
result.Message = "该机型暂无QA站";
return result;
}
var dataList = new List<ResponseQALogSearch>();
var strWhereList = new List<string>();//条件语句列表
var startDataTime = (reqModel.StartDate ?? DateTime.Now).ToString("yyyy-MM-dd 00:00:00");//开始时间
var endDataTime = (reqModel.EndDate ?? DateTime.Now).AddDays(1).ToString("yyyy-MM-dd 00:00:00");//结束时间
//时间
if (reqModel.StartDate != null)
{
if (reqModel.EndDate != null)
{
if (reqModel.StartDate > reqModel.EndDate)
{
throw new CustomException("结束时间必须早于开始时间");
}
strWhereList.Add(string.Format("(DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') >='{0}')", startDataTime));
strWhereList.Add(string.Format("(DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') <='{0}')", endDataTime));
}
else
{
strWhereList.Add(string.Format("TO_DAYS('{0}')=TO_DAYS(StartTime)", startDataTime));
}
}
else
{
if (reqModel.EndDate != null)
{
strWhereList.Add(string.Format("TO_DAYS('{0}')=TO_DAYS(StartTime)", endDataTime));
}
}
string strWhere = "";
if (strWhereList.Count > 0)
{
strWhere = " where " + string.Join(" AND ", strWhereList.ToArray()) + ";";
}
string connectionString = Users.GerOnUserCofin();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
try
{
StringBuilder strSql = new StringBuilder();
connection.Open();
var dbTableName = string.Format(TestLogTbName, reqModel.ProjectID, qaStation.ID);
strSql.Append("select * from " + dbTableName);
if (!string.IsNullOrEmpty(strWhere))
{
strSql.Append(strWhere);
}
MySqlDataAdapter command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
var onQALogDataList = new DALHelperCustom<ResponseQALogSearch>().DataRowToModels(dataSet.Tables[0]);
foreach (var data in onQALogDataList)
{
dataList.Add(new ResponseQALogSearch
{
StartTime = data.StartTime == null ? "" : data.StartTime,
QA_CheckResult = data.QA_CheckResult,
DUT_SN = data.DUT_SN,
});
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
//throw new Exception(ex.Message);
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
result.Data = dataList;
result.Status = 200;
}
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
public static ReturnResult<object> EveryDaySearch(int pid, int oid, List<TBL_Project> cacheUserProject, List<TBL_StationList> cacheUserStation, List<TBL_Orders> cacheUserOrder, string connectionString)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var project = cacheUserProject.SingleOrDefault(x => x.ID == pid);
if (project == null)
{
result.Message = "无效或不存在的机型";
return result;
}
var order = cacheUserOrder.SingleOrDefault(x => x.ProductID == pid && x.ID == oid);
if (order == null)
{
result.Message = "无效或不存在的订单";
return result;
}
var resModel = new ResponseEveryDaySearch
{
ProjectName = project.ProjectName,
OrderNo = order.OrderNo,
OrderCount = order.OrderCount,
CreateTime = order.CreateTime.ToString("yyyy/MM/dd"),
DeliveryTime = order.DeliveryTime.ToString("yyyy/MM/dd"),
};
var stationList = cacheUserStation.Where(x => x.StationType != StationType.QA.GetEnumDesc() && x.ProjectID == order.ProductID).OrderBy(o => o.ArtworkOrder);//不为该机型QA的测试站
DataTable tblDatas = new DataTable("Datas");
var strSql = "";
var dbTableName = "";
var dalHelperCustom = new DALHelperCustom<VM_TBL_CapacityEveryDay>();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
var minTime = Convert.ToDateTime(order.CreateTime.ToString("yyyy/MM/dd"));//订单最早日期
var maxTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd"));//订单最晚日期
DataSet dataSet = new DataSet();
MySqlDataAdapter command = new MySqlDataAdapter();
connection.Open();
strSql = "SELECT * FROM `TBL_ProductionPlan` WHERE OrderID=" + order.ID + " ORDER BY ProductionTime LIMIT 0,1;";
command = new MySqlDataAdapter(strSql, connection);
command.Fill(dataSet, "ds");
var ppList = new DALHelperCustom<TBL_ProductionPlan>().DataRowToModels(dataSet.Tables[0]);
if (ppList != null && ppList.Count() > 0)
{
minTime = ppList.First().ProductionTime;
}
TimeSpan ts = maxTime.Subtract(minTime);
int differenceInDays = ts.Days + 1;
tblDatas.Columns.Add("测试站", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数据", Type.GetType("System.String"));//新列
for (var i = 0; i < differenceInDays; i++)
{
tblDatas.Columns.Add(minTime.AddDays(i).ToString("yyyy/MM/dd"), Type.GetType("System.String"));//新列
}
foreach (var itemStation in stationList)
{
strSql = "";
dataSet.Clear();
dbTableName = string.Format(TestLogTbName, itemStation.ProjectID, itemStation.ID);//测试站表名
DataRow totalRow = tblDatas.NewRow();//总数据行
totalRow["测试站"] = itemStation.StationName;
totalRow["数据"] = "总数";
DataRow effRow = tblDatas.NewRow();//有效数行
effRow["测试站"] = itemStation.StationName;
effRow["数据"] = "有效";
DataRow passRow = tblDatas.NewRow();//PASS行
passRow["测试站"] = itemStation.StationName;
passRow["数据"] = "PASS";
DataRow fallRow = tblDatas.NewRow();//FALL行
fallRow["测试站"] = itemStation.StationName;
fallRow["数据"] = "FALL";
strSql = "select DUT_SN,TestResult,StartTime from `" + dbTableName + "` Where OrderID=" + oid;//查询语句
strSql += (string.Format(" AND (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') >='{0}')", minTime.ToString("yyyy-MM-dd hh:mm:ss")));
strSql += (string.Format(" AND (DATE_FORMAT(StartTime, '%Y-%m-%d %H:%i:%s') <='{0}')", maxTime.ToString("yyyy-MM-dd hh:mm:ss")));
strSql += ";";
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
var thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]).Select(s => new { StartTime = s.StartTime.ToString("yyyy/MM/dd"), s.TestResult, s.DUT_SN, DataTime = s.StartTime });
var dataListGroup = thisDataList.GroupBy(x => x.StartTime).OrderBy(o => o.Key);
foreach (var itemG in dataListGroup)
{
totalRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key).Count();
effRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key).GroupBy(g => g.DUT_SN).Count();
//passRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key && x.TestResult).Count();
//fallRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key && !x.TestResult).Count();
passRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key).GroupBy(s => s.DUT_SN)
.Select(s => s.OrderByDescending(o => o.DataTime).FirstOrDefault()).Where(x => x.TestResult).Count();
fallRow[itemG.Key] = thisDataList.Where(x => x.StartTime == itemG.Key).GroupBy(s => s.DUT_SN)
.Select(s => s.OrderByDescending(o => o.DataTime).FirstOrDefault()).Where(x => !x.TestResult).Count();
}
}
tblDatas.Rows.Add(totalRow);
tblDatas.Rows.Add(effRow);
tblDatas.Rows.Add(passRow);
tblDatas.Rows.Add(fallRow);
}
}
var rows = ModelHelper.TableToRow(tblDatas);
resModel.Rows = rows;
result.Data = resModel;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
catch (CustomException ex)
{
result.Message = ex.Message;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return result;
}
}
}

View File

@@ -0,0 +1,30 @@
using AUTS.Domain.Entities;
using AUTS.Services.Cache;
using AUTS.Services.Tool;
using System.Linq;
namespace AUTS.Services.Manager
{
public partial class ChartsDatas
{
private static readonly string sysDBListKey = "sysManage_DBList";//库列表
public static void UpdateSetCacheOfDBList()
{
var dbList = CacheHelp.GetSysDBList();
using (var db = new Uts_ManageEntities())
{
//所有
var count = db.TBL_UTS_Manage_DBList.Count();
if (count > dbList.Count)
{
var ids = "," + string.Join(",", dbList.Select(s => s.ID).ToArray()) + ",";
var addlist = db.TBL_UTS_Manage_DBList.ToList();
RedisHelper.StringSet(sysDBListKey, addlist);
}
}
}
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public class Home
{
/// <summary>
/// 已确认
/// </summary>
public int confirm { get; set; }
/// <summary>
/// 生产中
/// </summary>
public int yield { get; set; }
/// <summary>
/// 已完成
/// </summary>
public int accomplish { get; set; }
}
}

View File

@@ -0,0 +1,328 @@
using AUTS.Services.Tool;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
namespace AUTS.Services.Manager
{
/// <summary>
/// 日志类
/// </summary>
public partial class Logs
{
/// <summary>
/// 锁1 路径/App_Data/Log/
/// </summary>
private static readonly object _lock = new object();
/// <summary>
/// 锁2 路径/App_Data/TimingPlan/
/// </summary>
private static readonly object _lock1 = new object();
/// <summary>
/// 锁3 路径/App_Data/UDPlog/
/// </summary>
private static readonly object _lockUdp = new object();
public static void WriteErrorLog(Exception ex)
{
try
{
if (ex != null)
{
string content = "类型:错误代码\r\n";
content += "时间:" + DateTime.Now.ToString() + "\r\n";
content += "来源:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "内容:" + ex.Message + "\r\n";
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
}
catch (Exception)
{
throw;
}
}
public static void WriteLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志\r\n";
content += "时间:" + DateTime.Now.ToString() + "\r\n";
content += "内容:" + msg + "\r\n";
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
}
catch (Exception)
{
throw;
}
}
public static void WriteErrorLog(string errsrc, Exception ex)
{
try
{
string errtxt = "";
string exname = ex.GetType().ToString();
if (exname == "System.Data.Entity.Validation.DbEntityValidationException")
{
foreach (var item in ((DbEntityValidationException)ex).EntityValidationErrors)
{
foreach (var err in item.ValidationErrors)
{
errtxt += "EntityValidationErrors >>>>>> “" + err.PropertyName + "”字段" + err.ErrorMessage + "\r\n";
}
}
}
string content = (!string.IsNullOrEmpty(errsrc) ? "来自页面:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n" + errtxt;
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
//if (BaseConfigs.GetLogInDB == 1)
//{
//TSysLog log = new TSysLog();
//log.Content = content;
//log.Type = "系统日志";
//log.CreateTime = DateTime.Now;
//DataAccess.CreateSysLog().Add(log);
//}
//if (BaseConfigs.GetLogInFile == 1)
//{
Page page = new Page();
HttpServerUtility server = page.Server;
string dir = server.MapPath("/App_Data/Log/");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter FileWriter = new StreamWriter(path, true, System.Text.Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
//}
}
catch (Exception)
{
throw;
}
}
public static void WriteTimingPlanLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志 ";
content += "时间:" + DateTime.Now.ToString() + " ";
content += "内容:" + msg + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/TimingPlan/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lock1)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
//FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
public static void WriteErrorTimingPlanLog(string errsrc, Exception ex)
{
try
{
if (ex != null)
{
string content = (!string.IsNullOrEmpty(errsrc) ? "来自作业线程:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n";
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/TimingPlan/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lock1)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception exl)
{
LogHelp.WriteExceptionLog(ex);
LogHelp.WriteExceptionLog(exl);
}
}
public static void WriteTimingUDPLog(string msg)
{
try
{
if (!string.IsNullOrEmpty(msg))
{
string content = "类型:调试日志 ";
content += "时间:" + DateTime.Now.ToString() + " ";
content += "内容:" + msg + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/UDPLog/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lockUdp)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
//FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
}
}
public static void WriteErrorTimingUDPLog(string errsrc, Exception ex)
{
try
{
if (ex != null)
{
string content = (!string.IsNullOrEmpty(errsrc) ? "来自作业线程:" + errsrc : "") + "\r\n";
content += "发生时间:" + DateTime.Now.ToString() + "\r\n";
content += "异常对像:" + ex.TargetSite.ReflectedType.ToString() + "." + ex.TargetSite.Name + "\r\n";
content += "错误追踪:" + ex.StackTrace + "\r\n";
content += "错误提示:" + ex.Message + "\r\n";
if (ex.InnerException != null && ex.InnerException.InnerException != null)
content += ex.InnerException.InnerException.Message + "\r\n";
string dir = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/UDPLog/";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path = dir + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
lock (_lockUdp)
{
StreamWriter FileWriter = new StreamWriter(path, true, Encoding.UTF8); //创建日志文件
FileWriter.Write("---------------------------------------------------\r\n");
FileWriter.Write(content);
FileWriter.Close(); //关闭StreamWriter对象
}
}
}
catch (Exception exl)
{
LogHelp.WriteExceptionLog(ex);
LogHelp.WriteExceptionLog(exl);
}
}
}
public static class LogHelp
{
/// <summary>
/// 写入日志
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="operationer">操作人</param>
/// <param name="actionName">功能站点名称</param>
public static void WriteExceptionLog(Exception ex, string actionName = "", string operationer = "")
{
if (HttpContext.Current == null)
{
Log4Net.ExceptionLogHelper.Log(new AUTS.Log4Net.ExceptionLogMessage() { ActionName = actionName, exception = ex, Header = "", Url = "线程", Operationer = "线程", IP = "" });
}
else
{
Log4Net.ExceptionLogHelper.Log(new AUTS.Log4Net.ExceptionLogMessage() { ActionName = actionName, exception = ex, Header = HttpContext.Current.Request.Headers.ToString(), Url = HttpContext.Current.Request.Url.ToString(), Operationer = operationer, IP = IPHelper.GetIP() });
}
}
}
}

View File

@@ -0,0 +1,226 @@
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.DBUtility.Custom;
using AUTS.Services.Enums;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public partial class Orders
{
private static string TestLogTbName = "TBL_{0}_{1}_TestLog";//测试记录表名
public static ReturnResult<object> GetOrdersPlannedSpeed(List<TBL_Project> cacheUserProject, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var orderNotList = cacheUserOrder.Where(x => x.OrderStatus == 1);//取出未完成订单
var minTime = orderNotList.Min(m => m.CreateTime);//订单最早日期
var maxTime = DateTime.Now;//订单最晚日期
minTime = Convert.ToDateTime(minTime.ToString("yyyy/MM/dd"));//订单最早日期
maxTime = Convert.ToDateTime(maxTime.ToString("yyyy/MM/dd"));//订单最晚日期
TimeSpan ts = maxTime - minTime;
int differenceInDays = ts.Days + 1;
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("ID", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("单号", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("机型", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("客户", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数量", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("已完成", Type.GetType("System.String"));//新列
for (var i = 0; i < differenceInDays; i++)
{
tblDatas.Columns.Add(minTime.AddDays(i).ToString("yy/MM/dd"), Type.GetType("System.String"));//新列
}
var dbTableName = "";
var sumTotal = 0;
var dalHelperCustom = new DALHelperCustom<VM_PlannedSpeed>();
var thisDataList = new List<VM_PlannedSpeed>();
string connectionString = Users.GerOnUserCofin();//当前库连接串
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
MySqlDataAdapter command = new MySqlDataAdapter();
var strSql = "";
foreach (var item in orderNotList)
{
strSql = "";
dataSet.Clear();
sumTotal = 0;
DataRow newRow = tblDatas.NewRow();//新行
newRow["ID"] = item.ID;
newRow["单号"] = item.OrderNo;
newRow["机型"] = cacheUserProject.Single(x => x.ID == item.ProductID).ProjectName;
newRow["客户"] = cacheUserCustomer.Single(x => x.ID == item.CompanyID).CustomerAbbr;
newRow["数量"] = item.OrderCount;
var endTestStationID = cacheUserStationList.Where(x => x.ProjectID == item.ProductID && x.StationType == StationType.Test.GetEnumDesc()).Max(m => m.ID);//最大测试站
dbTableName = string.Format(TestLogTbName, item.ProductID, endTestStationID);//最大测试站表名
strSql = "select StartTime,DATE_FORMAT(StartTime,'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where OrderID=" + item.ID + " AND TestResult=1 GROUP BY DAYS;";//查询语句
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]);
foreach (var itemData in thisDataList)
{
//tblDatas.Rows[rowKey][itemData.CreateTime.ToString("yyyy/MM/dd")] = itemData.Total;
newRow[itemData.StartTime.ToString("yy/MM/dd")] = itemData.Total;
sumTotal += itemData.Total;
}
}
newRow["已完成"] = sumTotal;
tblDatas.Rows.Add(newRow);
}
}
var rows = ModelHelper.TableToRow(tblDatas);
result.Data = rows;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
public static ReturnResult<object> GetOrdersPlannedSpeedDetails(int id, List<TBL_Project> cacheUserProject, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList, string connectionString)
{
ReturnResult<object> result = new ReturnResult<object>();
try
{
var order = cacheUserOrder.Single(x => x.ID == id);//取出订单
var stationList = cacheUserStationList.Where(x => x.StationType != StationType.QA.GetEnumDesc() && x.ProjectID == order.ProductID);//不为该机型QA的测试站
var minTime = order.CreateTime;//订单最早日期
var maxTime = DateTime.Now;//订单最晚日期
minTime = Convert.ToDateTime(minTime.ToString("yyyy/MM/dd"));//订单最早日期
maxTime = Convert.ToDateTime(maxTime.ToString("yyyy/MM/dd"));//订单最晚日期
TimeSpan ts = maxTime - minTime;
int differenceInDays = ts.Days + 1;
DataTable tblDatas = new DataTable("Datas");
tblDatas.Columns.Add("测试站", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数量", Type.GetType("System.String"));//新列
for (var i = 0; i < differenceInDays; i++)
{
tblDatas.Columns.Add(minTime.AddDays(i).ToString("yy/MM/dd"), Type.GetType("System.String"));//新列
}
var dbTableName = "";
var strSql = "";
var sumTotal = 0;
var dalHelperCustom = new DALHelperCustom<VM_PlannedSpeed>();
//string connectionString = Users.GerOnUserCofin();//当前库连接串
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
MySqlDataAdapter command = new MySqlDataAdapter();
connection.Open();
//测试站列表
foreach (var itemStation in stationList)
{
strSql = "";
sumTotal = 0;
dataSet.Clear();
DataRow newRow = tblDatas.NewRow();//新行
newRow["测试站"] = itemStation.StationName;
newRow["数量"] = "当日";
DataRow newRow2 = tblDatas.NewRow();//新行
newRow2["测试站"] = itemStation.StationName;
newRow2["数量"] = "累计";
dbTableName = string.Format(TestLogTbName, itemStation.ProjectID, itemStation.ID);//测试站表名
strSql = "select StartTime,DATE_FORMAT(StartTime,'%Y%m%d') DAYS,COUNT(*) Total from `" + dbTableName + "` Where OrderID=" + id + " AND TestResult=1 GROUP BY DAYS;";//查询语句
command = new MySqlDataAdapter(strSql.ToString(), connection);
command.Fill(dataSet, "ds");
if (dataSet.Tables[0].Rows.Count > 0)
{
var thisDataList = dalHelperCustom.DataRowToModels(dataSet.Tables[0]).OrderBy(x => x.StartTime);
foreach (var itemData in thisDataList)
{
newRow[itemData.StartTime.ToString("yy/MM/dd")] = itemData.Total;
sumTotal += itemData.Total;
newRow2[itemData.StartTime.ToString("yy/MM/dd")] = sumTotal;
}
}
tblDatas.Rows.Add(newRow);
tblDatas.Rows.Add(newRow2);
}
}
var rows = ModelHelper.TableToRow(tblDatas);
result.Data = rows;
result.Status = 200;
}
catch (MySqlException ex)
{
result.Message = ex.Message;
Logs.WriteErrorLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
}
}

View File

@@ -0,0 +1,300 @@
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.DBUtility.Custom;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public partial class PPlans
{
/// <summary>
/// 内部单记录详情
/// </summary>
/// <param name="id">内部单ID</param>
/// <param name="cacheUserProject">机型缓存</param>
/// <param name="cacheUserOrderInternal">内部单缓存</param>
/// <param name="cacheUserOrder">订单缓存</param>
/// <param name="cacheUserCustomer">客户缓存</param>
/// <returns></returns>
public static VM_TBL_PPlanInternalDetails GetPPlanInternalDetails(int id, List<TBL_Project> cacheUserProject, List<TBL_OrderInternal> cacheUserOrderInternal, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer)
{
var vmodel = new VM_TBL_PPlanInternalDetails();
var orderInternalModel = cacheUserOrderInternal.Single(x => x.ID == id);//内部单
var orderModel = cacheUserOrder.Single(x => x.ID == orderInternalModel.OrderID);//订单
var project = cacheUserProject.Single(x => x.ID == orderModel.ProductID);//机型
var customer = cacheUserCustomer.Single(x => x.ID == orderModel.CompanyID);//客户
vmodel.ID = orderInternalModel.ID;
vmodel.OrderNo = orderModel.OrderNo;
vmodel.InternalNo = orderInternalModel.InternalNo;
vmodel.ProjectName = project.ProjectName;
vmodel.CustomerAbbr = customer.CustomerAbbr;
vmodel.DeliveryTime = orderModel.DeliveryTime;
var pPlanList = new DALHelperCustom<VM_TBL_PPlan>("TBL_ProductionPlan").GetList("OrderInternalID=" + id);
vmodel.PPlanList = pPlanList;
return vmodel;
}
public static ReturnResult<object> GetPPlanInternalDetails_New(int id, List<TBL_Project> cacheUserProject, List<TBL_OrderInternal> cacheUserOrderInternal, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList)
{
ReturnResult<object> result = new ReturnResult<object>();
var vmodel = new VM_TBL_PPlanInternalDetails();
var orderInternalModel = cacheUserOrderInternal.Single(x => x.ID == id);//内部单
var orderModel = cacheUserOrder.Single(x => x.ID == orderInternalModel.OrderID);//订单
var project = cacheUserProject.Single(x => x.ID == orderModel.ProductID);//机型
var customer = cacheUserCustomer.Single(x => x.ID == orderModel.CompanyID);//客户
vmodel.ID = orderInternalModel.ID;
vmodel.OrderNo = orderModel.OrderNo;
vmodel.InternalNo = orderInternalModel.InternalNo;
vmodel.ProjectName = project.ProjectName;
vmodel.CustomerAbbr = customer.CustomerAbbr;
vmodel.DeliveryTime = orderModel.DeliveryTime;
var pPlanList = new DALHelperCustom<VM_TBL_PPlan>("TBL_ProductionPlan").GetList("OrderInternalID=" + id);//取出当前内部单全部计划
if (pPlanList == null)
{
result.Status = 200;
return result;
}
var timeGroupList = pPlanList.GroupBy(g => g.ProductionTime);//按时间分组
var stationGroupList = pPlanList.GroupBy(g => g.StationID);//按工艺站分组
//var stationIDs = stationGroupList.Select(s => s.Key).ToArray();
var excludedFactionSet = new HashSet<int>(stationGroupList.Select(s => s.Key));//取出ID放入比较器
var stationList = cacheUserStationList.Where(x => excludedFactionSet.Contains(x.ID)).OrderBy(o => o.ArtworkOrder);//按工艺站排序
DataTable tblDatas = new DataTable("Datas");
//DataColumn dc = null;
tblDatas.Columns.Add("站", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("数据", Type.GetType("System.String"));//新列
foreach (var itemStation in stationList)
{
var stationName = cacheUserStationList.Single(x => x.ID == itemStation.ID).StationName;//取站名
//var stationName = cacheUserStationList.Single(x => x.StationID == itemStation.Key).StationName;//取站名
DataRow newRow = tblDatas.NewRow();//新行
newRow["站"] = stationName;
newRow["数据"] = "目标";
tblDatas.Rows.Add(newRow);
DataRow newRow2 = tblDatas.NewRow();
newRow2["站"] = stationName;
newRow2["数据"] = "累计";
tblDatas.Rows.Add(newRow2);
}
var rowKey = 0;
var timeStr = "";
var onPPlan = new VM_TBL_PPlan();
foreach (var item in timeGroupList)
{
timeStr = item.Key.ToString("yyyy/MM/dd");
tblDatas.Columns.Add(timeStr, Type.GetType("System.String"));//新列
rowKey = 0;
foreach (var itemStation in stationGroupList)
{
onPPlan = pPlanList.SingleOrDefault(x => x.ProductionTime == item.Key && x.StationID == itemStation.Key);
tblDatas.Rows[rowKey][timeStr] = onPPlan == null ? "" : onPPlan.ObjectiveYield.ToString();//目标
rowKey += 1;
tblDatas.Rows[rowKey][timeStr] = onPPlan == null ? "" : onPPlan.ObjectiveYieldTotal.ToString();//计划
rowKey += 1;
}
}
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow Row in tblDatas.Rows)//循环行
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(tblDatas.Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);
}
vmodel.rows = rows;
result.Data = vmodel;
result.Status = 200;
return result;
}
public static ReturnResult<object> GetPPlanInternalTable(int id, List<TBL_Project> cacheUserProject, List<TBL_OrderInternal> cacheUserOrderInternal, List<TBL_Orders> cacheUserOrder, List<TBL_Customer> cacheUserCustomer, List<TBL_StationList> cacheUserStationList)
{
ReturnResult<object> result = new ReturnResult<object>();
var vmodel = new VM_TBL_PPlanInternalDetails();
try
{
var orderInternalModel = cacheUserOrderInternal.Single(x => x.ID == id);//内部单
var orderModel = cacheUserOrder.FirstOrDefault(x => x.ID == orderInternalModel.OrderID);//订单
var project = cacheUserProject.FirstOrDefault(x => x.ID == orderInternalModel.ProductID);//机型
var customer = cacheUserCustomer.FirstOrDefault(x => x.ID == orderInternalModel.CompanyID);//客户
vmodel.ID = orderInternalModel.ID;
//vmodel.OrderNo = orderModel.OrderNo;
vmodel.InternalNo = orderInternalModel.InternalNo;
vmodel.ProjectName = project.ProjectName;
vmodel.ProjectID = project.ID;
//vmodel.CustomerAbbr = customer.CustomerAbbr;
//vmodel.DeliveryTimeStr = orderModel.DeliveryTime.ToString("yyyy/MM/dd");
vmodel.OrderCount = orderInternalModel.ObjectiveYield;
var stationList = cacheUserStationList.Where(x => x.ProjectID == orderInternalModel.ProductID).OrderBy(o => o.ArtworkOrder);//按工艺站排序
foreach (var item in stationList)
{
vmodel.StationText += "<strong>" + item.StationName + "</strong>" + "-" + item.StationDesc + "&emsp;";
}
var pPlanList = new DALHelperCustom<VM_TBL_PPlan>("TBL_ProductionPlan").GetList("OrderInternalID=" + id);//取出当前内部单全部计划
if (pPlanList == null)
{
result.Status = 200;
result.Data = vmodel;
return result;
}
var timeGroupList = pPlanList.OrderBy(o => o.ProductionTime).GroupBy(g => g.ProductionTime);//按时间分组
var stationGroupList = pPlanList.GroupBy(g => g.StationID);//按工艺站分组
var excludedFactionSet = new HashSet<int>(stationGroupList.Select(s => s.Key));//取出ID放入比较器
//var stationList = cacheUserStationList.Where(x => excludedFactionSet.Contains(x.StationID)).OrderBy(o => o.ArtworkOrder);//按工艺站排序
DataTable tblDatas = new DataTable("Datas");
//DataColumn dc = null;
tblDatas.Columns.Add("Type", Type.GetType("System.String"));//新列
tblDatas.Columns.Add("Date", Type.GetType("System.String"));//新列
//tblDatas.Columns.Add("DateTime", Type.GetType("System.String"));//新列
//tblDatas.Columns.Add("DataType", Type.GetType("System.String"));//新列
var totalList = new Dictionary<string, int>();
foreach (var itemStation in stationList)
{
var stationName = cacheUserStationList.Single(x => x.ID == itemStation.ID).StationName;//取站名
tblDatas.Columns.Add(stationName, Type.GetType("System.String"));//新列
totalList.Add(stationName, 0);
}
var timeStr = "";
var onPPlan = new VM_TBL_PPlan();
var thisStation = new TBL_StationList();
foreach (var item in timeGroupList)
{
timeStr = item.Key.ToString("yyyy/MM/dd");
//timeStr = item.Key.ToString("yyyy/MM/dd");
DataRow newRow = tblDatas.NewRow();//新行
newRow["Date"] = timeStr;
//newRow["DateTime"] = timeStr + "</br>" + Tool.StringHelp.GetWeek(timeStr.ToDateTime() ?? DateTime.Now);
newRow["Type"] = "ToDay";
//newRow["DataType"] = "今日";
DataRow newRow2 = tblDatas.NewRow();//新行
//newRow2["Date"] = timeStr;
newRow2["Date"] = Tool.StringHelp.GetWeek(timeStr.ToDateTime() ?? DateTime.Now);
//newRow2["DateTime"] = timeStr + "</br>" + Tool.StringHelp.GetWeek(timeStr.ToDateTime() ?? DateTime.Now);
newRow2["Type"] = "Total";
//newRow2["DataType"] = "累计";
foreach (var itemStation in stationGroupList)
{
thisStation = stationList.Single(x => x.ID == itemStation.Key);
onPPlan = pPlanList.SingleOrDefault(x => x.ProductionTime == item.Key && x.StationID == itemStation.Key);//计划表对象
if (onPPlan != null && onPPlan.ObjectiveYield > 0)
{
newRow[thisStation.StationName] = onPPlan == null ? 0 : onPPlan.ObjectiveYield;//目标;
//newRow2[thisStation.StationName] = (tblDatas.AsEnumerable().Select(d => Convert.ToDouble(d.Field<string>(thisStation.StationName))).Sum()) / 2 + (onPPlan == null ? 0 : onPPlan.ObjectiveYield);
//newRow2[thisStation.StationName] = onPPlan.ObjectiveYieldTotal;
totalList[thisStation.StationName] += onPPlan.ObjectiveYield;
newRow2[thisStation.StationName] = totalList[thisStation.StationName];
}
//else
//{
// newRow[thisStation.StationName] = 0;//目标;
// newRow2[thisStation.StationName] = 0;
//}
}
tblDatas.Rows.Add(newRow);
tblDatas.Rows.Add(newRow2);
//rowKey = 0;
//foreach (var itemStation in stationGroupList)
//{
// onPPlan = pPlanList.SingleOrDefault(x => x.ProductionTime == item.Key && x.StationID == itemStation.Key);
// tblDatas.Rows[rowKey][timeStr] = onPPlan == null ? "" : onPPlan.ObjectiveYield.ToString();//目标
// rowKey += 1;
// tblDatas.Rows[rowKey][timeStr] = onPPlan == null ? "" : onPPlan.ObjectiveYieldTotal.ToString();//计划
// rowKey += 1;
//}
}
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow Row in tblDatas.Rows)//循环行
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(tblDatas.Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);
}
vmodel.rows = rows;
result.Data = vmodel;
result.Status = 200;
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
LogHelp.WriteExceptionLog(ex);
}
return result;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public partial class TestLog
{
private static string TestLogTbName = "TBL_{0}_{1}_TestLog";//测试记录表名
public static ReturnResult<object> GetStation(int ProductID,List<TBL_StationList> stationLists,List<TBL_Project> projects)
{
ReturnResult<object> res = new ReturnResult<object>();
var oIStation = new List<VM_OrderInternalStations>();
try
{
var entity = stationLists.Where(e => e.ProjectID == ProductID && e.IsValid == 1).ToList();
foreach (var item in entity)
{
oIStation.Add(new VM_OrderInternalStations()
{
ID = item.ID,
StationDesc = item.StationDesc,
StationName = item.StationName
});
}
res.Message = projects.FirstOrDefault(e => e.ID == ProductID).ProjectName;
res.Data = oIStation;
res.Status = 200;
}
catch (Exception ex)
{
res.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return res;
}
}
}

View File

@@ -0,0 +1,143 @@
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Manager
{
public partial class TestLogs
{
private static string TestLogTbName = "TBL_{0}_{1}_TestLog";//测试记录表名
public static ReturnResult<List< VM_OrderInternalStations>> GetStation(int ProductID, List<TBL_StationList> stationLists, List<TBL_Project> projects)
{
ReturnResult<List<VM_OrderInternalStations>> res = new ReturnResult<List<VM_OrderInternalStations>>();
var oIStation = new List<VM_OrderInternalStations>();
try
{
var entity = stationLists.Where(e => e.ProjectID == ProductID && e.IsValid == 1).OrderBy(x => x.SnListOrder).ToList();
foreach (var item in entity)
{
oIStation.Add(new VM_OrderInternalStations()
{
ID = item.ID,
StationDesc = item.StationDesc,
StationName = item.StationName
});
}
res.Message = projects.FirstOrDefault(e => e.ID == ProductID).ProjectName;
res.Data = oIStation;
res.Status = 200;
}
catch (Exception ex)
{
res.Message = "网络系统繁忙,请稍候再试!";
Logs.WriteErrorLog(ex);
}
return res;
}
/// <summary>
/// 获取当前用户选择的库的下面的所有设备信息
/// </summary>
/// <param name="Id">UID</param>
/// <returns></returns>
public static List<TBL_UTS_Manage_DataServiceList> GetServiceList(int Id)
{
try
{
// 获取当前用户选择的库
var userAuthList = new List<TBL_UTS_Manage_DBList> { Manager.Users.GerOnUserCustomer()};
//获取用户所有的库 CacheHelp.GetUserAuthList().Where(x => x.UserID == Id).ToList();
var CustomerName = new List<string>();
for (int i = 0; i < userAuthList.Count; i++)
{
CustomerName.AddRange(userAuthList[i].DatabaseName.Split(new string[] { "uts_" }, StringSplitOptions.RemoveEmptyEntries));
}
using (var db = new Uts_ManageEntities())
{
var CompanyList = new List<string>();
for (int i = 0; i < CustomerName.Count; i++)
{
string cName = CustomerName[i].ToLower();
var Company = db.TBL_UTS_Manage_Company.FirstOrDefault(e => e.CustomerName.ToLower() == cName);
CompanyList.Add(Company.CustomerName.ToLower());
}
if (CompanyList == null || CompanyList.Count == 0) return null;
List<TBL_UTS_Manage_DataServiceList> data = db.TBL_UTS_Manage_DataServiceList.Where(x => CompanyList.Contains(x.CompanyName.ToLower())).OrderByDescending(x => x.IsOnline).ToList();
return data;
}
}
catch (Exception ex)
{
LogHelp.WriteExceptionLog(ex);
return null;
}
}
public static List<TBL_UTS_Manage_AppList> GetAppList()
{
List<TBL_UTS_Manage_AppList> userList = new List<TBL_UTS_Manage_AppList>();
using (var db = new Uts_ManageEntities())
{
userList = db.TBL_UTS_Manage_AppList.ToList();
}
return userList;
}
/// <summary>
/// 获取选择库下设备信息 及 是否在线
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public static List<TBL_UTS_Manage_DataServiceList> GetServiceAppList(int Id) {
List< TBL_UTS_Manage_DataServiceList> SERVER = GetServiceList(Id).Where(x=>x.ManageStatus==1).ToList();
using (var db = new Uts_ManageEntities())
{
var APP = db.TBL_UTS_Manage_AppList.ToList();
for (int i = 0; i < SERVER.Count; i++)
{
foreach (var item2 in APP)
{
if(item2.ServiceID != SERVER[i].ID) { continue; }
var today = DateTime.Now;
TimeSpan ts;
ts = today - (item2.LastActiveDateTime ?? today);
if (ts.TotalSeconds < 180)
{
SERVER[i].IsOnline = true;
}
else
{
SERVER[i].IsOnline = false;
}
}
}
}
return SERVER.OrderByDescending(x=>x.IsOnline).ToList();
}
//截取字符串
public string JieQu(string str)
{
string str2 = "";
var LtStr = str.Split(',');
int Sum = 2;
for (int i = 0; i <= LtStr.Length; i++)
{
str2 += LtStr[i] + ",";
if (i == Sum - 1)
{
str2 = str2.Substring(0, str2.Length - 1);
break;
}
}
Console.WriteLine(str2);
return str2;
}
}
}

View File

@@ -0,0 +1,93 @@
using AUTS.Domain.Application;
using AUTS.Domain.Entities;
using AUTS.Services.Enums;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace AUTS.Services.Manager
{
public static class UserOperationLog
{
public static void UserLog(string Openration,string Device)
{
try
{
TBL_UTS_UserOperation tBL_UTS_UserOperation = new TBL_UTS_UserOperation();
//获得IP
string ip = string.Empty;
string ipAddr = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddr))
ipAddr = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(ipAddr))
ipAddr = System.Web.HttpContext.Current.Request.UserHostAddress;
ip = ipAddr;
string browserVersions = string.Empty;
HttpBrowserCapabilities hbc = System.Web.HttpContext.Current.Request.Browser;
string browserType = hbc.Browser.ToString(); //获取浏览器类型
string browserVersion = hbc.Version.ToString(); //获取版本号
browserVersions = browserType + browserVersion;
var phone = System.Web.HttpContext.Current.Request.Cookies["phone"];
var PC = System.Web.HttpContext.Current.Request.Cookies["PC"];
tBL_UTS_UserOperation.UserName = Users.Umodel.UserName;
tBL_UTS_UserOperation.Database = "aa";
// Users.GerOnUserCustomer().DatabaseName;
tBL_UTS_UserOperation.Browser = browserVersions;//浏览器
tBL_UTS_UserOperation.Ip = ip;//ip
tBL_UTS_UserOperation.Device = Device;
tBL_UTS_UserOperation.CreationTime = DateTime.Now;//时间
tBL_UTS_UserOperation.Operation = Openration;
tBL_UTS_UserOperation.Location = GetBaiduIp(ip);
SqlConnect.SqlInsertUserLog(tBL_UTS_UserOperation);
}
catch (Exception ex)
{
}
}
/// <summary>
/// 百度api
/// </summary>
/// <returns></returns>
public static string GetBaiduIp(string ip)
{
string location = "";
try
{
string url = $"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={ip}&co=&resource_id=6006&oe=utf8";
WebClient client = new WebClient();
var buffer = client.DownloadData(url);
string jsonText = Encoding.UTF8.GetString(buffer);
JObject jo = JObject.Parse(jsonText);
Root root = JsonConvert.DeserializeObject<Root>(jo.ToString());
foreach (var item in root.data)
{
location = item.location;
}
return location;
}
catch (Exception ex)
{
//Console.WriteLine(ex);
return location;
}
}
}
}

View File

@@ -0,0 +1,283 @@
using AUTS.Domain.Application;
using AUTS.Domain.Entities;
using AUTS.Domain.ViewModels;
using AUTS.Services.Cache;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace AUTS.Services.Manager
{
/// <summary>
/// 用户类
/// </summary>
public partial class Users
{
public static readonly string connectionSrt = "Server =blv-cloud-db.mysql.rds.aliyuncs.com;Database=uts_db;Uid=blv_rcu;Pwd=fnadiaJDIJ7546;charset=utf8;port=3307";
//private static string onUserOperationSessionName = "UserOperationSessionName";//用户当前选择库
#region
private static List<TBL_UTS_Manage_DBList> cacheSysDBList
{
// get选择器获取Lazyk懒加载数据
get { return CacheHelp.GetSysDBList(); }
}
private static List<DBCofinStrModel> cacheSysDBCofinStrList
{
// get选择器获取Lazyk懒加载数据
get { return CacheHelp.GetDBCofinStrList(); }
}
//当前用户
public static TBL_UTS_Manage_User Umodel
{
// get选择器获取Lazyk懒加载数据
get { return UserLoginHelper.CurrentUser(); }
}
#endregion
#region
/// <summary>
/// 获取当前用户权限集合
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static List<TBL_UTS_Manage_UserAuth_Operation> GerOnUserAuthList(int userID)
{
string CacheKey = "OnUserAuthListCashRa-" + userID.ToString();
if (CacheExtensions.CheckCache(CacheKey))//查找缓存是否存在
{
var userAuthList = CacheExtensions.GetCache<List<TBL_UTS_Manage_UserAuth_Operation>>(CacheKey);
return userAuthList;
}
else
{
var db = new Uts_ManageEntities();
var onAccountAuth = db.TBL_UTS_Manage_UserAuth_Operation.Where(a => a.UserID == userID).ToList();
if (onAccountAuth != null && onAccountAuth.Count() > 0)
{
CacheExtensions.SetCache(CacheKey, onAccountAuth);
return onAccountAuth;
}
}
return null;
}
#endregion
#region
/// <summary>
/// 获取当前用户当前库权限
/// </summary>
/// <returns></returns>
public static TBL_UTS_Manage_UserAuth_Operation GerOnUserAuth(int onUserID)
{
string CustomerCacheKey = "UserCustomerCashRa-" + onUserID.ToString();
if (CacheExtensions.CheckCache(CustomerCacheKey))//查找缓存是否存在
{
var id = CacheExtensions.GetCache<int>(CustomerCacheKey);//当前库ID
var onUserAuthList = GerOnUserAuthList(onUserID);
if (onUserAuthList != null && onUserAuthList.Count() > 0)
{
return onUserAuthList.SingleOrDefault(x => x.UserID == onUserID && x.DatabaseID == id);
}
}
return null;
}
#endregion
#region
/// <summary>
/// 获取用户当前选择库信息
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns></returns>
public static TBL_UTS_Manage_DBList GerOnUserCustomer()
{
//var onCustomer = System.Web.HttpContext.Current.Session[onUserOperationSessionName];
var onCustomer = CacheHelp.GetUserOperation(Umodel.UserName);
if (onCustomer != 0)
{
return cacheSysDBList.SingleOrDefault(x => x.ID == onCustomer);
}
return null;
}
public static TBL_UTS_Manage_DBList GerOnUserCustomer(System.Web.HttpContext context)
{
//var onCustomer = context.Session[onUserOperationSessionName];
var onCustomer = CacheHelp.GetUserOperation(Umodel.UserName);
if (onCustomer != 0)
{
return cacheSysDBList.SingleOrDefault(x => x.ID == onCustomer);
}
return null;
}
#endregion
#region
/// <summary>
/// 获取用户当前选择库信息
/// </summary>
/// <param name="userID">用户ID</param>
/// <returns></returns>
public static DBCofinStrModel GerOnUserDBCofinStr()
{
//var onCustomer = System.Web.HttpContext.Current.Session[onUserOperationSessionName];
var onCustomer = CacheHelp.GetUserOperation(Umodel.UserName);
if (onCustomer != 0)
{
return cacheSysDBCofinStrList.SingleOrDefault(x => x.ID == onCustomer);
}
return null;
}
public static DBCofinStrModel GerOnUserDBCofinStr(System.Web.HttpContext context)
{
//var onCustomer = context.Session[onUserOperationSessionName];
var umodel= UserLoginHelper.CurrentUserAsync(context);
var onCustomer = CacheHelp.GetUserOperation(umodel.UserName);
if (onCustomer != 0)
{
return cacheSysDBCofinStrList.SingleOrDefault(x => x.ID == onCustomer);
}
return null;
}
#endregion
#region
/// <summary>
/// 获取用户当前选择数据库连接串
/// </summary>
/// <returns></returns>
public static string GerOnUserCofin()
{
var connectionString = "";
connectionString = GerOnUserDBCofinStr().CofinStr;
if (!String.IsNullOrEmpty(connectionString))
{
return connectionString;
}
return System.Configuration.ConfigurationManager.ConnectionStrings["Uts_Manage"].ConnectionString;
}
public static string GerOnUserCofin(System.Web.HttpContext context)
{
var connectionString = "";
connectionString = GerOnUserDBCofinStr(context).CofinStr;
if (!String.IsNullOrEmpty(connectionString))
{
return connectionString;
}
return System.Configuration.ConfigurationManager.ConnectionStrings["Uts_Manage"].ConnectionString;
}
#endregion
#region
/// <summary>
/// 添加用户
/// </summary>
/// <param name="fc">前端窗体数据</param>
/// <param name="entity"></param>
/// <returns></returns>
public static ReturnResult AddUser(FormCollection fc, TBL_UTS_Manage_User entity)
{
ReturnResult result = new ReturnResult();
try
{
//初始化参数
string passwordconfirm = fc["confirmpassword"]; //确认登录密码
string[] haveDBName = new string[0];
if (!string.IsNullOrEmpty(fc["haveDBName"]))
{
haveDBName = fc["haveDBName"].Split(','); //可查数据库
}
//必填项
if (string.IsNullOrEmpty(entity.Password)) throw new CustomException("登录密码不能为空");
if (string.IsNullOrEmpty(passwordconfirm)) throw new CustomException("确认登录密码不能为空");
if (passwordconfirm != entity.Password) throw new CustomException("登录密码与确认登录密码不一致");
//验证项
if (!Regex.IsMatch(entity.UserName, @"^[A-Za-z0-9_]+$")) throw new CustomException("会员编号只能为字母、数字和下划线");
if (entity.UserName.Length > 20) throw new CustomException("会员编号长度超过20个字符");
Uts_ManageEntities db = new Uts_ManageEntities();
//唯一项
if (db.TBL_UTS_Manage_User.Where(x => x.UserName == entity.UserName.Trim()).Count() > 0) throw new CustomException("用户名已被使用");
//初始化参数
entity.IsValid = true;
entity.IsAdmin = false;
//注册后完善
entity.PlaintextPwd = entity.Password;
entity.Password = entity.Password.ToMD5().ToMD5();
entity.CreateTime = DateTime.Now;
//将数据添加到EF,并且标记为添加标记,返回受影响的行数。
db.TBL_UTS_Manage_User.Add(entity);
//SaveChanges()数据保存到数据库,根据前面的标记生成对应的Sql语句交给数据库执行。
db.SaveChanges();
//向权限表添加数据
if (haveDBName.Length > 0)
{
for (var i = 0; i < haveDBName.Length; i++)
{
db.TBL_UTS_Manage_UserAuth_Operation.Add(new TBL_UTS_Manage_UserAuth_Operation
{
UserID = entity.ID,
DatabaseID = haveDBName[i].ToInt(),
DatabaseName = cacheSysDBList.SingleOrDefault(x => x.ID == haveDBName[i].ToInt()).DatabaseName,
});
}
db.SaveChanges();
}
CacheHelp.ClearUserAuthList();
result.Status = 200;
}
catch (CustomException ex)
{
result.Message = ex.Message.ToString();
}
catch (DbEntityValidationException ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
//Logs.WriteErrorLog(ex);
LogHelp.WriteExceptionLog(ex);
}
catch (Exception ex)
{
result.Message = "网络系统繁忙,请稍候再试!";
//Logs.WriteErrorLog(ex);
LogHelp.WriteExceptionLog(ex);
}
return result;
}
#endregion
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("AUTS.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AUTS.Services")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("56438f1c-ba3a-4272-964e-c6739ae0b4ec")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Tool
{
public class DateTimeDiff
{
public DateTimeDiff()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 把秒转换成分钟
/// </summary>
/// <returns></returns>
public static int SecondToMinute(int Second)
{
decimal mm = (decimal)((decimal)Second / (decimal)60);
return Convert.ToInt32(Math.Ceiling(mm));
}
/// <summary>
/// 计算两个时间的时间间隔
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <param name="DateTimeNew">较后的日期和时间</param>
/// <returns></returns>
public static string DateDiff(DateTime DateTimeOld, DateTime DateTimeNew)
{
string dateDiff = "";
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTimeNew.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int day = ts.Days;
int hou = ts.Hours;
int minu = ts.Minutes;
int sec = ts.Seconds;
if (day > 0)
{
if (day > 30)
{
if (day > 364)
{
dateDiff += day / 365 + "年";
}
else
{
dateDiff += day / 30 + "个月";
}
}
else
{
dateDiff += day.ToString() + "天";
}
}
else
{
if (hou > 0)
{
dateDiff += hou.ToString() + "小时";
}
else
{
if (minu > 0)
{
dateDiff += minu.ToString() + "分钟";
}
else
{
if (sec > 0)
{
dateDiff += sec.ToString() + "秒";
}
else
{
dateDiff += "0秒";
}
}
}
}
if (DateTimeNew.CompareTo(DateTimeOld) > 0)
{
dateDiff += "前";
}
else
{
dateDiff += "后";
}
return dateDiff;
}
/// <summary>
/// 返回两个日期之间的时间间隔y年份间隔、M月份间隔、d天数间隔、h小时间隔、m分钟间隔、s秒钟间隔、ms微秒间隔
/// </summary>
/// <param name="Date1">开始日期</param>
/// <param name="Date2">结束日期</param>
/// <param name="Interval">间隔标志</param>
/// <returns>返回间隔标志指定的时间间隔</returns>
public static int DateDiff(System.DateTime Date1, System.DateTime Date2, string Interval)
{
double dblYearLen = 365;//年的长度365天
double dblMonthLen = (365 / 12);//每个月平均的天数
System.TimeSpan objT;
objT = Date2.Subtract(Date1);
switch (Interval)
{
case "y"://返回日期的年份间隔
return System.Convert.ToInt32(objT.Days / dblYearLen);
case "M"://返回日期的月份间隔
return System.Convert.ToInt32(objT.Days / dblMonthLen);
case "d"://返回日期的天数间隔
return objT.Days;
case "h"://返回日期的小时间隔
return objT.Hours;
case "m"://返回日期的分钟间隔
return objT.Minutes;
case "s"://返回日期的秒钟间隔
return objT.Seconds;
case "ms"://返回时间的微秒间隔
return objT.Milliseconds;
default:
break;
}
return 0;
}
/// <summary>
///判断是否于1分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool DateDiff_minu(DateTime DateTimeOld)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > 1)
{
return true;
}
else
{
return false;
}
}
/// <summary>
///判断是否于m分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool DateDiff_minu(DateTime DateTimeOld, int m)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > m)
{
return true;
}
else
{
return false;
}
}
public static bool DateDiff_1minu(DateTime DateTimeOld)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Seconds;
if (minu > 10)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 与当前时间比较,重载时间比较函数,只有一个参数
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static string DateDiff(DateTime DateTimeOld)
{
return DateDiff(DateTimeOld, DateTime.Now);
}
/// <summary>
/// 日期比较,返回精确的几分几秒
/// </summary>
/// <param name="DateTime1">较早的日期和时间</param>
/// <param name="DateTime2">较迟的日期和时间</param>
/// <returns></returns>
public static string DateDiff_full(DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = null;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒";
return dateDiff;
}
/// <summary>
/// 时间比较,返回精确的几秒
/// </summary>
/// <param name="DateTime1">较早的日期和时间</param>
/// <param name="DateTime2">较迟的日期和时间</param>
/// <returns></returns>
public static int DateDiff_Sec(DateTime DateTime1, DateTime DateTime2)
{
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int dateDiff = ts.Days * 86400 + ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
return dateDiff;
}
/// <summary>
/// 日期比较
/// </summary>
/// <param name="today">当前日期</param>
/// <param name="writeDate">输入日期</param>
/// <param name="n">比较天数</param>
/// <returns>大于天数返回true小于返回false</returns>
public static bool CompareDate(string today, string writeDate, int n)
{
DateTime Today = Convert.ToDateTime(today);
DateTime WriteDate = Convert.ToDateTime(writeDate);
WriteDate = WriteDate.AddDays(n);
if (Today >= WriteDate)
return false;
else
return true;
}
public static string FormatProgress(DateTime StartTime, DateTime EndTime)
{
if (DateTime.Now > DateTime.Parse(EndTime.ToShortDateString() + " 23:59:59"))
return "活动结束";
else if (DateTime.Now < DateTime.Parse(StartTime.ToShortDateString() + " 0:0:0"))
return "即将开始";
else
{
int totalDay = DateTimeDiff.DateDiff(StartTime, EndTime, "d");
int inDay = DateTimeDiff.DateDiff(StartTime, DateTime.Now, "d");
if ((float)inDay / (float)totalDay < 0.2f)
return "刚刚开始";
else if ((float)inDay / (float)totalDay >= 0.2f && (float)inDay / (float)totalDay < 0.4)
return "正在进行";
else if ((float)inDay / (float)totalDay >= 0.4 && (float)inDay / (float)totalDay < 0.6)
return "活动过半";
else if ((float)inDay / (float)totalDay > 0.6 && (float)inDay / (float)totalDay <= 0.8)
return "进入尾声";
else
return "即将结束";
}
}
// 时间戳转为C#格式时间
public static DateTime StampToDateTime(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
// DateTime时间格式转换为Unix时间戳格式
public static double DateTimeToStamp(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (time - startTime).TotalMilliseconds;
}
/// <summary>
///判断是否于多少分钟之前
/// </summary>
/// <param name="DateTimeOld">较早的日期和时间</param>
/// <returns></returns>
public static bool allDateDiff_minu(DateTime DateTimeOld, int m)
{
TimeSpan ts1 = new TimeSpan(DateTimeOld.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
int minu = ts.Minutes;
if (minu > m)
{
return true;
}
else
{
return false;
}
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Tool
{
/// <summary>
/// 实体帮助
/// </summary>
public static class ModelHelper
{
/// <summary>
/// 获取实体属性名
/// </summary>
/// <returns></returns>
public static string GetModelPropertyName<T>() where T : class, new()
{
string nameStr = "";
foreach (PropertyInfo pi in (new T()).GetType().GetProperties())
{
//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
var name = pi.Name;
//var value = pi.GetValue(list, null);//用pi.GetValue获得值
//var type = value?.GetType() ?? typeof(object);//获得属性的类型
nameStr += "`" + name + "`,";
}
return nameStr.Substring(0, nameStr.Length - 1);//nameStr; 去除最后一个逗号
}
public static List<Dictionary<string, object>> TableToRow(DataTable tbl)
{
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
foreach (DataRow Row in tbl.Rows)//循环行
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < Row.ItemArray.Length; i++)
{
row.Add(tbl.Columns[i].ColumnName, Row[i].ToString());
}
rows.Add(row);
}
return rows;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Tool
{
public class ComputerHelp
{
}
}

View File

@@ -0,0 +1,162 @@
using AUTS.Services.Extensions;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace AUTS.Services.Tool
{
/// <summary>
/// web.config操作类
/// Copyright (C) Maticsoft
/// </summary>
public sealed class ConfigHelper
{
/// <summary>
/// 得到AppSettings中的配置字符串信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetConfigString(string key)
{
string CacheKey = "AppSettings-" + key;
object objModel = CacheExtensions.GetCache<object>(CacheKey);
if (objModel == null)
{
try
{
objModel = ConfigurationManager.AppSettings[key];
if (objModel != null)
{
CacheExtensions.SetCache(CacheKey, objModel, Enums.CacheTimeType.ByHours, 3);
}
}
catch
{ }
}
return objModel.ToString();
}
/// <summary>
/// 得到AppSettings中的配置Bool信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool GetConfigBool(string key)
{
bool result = false;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = bool.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 得到AppSettings中的配置Decimal信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static decimal GetConfigDecimal(string key)
{
decimal result = 0;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = decimal.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 得到AppSettings中的配置int信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int GetConfigInt(string key)
{
int result = 0;
string cfgVal = GetConfigString(key);
if (null != cfgVal && string.Empty != cfgVal)
{
try
{
result = int.Parse(cfgVal);
}
catch (FormatException)
{
// Ignore format exceptions.
}
}
return result;
}
/// <summary>
/// 修改AppSettings中的配置信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static void UpdatetConfig(string key, string value)
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppSettings = (AppSettingsSection)objConfig.GetSection("appSettings");
if (objAppSettings != null)
{
objAppSettings.Settings[key].Value = value;
objConfig.Save();
}
}
/// <summary>
/// 加载配置文件 app升级配置文件
/// </summary>
/// <returns></returns>
public static Dictionary<String, String> loadCfg()
{
string cfgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
+ Path.DirectorySeparatorChar + "appset" + Path.DirectorySeparatorChar + "appconfig.properties";
Dictionary<String, String> cfg = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader(cfgPath))
{
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
if (line.StartsWith("#"))
{
continue;
}
int startInd = line.IndexOf("=");
string key = line.Substring(0, startInd);
string val = line.Substring(startInd + 1, line.Length - (startInd + 1));
if (!cfg.ContainsKey(key) && !string.IsNullOrEmpty(val))
{
cfg.Add(key, val);
}
}
}
return cfg;
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AUTS.Services.Tool
{
/// <summary>
/// 枚举帮助类
/// </summary>
public static class EnumHelper
{
///// <summary>
///// 获取枚举的Short类型
///// </summary>
///// <param name="value"></param>
///// <returns></returns>
//public static short GetShortValue(Enum value)
//{
// return short.Parse(((int)Enum.Parse(value.GetType(), value.ToString())).ToString());
//}
///// <summary>
///// 得到枚举中文备注
///// </summary>
///// <param name="enumValue"></param>
///// <returns></returns>
//public static string GetEnumDesc(Enum enumValue)
//{
// string value = enumValue.ToString();
// FieldInfo field = enumValue.GetType().GetField(value);
// object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
// if (objs.Length == 0) //当描述属性没有时,直接返回名称
// return value;
// DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
// return descriptionAttribute.Description;
//}
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
namespace AUTS.Services.Tool
{
public class IPHelper
{
public static string GetIP()
{
if (HttpContext.Current == null)
{
throw new Exception("HttpContext.Current为null");
}
string ip = string.Empty;
if (!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_VIA"]))
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
if (string.IsNullOrEmpty(ip))
ip = Convert.ToString(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
return ip;
}
/// <summary>获取客户端的IP可以取到代理后的IP
///
/// </summary>
/// <returns></returns>
public static string GetClientIp()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(result))
{
//可能有代理
if (result.IndexOf(".", StringComparison.Ordinal) == -1)
result = null;
else
{
if (result.IndexOf(",", StringComparison.Ordinal) != -1)
{
//有“,”估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
foreach (string t in temparyip)
{
if (IsIpAddress(t)
&& t.Substring(0, 3) != "10."
&& t.Substring(0, 7) != "192.168"
&& t.Substring(0, 7) != "172.16.")
{
return t; //找到不是内网的地址
}
}
}
else if (IsIpAddress(result)) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP取IP
}
}
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
/// <summary>判断是否是IP地址格式 0.0.0.0
///
/// </summary>
/// <param name="str">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIpAddress(string str)
{
if (string.IsNullOrEmpty(str) || str.Length < 7 || str.Length > 15) return false;
const string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
using AUTS.Domain.Entities;
using AUTS.Services.Cache;
using System;
using System.Linq;
namespace AUTS.Services
{
public partial class DevManageHelp
{
public static void UdpDevServiceHandle(int sID)
{
var devService = CacheHelp.GetHashService(sID);
if (devService != null)
{
var thisTime = DateTime.Now;
TimeSpan ts = thisTime - (devService.ServiceLastActiveDateTime ?? thisTime);
if (ts.TotalSeconds > 30)
{
devService.ServiceOnlineDateTime = thisTime;
}
devService.ServiceLastActiveDateTime = thisTime;
CacheHelp.SetHashService(devService);
}
}
}
}

View File

@@ -0,0 +1,296 @@
using AUTS.Services.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AUTS.Services
{
public partial class UDPHelp
{
/// <summary>
/// 用于UDP发送的网络服务类Socket
/// </summary>
static Socket socketRecv = null;
/// <summary>
/// 本机IP端口信息
/// </summary>
static IPEndPoint localIpep = null;
/// <summary>
/// 开关在监听UDP报文阶段为true否则为false
/// </summary>
static bool IsUdpcRecvStart = false;
/// <summary>
/// 线程不断监听UDP报文
/// </summary>
static Thread thrRecv;
/// <summary>
/// 开启监听
/// </summary>
public static void StartReceive()
{
//if (!IsUdpcRecvStart) // 未监听的情况,开始监听
//{
//localIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7254); // 本机IP和监听端口号
localIpep = new IPEndPoint(IPAddress.Any, 5920); // 本机IP和监听端口号
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
//IPEndPoint[] ipEndPoints = ipProperties.GetActiveUdpListeners();
var portCount = ipProperties.GetActiveUdpListeners().Where(x => x.Port == 5920).Count();
if (portCount == 0)
{
socketRecv = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socketRecv.Bind(localIpep);
thrRecv = new Thread(new ThreadStart(ReceiveMessage)); //开辟一个新线程
if (thrRecv.ThreadState != ThreadState.Running)
{
thrRecv.Start();
IsUdpcRecvStart = true;
Logs.WriteTimingUDPLog("UDP监听器已成功启动,IP:" + localIpep);
}
}
//}
}
/// <summary>
/// 关闭监听
/// </summary>
public static void StopReceive()
{
if (IsUdpcRecvStart)
{
thrRecv.Abort(); // 必须先关闭这个线程,否则会异常
//udpcRecv.Close();
socketRecv.Close();
IsUdpcRecvStart = false;
Logs.WriteTimingUDPLog("UDP监听器已成功关闭");
}
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="obj"></param>
private static void ReceiveMessage()
{
while (IsUdpcRecvStart)
{
try
{
// 接收
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
byte[] data = new byte[256];
int len = socketRecv.ReceiveFrom(data, ref Remote);
string result = BitConverter.ToString(data, 0, len);
UdpMsgHandle(data, len, Remote);
Logs.WriteTimingUDPLog("UDP接收数据:{来源IP:" + Remote + " ,数据包:" + result + " }");
}
catch (Exception ex)
{
Logs.WriteErrorTimingUDPLog("UDP接收错误:", ex);
break;
}
}
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="obj"></param>
private static void SendMessage(object obj)
{
try
{
string message = (string)obj;
byte[] sendbytes = Encoding.Unicode.GetBytes(message);
IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8819); // 发送到的IP地址和端口号
socketRecv.SendTo(sendbytes, sendbytes.Length, SocketFlags.None, remoteIpep);
}
catch (Exception ex)
{
Logs.WriteErrorTimingUDPLog("UDP发送", ex);
}
}
/// <summary>
/// 处理UDP信息
/// </summary>
/// <param name="data"></param>
/// <param name="len"></param>
/// <param name="Remote"></param>
public static void UdpMsgHandle(byte[] data, int len, EndPoint Remote)
{
var keyNum = Convert.ToInt32(data[2]);//数据包长度
var checkValue = data[3];//校验位
Array.Clear(data, 3, 1);//data 从起始位置4 删除1个位置
var packetSum = AddMsgByte(data);//数据包累加
var checkSum = (byte)((255 - packetSum) & 0xFF);
if ((len - keyNum) == 5 && checkSum == checkValue)
{
var sID = BitConverter.ToInt32(data, 5);
DevManageHelp.UdpDevServiceHandle(sID);
IPEndPoint endpoint = Remote as IPEndPoint;
var ipByte = endpoint.Address.GetAddressBytes();
var retMsg = new byte[256];
Buffer.BlockCopy(data, 0, retMsg, 0, 3);
retMsg[4] = Convert.ToByte(data[4] + 0xA0);
Buffer.BlockCopy(ipByte, 0, retMsg, 5, ipByte.Length);
var num = AddMsgByte(retMsg);
retMsg[3] = (byte)((255 - num) & 0xFF);
socketRecv.SendTo(retMsg, len, SocketFlags.None, Remote);
}
}
/// <summary>
/// 累加十六进制数据
/// </summary>
/// <param name="retMsg"></param>
/// <returns></returns>
public static int AddMsgByte(byte[] retMsg)
{
//var len = retMsg.Length;
var num = 0;
for (var i = 0; i < retMsg.Length; i++)
{
num += retMsg[i];
}
return num;
}
}
public partial class UDPHelp_New
{
/// <summary>
/// 累加十六进制数据
/// </summary>
/// <param name="retMsg"></param>
/// <returns></returns>
public static int AddMsgByte(byte[] retMsg)
{
//var len = retMsg.Length;
var num = 0;
for (var i = 0; i < retMsg.Length; i++)
{
num += retMsg[i];
}
return num;
}
public static void CreatSocket()
{
try
{
int port = 5930;
string host = "127.0.0.1";
/**/
///创建终结点EndPoint
IPAddress ip = IPAddress.Parse(host); //把ip地址字符串转换为IPAddress类型的实例
IPEndPoint ipe = new IPEndPoint(ip, port); //用指定的端口和ip初始化IPEndPoint类的新实例
/**/
///创建终结点EndPoint
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
foreach (IPAddress address in Dns.GetHostEntry(host).AddressList)
{
if (address.AddressFamily.ToString() == "InterNetwork")
{
IPAddress hostIP = address;
IPEndPoint ipe2 = new IPEndPoint(address, 5930);
socket.Bind(ipe2); //绑定EndPoint对像
//socket.Listen(0); //开始监听
//接受到client连接为此连接建立新的socket并接受信息
while (true) //定义循环以便可以简历N次连接
{
Socket temp = socket.Accept(); //为新建连接创建新的socket
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
byte[] recvBytes = new byte[256];
int bytes = temp.ReceiveFrom(recvBytes, ref Remote); //从客户端接受信息
var sID = BitConverter.ToInt32(recvBytes, 5);
DevManageHelp.UdpDevServiceHandle(sID);
string recvStr = BitConverter.ToString(recvBytes, 0, bytes);
var retMsg = UdpMsgHandle_New(recvBytes, bytes, Remote);
temp.Send(retMsg, bytes, 0);//返回信息给客户端
if (temp != null)
temp.Close();
Logs.WriteTimingUDPLog("UDP接收-IP:" + Remote + ",数据包:" + recvStr);
}
}
}
}
catch (Exception ex)
{
Logs.WriteErrorTimingUDPLog("UDP监听器开启错误:", ex);
}
}
public static byte[] UdpMsgHandle_New(byte[] data, int len, EndPoint Remote)
{
var retMsg = new byte[256];
var keyNum = Convert.ToInt32(data[2]);
if ((len - keyNum) == 5)
{
IPEndPoint endpoint = Remote as IPEndPoint;
//IPAddress ip = endpoint.Address;
var ipByte = endpoint.Address.GetAddressBytes();
//var ipByte = new byte[] { 183, 12, 223, 210 };
retMsg[0] = data[0];
retMsg[1] = data[1];
retMsg[2] = data[2];
retMsg[4] = Convert.ToByte(data[4].ToInt() + 160);
retMsg[5] = ipByte[0];
retMsg[6] = ipByte[1];
retMsg[7] = ipByte[2];
retMsg[8] = ipByte[3];
var num = AddMsgByte(retMsg);
retMsg[3] = (byte)((255 - num) & 0xFF);
}
return retMsg;
}
}
}

View File

@@ -0,0 +1,243 @@
using AUTS.Domain.Application;
using AUTS.Domain.Entities;
using AUTS.Services.Extensions;
using AUTS.Services.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
namespace AUTS.Services
{
public static class UserLoginHelper
{
//登录缓存键前缀
/// <summary>
/// 登录缓存键前缀
/// </summary>
//static string CacheUserName { get { return typeof(TBL_UTS_Manage_UserList).Name + "_"; } }
static string CookieName_User = (ConfigHelper.GetConfigString("DBName") + "_User").ToMD5();
static string CookieName_Token = (ConfigHelper.GetConfigString("DBName") + "_Token").ToMD5();
public static TBL_UTS_Manage_User GetUserLoginBy(string keyword, string password)
{
//string pwd = password.ToMD5().ToMD5();
string pwd = password.ToMD5().ToMD5();
//TBL_UTS_Manage_User matchedSList = SqlSugarBase.Db.Queryable<TBL_UTS_Manage_User>().First(x=>x.UserName== keyword && x.Password == pwd);
//if (matchedSList != null)
//{
// HttpContext.Current.Session[CookieName_User] = matchedSList;
// CookieExtensions.WriteCookie(CookieName_User, keyword, 60);
// CookieExtensions.WriteCookie(CookieName_Token, keyword.ToMD5() + "" + pwd, 60);
// return matchedSList;
//}
using (var db = new Uts_ManageEntities())
{
//var account = db.TBL_UTS_Manage_User.SingleOrDefault(a => (a.UserName == keyword.Trim()) && a.Password == password);
var account = db.TBL_UTS_Manage_User.SingleOrDefault(a => (a.UserName == keyword.Trim()) && a.Password == pwd);
if (account != null)
{
HttpContext.Current.Session[CookieName_User] = account;
CookieExtensions.WriteCookie(CookieName_User, keyword, 60);
CookieExtensions.WriteCookie(CookieName_Token, keyword.ToMD5() + "" + pwd, 60);
return account;
}
}
return null;
}
//获取当前会员登录对象
/// <summary>
/// 获取当前会员登录对象
/// <para>当没登陆或者登录信息不符时,这里返回 null </para>
/// </summary>
/// <returns></returns>
public static TBL_UTS_Manage_User CurrentUser()
{
//校验用户是否已经登录
var user = HttpContext.Current.Session[CookieName_User] as TBL_UTS_Manage_User;
if (user != null) return user;
else
{
if (HttpContext.Current.Request.Cookies[CookieName_User] != null && HttpContext.Current.Request.Cookies[CookieName_Token] != null)
{
string keyword = HttpContext.Current.Request.Cookies[CookieName_User].Value;
string token = HttpContext.Current.Request.Cookies[CookieName_Token].Value;
string pwd = token.Substring(32);
var db = new Uts_ManageEntities();
var account = db.TBL_UTS_Manage_User.SingleOrDefault(a => a.UserName == keyword.Trim() && a.Password == pwd);
if (account != null)
{
return account;
}
}
}
return null;
}
/// <summary>
/// 控制器名
/// </summary>
/// <returns></returns>
public static string Controller()
{
//校验用户是否已经登录
var controllerName = CookieExtensions.GetCookie("controllerName");
if (controllerName != null) return controllerName;
return null;
}
/// <summary>
/// 管理名称
/// </summary>
/// <returns></returns>
public static string ManageName()
{
//校验用户是否已经登录
var ManageName = CookieExtensions.GetCookie("ManageName");
if (ManageName != null) return ManageName;
return null;
}
/// <summary>
/// 方法名
/// </summary>
/// <returns></returns>
public static string ActionName()
{
//校验用户是否已经登录
var actionName = CookieExtensions.GetCookie("actionName");
if (actionName != null) return actionName;
return null;
}
/// <summary>
/// 只读方法名
/// </summary>
/// <returns></returns>
public static string ReadOnlyActionName()
{
//校验用户是否已经登录
var actionName = CookieExtensions.GetCookie("actionReadOnly");
if (actionName != null) return actionName;
return null;
}
//获取当前会员登录对象 异步
/// <summary>
/// 获取当前会员登录对象
/// <para>当没登陆或者登录信息不符时,这里返回 null </para>
/// </summary>
/// <returns></returns>
public static TBL_UTS_Manage_User CurrentUserAsync(System.Web.HttpContext context)
{
//校验用户是否已经登录
var user = context.Session[CookieName_User] as TBL_UTS_Manage_User;
if (user != null) return user;
else
{
if (context.Request.Cookies[CookieName_User] != null && context.Request.Cookies[CookieName_Token] != null)
{
string keyword = context.Request.Cookies[CookieName_User].Value;
string token = context.Request.Cookies[CookieName_Token].Value;
string pwd = token.Substring(32);
var db = new Uts_ManageEntities();
var account = db.TBL_UTS_Manage_User.SingleOrDefault(a => a.UserName == keyword.Trim() && a.Password == pwd);
if (account != null)
{
return account;
}
}
}
return null;
}
//登出
/// <summary>
/// 登出
/// </summary>
public static void UserLogout()
{
if (CheckUserLogin())
{
//获取会员ID
var id = HttpContext.Current.User.Identity.Name;
FormsAuthentication.SignOut();
RemoveUser(id);
}
}
//移除指定会员ID的登录缓存
/// <summary>
/// 移除指定会员ID的登录缓存
/// </summary>
/// <param name="ID"></param>
public static void RemoveUser(string ID)
{
//MvcCore.Extensions.CacheExtensions.ClearCache(cacheUserName + ID);
HttpContext.Current.Session.Clear();
HttpCookie hc1 = HttpContext.Current.Request.Cookies[CookieName_User];
hc1.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(hc1);
HttpCookie hc2 = HttpContext.Current.Request.Cookies[CookieName_Token];
hc2.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(hc2);
}
//判断当前访问是否有会员登录
/// <summary>
/// 判断当前访问是否有会员登录
/// </summary>
/// <returns></returns>
public static bool CheckUserLogin()
{
if (HttpContext.Current.Request.Cookies[CookieName_User] != null && HttpContext.Current.Request.Cookies[CookieName_Token] != null)
{
string keyword = HttpContext.Current.Request.Cookies[CookieName_User].Value;
string token = HttpContext.Current.Request.Cookies[CookieName_Token].Value;
string pwd = token.Substring(32);
var db = new Uts_ManageEntities();
try
{
var account = db.TBL_UTS_Manage_User.SingleOrDefault(a => a.UserName == keyword.Trim() && a.Password == pwd);
if (account != null) return true;
}
catch (Exception ex)
{
throw;
}
}
return false;
}
////当前在线会员数量
///// <summary>
///// 当前在线会员数量
///// </summary>
//public static int UserCount
//{
// get
// {
// return CacheExtensions.GetAllCache().Where(s => s.StartsWith(CacheUserName)).Count();
// }
//}
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.2.0" targetFramework="net461" />
<package id="Google.Protobuf" version="3.21.9" targetFramework="net48" />
<package id="K4os.Compression.LZ4" version="1.3.5" targetFramework="net48" />
<package id="K4os.Compression.LZ4.Streams" version="1.3.5" targetFramework="net48" />
<package id="K4os.Hash.xxHash" version="1.0.8" targetFramework="net48" />
<package id="log4net" version="2.0.8" targetFramework="net461" />
<package id="MySql.Data" version="6.9.12" targetFramework="net48" />
<package id="MySql.Data.Entity" version="6.9.11" targetFramework="net461" />
<package id="Newtonsoft.Json" version="11.0.1" targetFramework="net461" />
<package id="Portable.BouncyCastle" version="1.9.0" targetFramework="net48" />
<package id="SqlSugar" version="5.1.2.7" targetFramework="net461" />
<package id="StackExchange.Redis" version="1.2.6" targetFramework="net461" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.IO.Pipelines" version="5.0.2" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
</packages>